Python pyVmomi.vim.Task() Examples

The following are 17 code examples of pyVmomi.vim.Task(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyVmomi.vim , or try the search function .
Example #1
Source File: vmdk_ops.py    From vsphere-storage-for-docker with Apache License 2.0 6 votes vote down vote up
def getTaskList(prop_collector, tasks):
    # Create filter
    obj_specs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task)
                 for task in tasks]
    property_spec = vmodl.query.PropertyCollector.PropertySpec(type=vim.Task,
                                                               pathSet=[],
                                                               all=True)
    filter_spec = vmodl.query.PropertyCollector.FilterSpec()
    filter_spec.objectSet = obj_specs
    filter_spec.propSet = [property_spec]
    return prop_collector.CreateFilter(filter_spec, True)

#-----------------------------------------------------------
#
# Support for 'wait for task completion'
# Keep it here to keep a single file for now
# 
Example #2
Source File: virtualcenter.py    From wrapanapi with MIT License 6 votes vote down vote up
def cpu_hot_plug(self, value):
        """
        Set cpuHotPlug (enabled/disabled) for VM/Instance.

        Args:
            value (bool): cpu hot plug state
        """
        if self.cpu_hot_plug != value:
            if self.is_stopped:
                spec = vim.vm.ConfigSpec()
                spec.cpuHotAddEnabled = value
                task = self.raw.ReconfigVM_Task(spec)

                try:
                    wait_for(lambda: task.info.state not in ["running", "queued"])
                except TimedOutError:
                    self.logger.exception("Task did not go to success state: %s", task)
            else:
                raise VMInstanceNotStopped(self.name, "cpuHotPlug") 
Example #3
Source File: virtualcenter.py    From wrapanapi with MIT License 6 votes vote down vote up
def memory_hot_plug(self, value):
        """
        Set memoryHotPlug (enabled/disabled) for VM/Instance

        Args:
            value (bool): memory hot plug state
        """
        if self.memory_hot_plug != value:
            if self.is_stopped:
                spec = vim.vm.ConfigSpec()
                spec.memoryHotAddEnabled = value
                task = self.raw.ReconfigVM_Task(spec)

                try:
                    wait_for(lambda: task.info.state not in ["running", "queued"])
                except TimedOutError:
                    self.logger.exception("Task did not go to success state: %s", task)
            else:
                raise VMInstanceNotStopped(self.name, "memoryHotPlug") 
Example #4
Source File: vSphere.py    From im with GNU General Public License v3.0 5 votes vote down vote up
def CreateContainerView(self, rootFolder, type_list, flag):
        container = MagicMock()
        c = MagicMock()
        container.view = [c]
        if type_list[0] == vim.Datastore:
            c.name = "datastore"
        elif type_list[0] == vim.Network:
            c.name = "vsnet1"
            c.summary.ipPoolName = "ippool1"
            c2 = MagicMock()
            c2.name = "vsnet2"
            c2.summary.ipPoolName = "ippool2"
            container.view.append(c2)
        elif type_list[0] == vim.VirtualMachine:
            c.name = "vm-template"
            c.Clone.return_value = vim.Task("CreateVM")
            c.Suspend.return_value = vim.Task("SuspendVM")
            c.PowerOn.return_value = vim.Task("PowerOnVM")
            c.Reset.return_value = vim.Task("ResetVM")
            c.PowerOff.return_value = vim.Task("PowerOffVM")
            c.Destroy.return_value = vim.Task("DestroyVM")
            c.summary.runtime.powerState = self.vm_state
            c.runtime.powerState = self.vm_state
            nic1 = MagicMock()
            nic1.ipAddress = "10.0.0.1"
            nic2 = MagicMock()
            nic2.ipAddress = "8.8.8.8"
            c.guest.net = [nic1, nic2]
            dev1 = MagicMock()
            dev2 = vim.vm.device.VirtualSCSIController()
            c.config.hardware.device = [dev1, dev2]
            dev1.backing.fileName = ""
            dev1.unitNumber = 1
        else:
            raise Exception("Invalid type")

        return container 
