Example #1
0
    def _poll_task(self, task):
        """Poll the given task until completion.

        If the task completes successfully, the method returns the task info
        using the input event (param done). In case of any error, appropriate
        exception is set in the event.

        :param task: managed object reference of the task
        """
        LOG.debug("Invoking VIM API to read info of task: %s.", task)
        try:
            task_info = self.invoke_api(vim_util, 'get_object_property',
                                        self.vim, task, 'info')
        except exceptions.VimException:
            with excutils.save_and_reraise_exception():
                LOG.exception(
                    _LE("Error occurred while reading info of "
                        "task: %s."), task)
        else:
            if task_info.state in ['queued', 'running']:
                if hasattr(task_info, 'progress'):
                    LOG.debug("Task: %(task)s progress is %(progress)s%%.", {
                        'task': task,
                        'progress': task_info.progress
                    })
            elif task_info.state == 'success':
                LOG.debug("Task: %s status is success.", task)
                raise loopingcall.LoopingCallDone(task_info)
            else:
                error_msg = six.text_type(task_info.error.localizedMessage)
                error = task_info.error
                name = error.fault.__class__.__name__
                task_ex = exceptions.get_fault_class(name)(error_msg)
                raise task_ex
Example #2
0
    def _poll_task(self, task):
        """Poll the given task until completion.

        If the task completes successfully, the method returns the task info
        using the input event (param done). In case of any error, appropriate
        exception is set in the event.

        :param task: managed object reference of the task
        """
        LOG.debug("Invoking VIM API to read info of task: %s.", task)
        try:
            task_info = self.invoke_api(vim_util, "get_object_property", self.vim, task, "info")
        except exceptions.VimException:
            with excutils.save_and_reraise_exception():
                LOG.exception(_LE("Error occurred while reading info of " "task: %s."), task)
        else:
            if task_info.state in ["queued", "running"]:
                if hasattr(task_info, "progress"):
                    LOG.debug(
                        "Task: %(task)s progress is %(progress)s%%.", {"task": task, "progress": task_info.progress}
                    )
            elif task_info.state == "success":
                LOG.debug("Task: %s status is success.", task)
                raise loopingcall.LoopingCallDone(task_info)
            else:
                error_msg = six.text_type(task_info.error.localizedMessage)
                error = task_info.error
                name = error.fault.__class__.__name__
                fault_class = exceptions.get_fault_class(name)
                if fault_class:
                    task_ex = fault_class(error_msg)
                else:
                    task_ex = exceptions.VimFaultException([name], error_msg)
                raise task_ex
Example #3
0
        def _invoke_api(module, method, *args, **kwargs):
            try:
                api_method = getattr(module, method)
                return api_method(*args, **kwargs)
            except exceptions.VimFaultException as excep:
                # If this is due to an inactive session, we should re-create
                # the session and retry.
                if exceptions.NOT_AUTHENTICATED in excep.fault_list:
                    # The NotAuthenticated fault is set by the fault checker
                    # due to an empty response. An empty response could be a
                    # valid response; for e.g., response for the query to
                    # return the VMs in an ESX server which has no VMs in it.
                    # Also, the server responds with an empty response in the
                    # case of an inactive session. Therefore, we need a way to
                    # differentiate between these two cases.
                    if self.is_current_session_active():
                        LOG.debug("Returning empty response for "
                                  "%(module)s.%(method)s invocation.",
                                  {'module': module,
                                   'method': method})
                        return []
                    else:
                        # empty response is due to an inactive session
                        excep_msg = (
                            _("Current session: %(session)s is inactive; "
                              "re-creating the session while invoking "
                              "method %(module)s.%(method)s.") %
                            {'session': _trunc_id(self._session_id),
                             'module': module,
                             'method': method})
                        LOG.debug(excep_msg)
                        self._create_session()
                        raise exceptions.VimConnectionException(excep_msg,
                                                                excep)
                else:
                    # no need to retry for other VIM faults like
                    # InvalidArgument
                    # Raise specific exceptions here if possible
                    if excep.fault_list:
                        LOG.debug("Fault list: %s", excep.fault_list)
                        fault = excep.fault_list[0]
                        clazz = exceptions.get_fault_class(fault)
                        if clazz:
                            raise clazz(six.text_type(excep),
                                        details=excep.details)
                    raise

            except exceptions.VimConnectionException:
                with excutils.save_and_reraise_exception():
                    # Re-create the session during connection exception only
                    # if the session has expired. Otherwise, it could be
                    # a transient issue.
                    if not self.is_current_session_active():
                        LOG.debug("Re-creating session due to connection "
                                  "problems while invoking method "
                                  "%(module)s.%(method)s.",
                                  {'module': module,
                                   'method': method})
                        self._create_session()
