def test_invoke_api_with_session_is_active_error(self):
        api_session = self._create_api_session(True)
        api_session.create_session = mock.Mock()
        vim_obj = api_session.vim
        vim_obj.SessionIsActive.side_effect = error_util.VimFaultException(
            None, None)
        result = mock.Mock()
        responses = [
            error_util.VimFaultException([error_util.NOT_AUTHENTICATED],
                                         "error"), result
        ]

        def api(*args, **kwargs):
            response = responses.pop(0)
            if isinstance(response, Exception):
                raise response
            return response

        module = mock.Mock()
        module.api = api
        ret = api_session.invoke_api(module, 'api')
        self.assertEqual(result, ret)
        vim_obj.SessionIsActive.assert_called_once_with(
            vim_obj.service_content.sessionManager,
            sessionID=api_session._session_id,
            userName=api_session._session_username)
        api_session.create_session.assert_called_once_with()
Beispiel #2
0
 def _poll_lease(self, lease):
     try:
         state = self.invoke_api(vim_util, 'get_object_property', self.vim,
                                 lease, 'state')
         if state == 'ready':
             # done
             LOG.debug(_("Lease is ready."))
         elif state == 'initializing':
             LOG.debug(_("Lease initializing..."))
             return
         elif state == 'error':
             error_msg = self.invoke_api(vim_util, 'get_object_property',
                                         self.vim, lease, 'error')
             LOG.exception(error_msg)
             excep = error_util.VimFaultException([], error_msg)
             raise excep
         else:
             # unknown state - complain
             error_msg = _("Error: unknown lease state %s.") % state
             raise error_util.VimFaultException([], error_msg)
     except Exception as excep:
         LOG.exception(excep)
         raise excep
     # stop the loop since state is ready
     raise loopingcall.LoopingCallDone()
Beispiel #3
0
        def retrieve_properties_ex_fault_checker(response):
            """Checks the RetrievePropertiesEx response for errors.

            Certain faults are sent as part of the SOAP body as property of
            missingSet. For example NotAuthenticated fault. The method raises
            appropriate VimFaultException when an error is found.

            :param response: Response from RetrievePropertiesEx API call
            """

            fault_list = []
            if not response:
                # This is the case when the session has timed out. ESX SOAP
                # server sends an empty RetrievePropertiesExResponse. Normally
                # missingSet in the returnval field has the specifics about
                # the error, but that's not the case with a timed out idle
                # session. It is as bad as a terminated session for we cannot
                # use the session. So setting fault to NotAuthenticated fault.
                fault_list = [error_util.NOT_AUTHENTICATED]
            else:
                for obj_cont in response:
                    if hasattr(obj_cont, 'missingSet'):
                        for missing_elem in obj_cont.missingSet:
                            fault_type = missing_elem.fault.fault.__class__
                            # Fault needs to be added to the type of fault
                            # for uniformity in error checking as SOAP faults
                            # define
                            fault_list.append(fault_type.__name__)
            if fault_list:
                exc_msg_list = ', '.join(fault_list)
                raise error_util.VimFaultException(
                    fault_list,
                    _("Error(s): %s occurred "
                      "in the call to "
                      "RetrievePropertiesEx.") % exc_msg_list)
Beispiel #4
0
    def _poll_task(self, task):
        """Poll the given task.

        If the task completes successfully then returns task info.
        In case of error sends back appropriate error.

        :param task: Managed object reference of the task
        :param event: Event that captures task status
        """
        try:
            task_info = self.invoke_api(vim_util, 'get_object_property',
                                        self.vim, task, 'info')
            if task_info.state in ['queued', 'running']:
                # If task already completed on server, it will not return
                # the progress.
                if hasattr(task_info, 'progress'):
                    LOG.debug("Task: %(task)s progress: %(prog)s." %
                              {'task': task, 'prog': task_info.progress})
                return
            elif task_info.state == 'success':
                LOG.debug("Task %s status: success." % task)
            else:
                error_msg = str(task_info.error.localizedMessage)
                LOG.exception(_LE("Task: %(task)s failed with "
                                  "error: %(err)s.") %
                              {'task': task, 'err': error_msg})
                raise error_util.VimFaultException([], error_msg)
        except Exception as excep:
            LOG.exception(_LE("Task: %(task)s failed with "
                              "error: %(err)s.") %
                          {'task': task, 'err': excep})
            raise excep
        # got the result. So stop the loop.
        raise loopingcall.LoopingCallDone(task_info)
 def api(*args, **kwargs):
     raise error_util.VimFaultException([error_util.NOT_AUTHENTICATED],
                                        "error")
 def api(*args, **kwargs):
     raise error_util.VimFaultException([], "error")
Beispiel #7
0
        def vim_request_handler(managed_object, **kwargs):
            """Handler for VI SDK calls.

            Builds the SOAP message and parses the response for fault
            checking and other errors.

            :param managed_object:Managed object reference
            :param kwargs: Keyword arguments of the call
            :return: Response of the API call
            """

            try:
                if isinstance(managed_object, str):
                    # For strings use string value for value and type
                    # of the managed object.
                    managed_object = get_moref(managed_object, managed_object)
                request = getattr(self.client.service, attr_name)
                response = request(managed_object, **kwargs)
                if (attr_name.lower() == 'retrievepropertiesex'):
                    retrieve_properties_ex_fault_checker(response)
                return response

            except error_util.VimFaultException as excep:
                raise

            except suds.WebFault as excep:
                doc = excep.document
                detail = doc.childAtPath('/Envelope/Body/Fault/detail')
                fault_list = []
                for child in detail.getChildren():
                    fault_list.append(child.get('type'))
                raise error_util.VimFaultException(fault_list, excep)

            except AttributeError as excep:
                raise error_util.VimAttributeException(
                    _("No such SOAP method "
                      "%(attr)s. Detailed "
                      "error: %(excep)s.") % {
                          'attr': attr_name,
                          'excep': excep
                      })

            except (httplib.CannotSendRequest, httplib.ResponseNotReady,
                    httplib.CannotSendHeader) as excep:
                raise error_util.SessionOverLoadException(
                    _("httplib error in "
                      "%(attr)s: "
                      "%(excep)s.") % {
                          'attr': attr_name,
                          'excep': excep
                      })

            except (urllib2.URLError, urllib2.HTTPError) as excep:
                raise error_util.VimConnectionException(
                    _("urllib2 error in %(attr)s: %(excep)s.") % {
                        'attr': attr_name,
                        'excep': excep
                    })

            except Exception as excep:
                # Socket errors which need special handling for they
                # might be caused by server API call overload
                if (str(excep).find(ADDRESS_IN_USE_ERROR) != -1
                        or str(excep).find(CONN_ABORT_ERROR)) != -1:
                    raise error_util.SessionOverLoadException(
                        _("Socket error "
                          "in %(attr)s: "
                          "%(excep)s.") % {
                              'attr': attr_name,
                              'excep': excep
                          })
                # Type error that needs special handling for it might be
                # caused by server API call overload
                elif str(excep).find(RESP_NOT_XML_ERROR) != -1:
                    raise error_util.SessionOverLoadException(
                        _("Type error "
                          "in %(attr)s: "
                          "%(excep)s.") % {
                              'attr': attr_name,
                              'excep': excep
                          })
                else:
                    raise error_util.VimException(
                        _("Error in %(attr)s. "
                          "Detailed error: "
                          "%(excep)s.") % {
                              'attr': attr_name,
                              'excep': excep
                          })