Example #5
Source File: vSphere.py    From im with GNU General Public License v3.0 5 votes vote down vote up
def test_40_stop(self, conn, pvim):
        auth = Authentication([{'id': 'vsp', 'type': 'vSphere', 'host': 'https://vspherehost',
                                'username': 'user', 'password': 'password'}])
        vsphere_cloud = self.get_vsphere_cloud()

        smatconn = MagicMock()
        conn.return_value = smatconn
        retcont = MagicMock()
        smatconn.RetrieveContent.return_value = retcont
        retcont.viewManager.CreateContainerView.side_effect = self.CreateContainerView
        pvim.VirtualMachine = vim.VirtualMachine

        pvim.TaskInfo.State.success = vim.TaskInfo.State.success
        pvim.Task = vim.Task
        property_collector = MagicMock()
        smatconn.content.propertyCollector = property_collector
        update = MagicMock()
        property_collector.WaitForUpdates.return_value = update
        fs = MagicMock()
        update.filterSet = [fs]
        objs = MagicMock()
        fs.objectSet = [objs]
        change = MagicMock()
        objs.changeSet = [change]
        objs.obj = vim.Task("SuspendVM")
        change.name = "info.state"
        change.val = vim.TaskInfo.State.success

        inf = MagicMock()
        vm = VirtualMachine(inf, "vm-template", vsphere_cloud.cloud, "", "", vsphere_cloud, 1)

        success, _ = vsphere_cloud.stop(vm, auth)

        self.assertTrue(success, msg="ERROR: stopping VM info.")
        self.assertNotIn("ERROR", self.log.getvalue(), msg="ERROR found in log: %s" % self.log.getvalue()) 
Example #6
Source File: vSphere.py    From im with GNU General Public License v3.0 5 votes vote down vote up
def test_50_start(self, conn, pvim):
        auth = Authentication([{'id': 'vsp', 'type': 'vSphere', 'host': 'https://vspherehost',
                                'username': 'user', 'password': 'password'}])
        vsphere_cloud = self.get_vsphere_cloud()

        smatconn = MagicMock()
        conn.return_value = smatconn
        retcont = MagicMock()
        smatconn.RetrieveContent.return_value = retcont
        retcont.viewManager.CreateContainerView.side_effect = self.CreateContainerView
        pvim.VirtualMachine = vim.VirtualMachine

        pvim.TaskInfo.State.success = vim.TaskInfo.State.success
        pvim.Task = vim.Task
        property_collector = MagicMock()
        smatconn.content.propertyCollector = property_collector
        update = MagicMock()
        property_collector.WaitForUpdates.return_value = update
        fs = MagicMock()
        update.filterSet = [fs]
        objs = MagicMock()
        fs.objectSet = [objs]
        change = MagicMock()
        objs.changeSet = [change]
        objs.obj = vim.Task("PowerOnVM")
        change.name = "info.state"
        change.val = vim.TaskInfo.State.success
        inf = MagicMock()
        vm = VirtualMachine(inf, "vm-template", vsphere_cloud.cloud, "", "", vsphere_cloud, 1)

        self.vm_state = "suspended"
        success, _ = vsphere_cloud.start(vm, auth)
        self.vm_state = "poweredOn"

        self.assertTrue(success, msg="ERROR: stopping VM info.")
        self.assertNotIn("ERROR", self.log.getvalue(), msg="ERROR found in log: %s" % self.log.getvalue()) 
Example #7
Source File: vSphere.py    From im with GNU General Public License v3.0 5 votes vote down vote up
def test_52_reboot(self, conn, pvim):
        auth = Authentication([{'id': 'vsp', 'type': 'vSphere', 'host': 'https://vspherehost',
                                'username': 'user', 'password': 'password'}])
        vsphere_cloud = self.get_vsphere_cloud()

        smatconn = MagicMock()
        conn.return_value = smatconn
        retcont = MagicMock()
        smatconn.RetrieveContent.return_value = retcont
        retcont.viewManager.CreateContainerView.side_effect = self.CreateContainerView
        pvim.VirtualMachine = vim.VirtualMachine

        pvim.TaskInfo.State.success = vim.TaskInfo.State.success
        pvim.Task = vim.Task
        property_collector = MagicMock()
        smatconn.content.propertyCollector = property_collector
        update = MagicMock()
        property_collector.WaitForUpdates.return_value = update
        fs = MagicMock()
        update.filterSet = [fs]
        objs = MagicMock()
        fs.objectSet = [objs]
        change = MagicMock()
        objs.changeSet = [change]
        objs.obj = vim.Task("ResetVM")
        change.name = "info.state"
        change.val = vim.TaskInfo.State.success
        inf = MagicMock()
        vm = VirtualMachine(inf, "vm-template", vsphere_cloud.cloud, "", "", vsphere_cloud, 1)

        success, _ = vsphere_cloud.reboot(vm, auth)

        self.assertTrue(success, msg="ERROR: rebooting VM info.")
        self.assertNotIn("ERROR", self.log.getvalue(), msg="ERROR found in log: %s" % self.log.getvalue()) 