Example #4
0
        def _invoke_api(module, method, *args, **kwargs):
            try:
                api_method = getattr(module, method)
                return api_method(*args, **kwargs)
            except exceptions.VimFaultException as excep:
                # If this is due to an inactive session, we should re-create
                # the session and retry.
                if exceptions.NOT_AUTHENTICATED in excep.fault_list:
                    # The NotAuthenticated fault is set by the fault checker
                    # due to an empty response. An empty response could be a
                    # valid response; for e.g., response for the query to
                    # return the VMs in an ESX server which has no VMs in it.
                    # Also, the server responds with an empty response in the
                    # case of an inactive session. Therefore, we need a way to
                    # differentiate between these two cases.
                    if self.is_current_session_active():
                        LOG.debug("Returning empty response for "
                                  "%(module)s.%(method)s invocation.",
                                  {'module': module,
                                   'method': method})
                        return []
                    else:
                        # empty response is due to an inactive session
                        excep_msg = (
                            _("Current session: %(session)s is inactive; "
                              "re-creating the session while invoking "
                              "method %(module)s.%(method)s.") %
                            {'session': _trunc_id(self._session_id),
                             'module': module,
                             'method': method})
                        LOG.debug(excep_msg)
                        self._create_session()
                        raise exceptions.VimConnectionException(excep_msg,
                                                                excep)
                else:
                    # no need to retry for other VIM faults like
                    # InvalidArgument
                    # Raise specific exceptions here if possible
                    if excep.fault_list:
                        LOG.debug("Fault list: %s", excep.fault_list)
                        fault = excep.fault_list[0]
                        clazz = exceptions.get_fault_class(fault)
                        if clazz:
                            raise clazz(six.text_type(excep),
                                        details=excep.details)
                    raise

            except exceptions.VimConnectionException:
                with excutils.save_and_reraise_exception():
                    # Re-create the session during connection exception only
                    # if the session has expired. Otherwise, it could be
                    # a transient issue.
                    if not self.is_current_session_active():
                        LOG.debug("Re-creating session due to connection "
                                  "problems while invoking method "
                                  "%(module)s.%(method)s.",
                                  {'module': module,
                                   'method': method})
                        self._create_session()
Example #5
0
    def _poll_task(self, task, ctx):
        """Poll the given task until completion.

        If the task completes successfully, the method returns the task info
        using the input event (param done). In case of any error, appropriate
        exception is set in the event.

        :param task: managed object reference of the task
        :param ctx: request context for the corresponding task
        """
        if ctx is not None:
            ctx.update_store()
        try:
            # we poll tasks too often, so skip logging the opID as it generates
            # too much noise in the logs
            task_info = self.invoke_api(vim_util,
                                        'get_object_property',
                                        self.vim,
                                        task,
                                        'info',
                                        skip_op_id=True)
        except exceptions.VimException:
            with excutils.save_and_reraise_exception():
                LOG.exception("Error occurred while reading info of "
                              "task: %s.",
                              task)
        else:
            task_detail = {'id': task.value}
            # some internal tasks do not have 'name' set
            if getattr(task_info, 'name', None):
                task_detail['name'] = task_info.name

            if task_info.state in ['queued', 'running']:
                if hasattr(task_info, 'progress'):
                    LOG.debug("Task: %(task)s progress is %(progress)s%%.",
                              {'task': task_detail,
                               'progress': task_info.progress})
            elif task_info.state == 'success':
                def get_completed_task():
                    complete_time = getattr(task_info, 'completeTime', None)
                    if complete_time:
                        duration = complete_time - task_info.queueTime
                        task_detail['duration_secs'] = duration.total_seconds()
                    return task_detail
                LOG.debug("Task: %s completed successfully.",
                          get_completed_task())
                raise loopingcall.LoopingCallDone(task_info)
            else:
                error_msg = six.text_type(task_info.error.localizedMessage)
                error = task_info.error
                name = error.fault.__class__.__name__
                fault_class = exceptions.get_fault_class(name)
                if fault_class:
                    task_ex = fault_class(error_msg)
                else:
                    task_ex = exceptions.VimFaultException([name],
                                                           error_msg)
                raise task_ex
 def test_get_fault_class(self):
     self.assertEqual(exceptions.AlreadyExistsException,
                      exceptions.get_fault_class("AlreadyExists"))
     self.assertEqual(exceptions.CannotDeleteFileException,
                      exceptions.get_fault_class("CannotDeleteFile"))
     self.assertEqual(exceptions.FileAlreadyExistsException,
                      exceptions.get_fault_class("FileAlreadyExists"))
     self.assertEqual(exceptions.FileFaultException,
                      exceptions.get_fault_class("FileFault"))
     self.assertEqual(exceptions.FileLockedException,
                      exceptions.get_fault_class("FileLocked"))
     self.assertEqual(exceptions.FileNotFoundException,
                      exceptions.get_fault_class("FileNotFound"))
     self.assertEqual(exceptions.InvalidPowerStateException,
                      exceptions.get_fault_class("InvalidPowerState"))
     self.assertEqual(exceptions.InvalidPropertyException,
                      exceptions.get_fault_class("InvalidProperty"))
     self.assertEqual(exceptions.NoPermissionException,
                      exceptions.get_fault_class("NoPermission"))
     self.assertEqual(exceptions.NotAuthenticatedException,
                      exceptions.get_fault_class("NotAuthenticated"))
     self.assertEqual(exceptions.TaskInProgress,
                      exceptions.get_fault_class("TaskInProgress"))
     self.assertEqual(exceptions.DuplicateName,
                      exceptions.get_fault_class("DuplicateName"))
     self.assertEqual(exceptions.NoDiskSpaceException,
                      exceptions.get_fault_class("NoDiskSpace"))
     self.assertEqual(exceptions.ToolsUnavailableException,
                      exceptions.get_fault_class("ToolsUnavailable"))
     self.assertEqual(exceptions.ManagedObjectNotFoundException,
                      exceptions.get_fault_class("ManagedObjectNotFound"))
     # Test unknown fault.
     self.assertIsNone(exceptions.get_fault_class("NotAFile"))
 def test_register_fault_class_override(self):
     exc = self._create_subclass_exception()
     exceptions.register_fault_class(exceptions.ALREADY_EXISTS, exc)
     self.assertEqual(exc,
                      exceptions.get_fault_class(exceptions.ALREADY_EXISTS))
 def test_register_fault_class(self):
     exc = self._create_subclass_exception()
     exceptions.register_fault_class('ValueError', exc)
     self.assertEqual(exc, exceptions.get_fault_class('ValueError'))