Example #8
Source File: virtualcenter.py    From wrapanapi with MIT License 5 votes vote down vote up
def destroy_folder(self, folder_name):
        """Delete a Vm folder under Datacenter

        Args:
            folder_name: Name of Vm Folder
            return: vim.Task
        """
        folder = self._search_folders_for_vm(folder_name)
        return folder.Destroy() 
Example #9
Source File: virtualcenter.py    From wrapanapi with MIT License 5 votes vote down vote up
def _task_wait(self, task):
        """
        Update a task and check its state. If the task state is not ``queued``, ``running`` or
        ``None``, then return the state. Otherwise return None.

        Args:
            task (pyVmomi.vim.Task): The task whose state is being monitored
        Returns:
            string: pyVmomi.vim.TaskInfo.state value if the task is not queued/running/None
        """
        task = self.get_updated_obj(task)
        if task.info.state not in ['queued', 'running', None]:
            return task.info.state 
Example #10
Source File: virtualcenter.py    From wrapanapi with MIT License 5 votes vote down vote up
def get_task_status(self, task):
        """Update a task and return its state, as a vim.TaskInfo.State string wrapper

        Args:
            task (pyVmomi.vim.Task): The task whose state is being returned
        Returns:
            string: pyVmomi.vim.TaskInfo.state value
        """
        task = self.get_updated_obj(task)
        return task.info.state 
Example #11
Source File: vsphere_blockdevice.py    From vsphere-flocker-driver with Apache License 2.0 4 votes vote down vote up
def _wait_for_tasks(self, tasks, si):
        """
        Given the service instance, si, and tasks, it returns after all the
        tasks are complete
        """
        pc = si.content.propertyCollector
        taskList = [str(task) for task in tasks]

        # Create filter
        objSpecs = [vmodl.query.PropertyCollector.ObjectSpec(
            obj=task) for task in tasks]
        propSpec = vmodl.query.PropertyCollector.PropertySpec(
            type=vim.Task, pathSet=[], all=True)
        filterSpec = vmodl.query.PropertyCollector.FilterSpec()
        filterSpec.objectSet = objSpecs
        filterSpec.propSet = [propSpec]
        filter = pc.CreateFilter(filterSpec, True)

        try:
            version, state = None, None

            # Loop looking for updates till the state moves to a completed
            # state.
            while len(taskList):
                update = pc.WaitForUpdates(version)
                for filterSet in update.filterSet:
                    for objSet in filterSet.objectSet:
                        task = objSet.obj
                        for change in objSet.changeSet:
                            if change.name == 'info':
                                state = change.val.state
                            elif change.name == 'info.state':
                                state = change.val
                            else:
                                continue

                            if not str(task) in taskList:
                                continue

                            if state == vim.TaskInfo.State.success:
                                logging.debug("{} ".format(task.info.result))
                                # Remove task from taskList
                                taskList.remove(str(task))
                            elif state == vim.TaskInfo.State.error:
                                raise task.info.error
            # Move to next version
            version = update.version
        finally:
            if filter:
                filter.Destroy() 
Example #12
Source File: ezmomi.py    From ezmomi with MIT License 4 votes vote down vote up
def WaitForTasks(self, tasks):
        """
        Given the service instance si and tasks, it returns after all the
        tasks are complete
        """
        pc = self.si.content.propertyCollector

        taskList = [str(task) for task in tasks]

        # Create filter
        objSpecs = [vmodl.query.PropertyCollector.ObjectSpec(
            obj=task) for task in tasks]
        propSpec = vmodl.query.PropertyCollector.PropertySpec(
            type=vim.Task, pathSet=[], all=True)
        filterSpec = vmodl.query.PropertyCollector.FilterSpec()
        filterSpec.objectSet = objSpecs
        filterSpec.propSet = [propSpec]
        filter = pc.CreateFilter(filterSpec, True)

        try:
            version, state = None, None

            # Loop looking for updates till the state moves to a
            # completed state.
            while len(taskList):
                update = pc.WaitForUpdates(version)
                for filterSet in update.filterSet:
                    for objSet in filterSet.objectSet:
                        task = objSet.obj
                        for change in objSet.changeSet:
                            if change.name == 'info':
                                state = change.val.state
                            elif change.name == 'info.state':
                                state = change.val
                            else:
                                continue

                            if state == vim.TaskInfo.State.success:
                                # Remove task from taskList
                                taskList.remove(str(task))
                            elif state == vim.TaskInfo.State.error:
                                raise task.info.error
                # Move to next version
                version = update.version
        finally:
            if filter:
                filter.Destroy() 