Example #9
0
 def test_register_fault_class_override(self):
     exc = self._create_subclass_exception()
     exceptions.register_fault_class(exceptions.ALREADY_EXISTS, exc)
     self.assertEqual(exc,
                      exceptions.get_fault_class(exceptions.ALREADY_EXISTS))
Example #10
0
 def test_register_fault_class(self):
     exc = self._create_subclass_exception()
     exceptions.register_fault_class('ValueError', exc)
     self.assertEqual(exc, exceptions.get_fault_class('ValueError'))
 def test_get_fault_class(self):
     self.assertEqual(exceptions.AlreadyExistsException,
                      exceptions.get_fault_class("AlreadyExists"))
     self.assertEqual(exceptions.CannotDeleteFileException,
                      exceptions.get_fault_class("CannotDeleteFile"))
     self.assertEqual(exceptions.FileAlreadyExistsException,
                      exceptions.get_fault_class("FileAlreadyExists"))
     self.assertEqual(exceptions.FileFaultException,
                      exceptions.get_fault_class("FileFault"))
     self.assertEqual(exceptions.FileLockedException,
                      exceptions.get_fault_class("FileLocked"))
     self.assertEqual(exceptions.FileNotFoundException,
                      exceptions.get_fault_class("FileNotFound"))
     self.assertEqual(exceptions.InvalidPowerStateException,
                      exceptions.get_fault_class("InvalidPowerState"))
     self.assertEqual(exceptions.InvalidPropertyException,
                      exceptions.get_fault_class("InvalidProperty"))
     self.assertEqual(exceptions.NoPermissionException,
                      exceptions.get_fault_class("NoPermission"))
     self.assertEqual(exceptions.NotAuthenticatedException,
                      exceptions.get_fault_class("NotAuthenticated"))
     self.assertEqual(exceptions.TaskInProgress,
                      exceptions.get_fault_class("TaskInProgress"))
     self.assertEqual(exceptions.DuplicateName,
                      exceptions.get_fault_class("DuplicateName"))
     self.assertEqual(exceptions.NoDiskSpaceException,
                      exceptions.get_fault_class("NoDiskSpace"))
     self.assertEqual(exceptions.ToolsUnavailableException,
                      exceptions.get_fault_class("ToolsUnavailable"))
     self.assertEqual(exceptions.ManagedObjectNotFoundException,
                      exceptions.get_fault_class("ManagedObjectNotFound"))
     # Test unknown fault.
     self.assertIsNone(exceptions.get_fault_class("NotAFile"))