Example #13
Source File: tasks.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def wait_for_tasks(service_instance, tasks):
    """Given the service instance si and tasks, it returns after all the
   tasks are complete
   """
    property_collector = service_instance.content.propertyCollector
    task_list = [str(task) for task in tasks]
    # Create filter
    obj_specs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task)
                 for task in tasks]
    property_spec = vmodl.query.PropertyCollector.PropertySpec(type=vim.Task,
                                                               pathSet=[],
                                                               all=True)
    filter_spec = vmodl.query.PropertyCollector.FilterSpec()
    filter_spec.objectSet = obj_specs
    filter_spec.propSet = [property_spec]
    pcfilter = property_collector.CreateFilter(filter_spec, True)
    try:
        version, state = None, None
        # Loop looking for updates till the state moves to a completed state.
        while len(task_list):
            update = property_collector.WaitForUpdates(version)
            for filter_set in update.filterSet:
                for obj_set in filter_set.objectSet:
                    task = obj_set.obj
                    for change in obj_set.changeSet:
                        if change.name == 'info':
                            state = change.val.state
                        elif change.name == 'info.state':
                            state = change.val
                        else:
                            continue

                        if not str(task) in task_list:
                            continue

                        if state == vim.TaskInfo.State.success:
                            # Remove task from taskList
                            task_list.remove(str(task))
                        elif state == vim.TaskInfo.State.error:
                            raise task.info.error
            # Move to next version
            version = update.version
    finally:
        if pcfilter:
            pcfilter.Destroy() 
Example #14
Source File: create_and_remove_snapshot.py    From vmware-pyvmomi-examples with Apache License 2.0 4 votes vote down vote up
def wait_for_task(task, raiseOnError=True, si=None, pc=None):
    if si is None:
        si = GetSi()

    if pc is None:
        sc = si.RetrieveContent()
        pc = sc.propertyCollector

    # First create the object specification as the task object.
    objspec = vmodl.Query.PropertyCollector.ObjectSpec()
    objspec.SetObj(task)

    # Next, create the property specification as the state.
    propspec = vmodl.Query.PropertyCollector.PropertySpec()
    propspec.SetType(vim.Task);
    propspec.SetPathSet(["info.state"]);
    propspec.SetAll(True)

    # Create a filter spec with the specified object and property spec.
    filterspec = vmodl.Query.PropertyCollector.FilterSpec()
    filterspec.SetObjectSet([objspec])
    filterspec.SetPropSet([propspec])

    # Create the filter
    filter = pc.CreateFilter(filterspec, True)
   
    # Loop looking for updates till the state moves to a completed state.
    taskName = task.GetInfo().GetName()
    update = pc.WaitForUpdates(None)
    state = task.GetInfo().GetState()
    while state != vim.TaskInfo.State.success and \
            state != vim.TaskInfo.State.error:
        if (state == 'running') and (taskName.info.name != "Destroy"):
            # check to see if VM needs to ask a question, thow exception
            vm = task.GetInfo().GetEntity()
            if vm is not None and isinstance(vm, vim.VirtualMachine):
                qst = vm.GetRuntime().GetQuestion()
            if qst is not None:
                raise Exception("Task blocked, User Intervention required")
      
    update = pc.WaitForUpdates(update.GetVersion())
    state = task.GetInfo().GetState()
         
    filter.Destroy()
    if state == "error" and raiseOnError:
        raise task.GetInfo().GetError()
      
    return state 
Example #15
Source File: vm_power_ops.py    From vmware-pyvmomi-examples with Apache License 2.0 4 votes vote down vote up
def wait_for_task(task, raiseOnError=True, si=None, pc=None):
    if si is None:
        si = GetSi()

    if pc is None:
        sc = si.RetrieveContent()
        pc = sc.propertyCollector

    # First create the object specification as the task object.
    objspec = vmodl.Query.PropertyCollector.ObjectSpec()
    objspec.SetObj(task)

    # Next, create the property specification as the state.
    propspec = vmodl.Query.PropertyCollector.PropertySpec()
    propspec.SetType(vim.Task);
    propspec.SetPathSet(["info.state"]);
    propspec.SetAll(True)

    # Create a filter spec with the specified object and property spec.
    filterspec = vmodl.Query.PropertyCollector.FilterSpec()
    filterspec.SetObjectSet([objspec])
    filterspec.SetPropSet([propspec])

    # Create the filter
    filter = pc.CreateFilter(filterspec, True)
   
    # Loop looking for updates till the state moves to a completed state.
    taskName = task.GetInfo().GetName()
    update = pc.WaitForUpdates(None)
    state = task.GetInfo().GetState()
    while state != vim.TaskInfo.State.success and \
            state != vim.TaskInfo.State.error:
        if (state == 'running') and (taskName.info.name != "Destroy"):
            # check to see if VM needs to ask a question, thow exception
            vm = task.GetInfo().GetEntity()
            if vm is not None and isinstance(vm, vim.VirtualMachine):
                qst = vm.GetRuntime().GetQuestion()
            if qst is not None:
                raise Exception("Task blocked, User Intervention required")
      
    update = pc.WaitForUpdates(update.GetVersion())
    state = task.GetInfo().GetState()
         
    filter.Destroy()
    if state == "error" and raiseOnError:
        raise task.GetInfo().GetError()
      
    return state 
Example #16
Source File: vim_utils.py    From vsphere-automation-sdk-python with MIT License 4 votes vote down vote up
def wait_for_tasks(content, tasks):
    """
    Given the tasks, it returns after all the tasks are complete
    """
    taskList = [str(task) for task in tasks]

    # Create filter
    objSpecs = [
        vmodl.query.PropertyCollector.ObjectSpec(obj=task) for task in tasks
    ]
    propSpec = vmodl.query.PropertyCollector.PropertySpec(
        type=vim.Task, pathSet=[], all=True)
    filterSpec = vmodl.query.PropertyCollector.FilterSpec()
    filterSpec.objectSet = objSpecs
    filterSpec.propSet = [propSpec]
    task_filter = content.propertyCollector.CreateFilter(filterSpec, True)

    try:
        version, state = None, None

        # Loop looking for updates till the state moves to a completed state.
        while len(taskList):
            update = content.propertyCollector.WaitForUpdates(version)
            for filterSet in update.filterSet:
                for objSet in filterSet.objectSet:
                    task = objSet.obj
                    for change in objSet.changeSet:
                        if change.name == 'info':
                            state = change.val.state
                        elif change.name == 'info.state':
                            state = change.val
                        else:
                            continue

                        if not str(task) in taskList:
                            continue

                        if state == vim.TaskInfo.State.success:
                            # Remove task from taskList
                            taskList.remove(str(task))
                        elif state == vim.TaskInfo.State.error:
                            raise task.info.error
            # Move to next version
            version = update.version
    finally:
        if task_filter:
            task_filter.Destroy() 
Example #17
Source File: vSphere.py    From im with GNU General Public License v3.0 4 votes vote down vote up
def wait_for_tasks(service_instance, tasks):
        """
        Written by Michael Rice <michael@michaelrice.org>
        Github: https://github.com/michaelrice
        Website: https://michaelrice.github.io/
        Blog: http://www.errr-online.com/
        This code has been released under the terms of the Apache 2 licenses
        http://www.apache.org/licenses/LICENSE-2.0.html
        Helper module for task operations.

        Given the service instance si and tasks, it returns after all the
        tasks are complete
        """
        property_collector = service_instance.content.propertyCollector
        task_list = [str(task) for task in tasks]
        # Create filter
        property_spec = vmodl.query.PropertyCollector.PropertySpec(type=vim.Task,
                                                                   pathSet=[],
                                                                   all=True)
        obj_specs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task) for task in tasks]

        filter_spec = vmodl.query.PropertyCollector.FilterSpec()
        filter_spec.objectSet = obj_specs
        filter_spec.propSet = [property_spec]
        pcfilter = property_collector.CreateFilter(filter_spec, True)
        try:
            version, state = None, None
            # Loop looking for updates till the state moves to a completed state.
            while len(task_list):
                update = property_collector.WaitForUpdates(version)
                for filter_set in update.filterSet:
                    for obj_set in filter_set.objectSet:
                        task = obj_set.obj
                        for change in obj_set.changeSet:
                            if change.name == 'info':
                                state = change.val.state
                            elif change.name == 'info.state':
                                state = change.val
                            else:
                                continue

                            if not str(task) in task_list:
                                continue

                            if state == vim.TaskInfo.State.success:
                                # Remove task from taskList
                                task_list.remove(str(task))
                            elif state == vim.TaskInfo.State.error:
                                raise task.info.error
                # Move to next version
                version = update.version
        finally:
            if pcfilter:
                pcfilter.Destroy()