Beispiel #1
0
    async def close(self, exception=None):
        """Close down the handler connection.

        If the handler has already closed,
        this operation will do nothing. An optional exception can be passed in to
        indicate that the handler was shutdown due to error.
        It is recommended to open a handler within a context manager as
        opposed to calling the method directly.

        .. note:: This operation is not thread-safe.

        :param exception: An optional exception if the handler is closing
         due to an error.
        :type exception: Exception

        .. admonition:: Example:
            .. literalinclude:: ../samples/async_samples/test_examples_async.py
                :start-after: [START open_close_sender_directly]
                :end-before: [END open_close_sender_directly]
                :language: python
                :dedent: 4
                :caption: Explicitly open and close a Sender.

        """
        self.running = False
        if self.error:
            return
        if isinstance(exception, ServiceBusError):
            self.error = exception
        elif exception:
            self.error = ServiceBusError(str(exception))
        else:
            self.error = ServiceBusError("This message handler is now closed.")
        await self._handler.close_async()
Beispiel #2
0
 async def _handle_exception(self, exception):
     if isinstance(exception, (errors.LinkDetach, errors.ConnectionClose)):
         if exception.action and exception.action.retry and self.auto_reconnect:
             _log.info("Async handler detached. Attempting reconnect.")
             await self.reconnect()
         elif exception.condition == constants.ErrorCodes.UnauthorizedAccess:
             _log.info("Async handler detached. Shutting down.")
             error = ServiceBusAuthorizationError(str(exception), exception)
             await self.close(exception=error)
             raise error
         else:
             _log.info("Async handler detached. Shutting down.")
             error = ServiceBusConnectionError(str(exception), exception)
             await self.close(exception=error)
             raise error
     elif isinstance(exception, errors.MessageHandlerError):
         if self.auto_reconnect:
             _log.info("Async handler error. Attempting reconnect.")
             await self.reconnect()
         else:
             _log.info("Async handler error. Shutting down.")
             error = ServiceBusConnectionError(str(exception), exception)
             await self.close(exception=error)
             raise error
     elif isinstance(exception, errors.AMQPConnectionError):
         message = "Failed to open handler: {}".format(exception)
         raise ServiceBusConnectionError(message, exception)
     else:
         _log.info("Unexpected error occurred (%r). Shutting down.",
                   exception)
         error = ServiceBusError("Handler failed: {}".format(exception),
                                 exception)
         await self.close(exception=error)
         raise error
    def _mgmt_request_response(self, operation, message, callback, **kwargs):
        if not self.running:
            raise InvalidHandlerState("Client connection is closed.")

        try:
            application_properties = {
                ASSOCIATEDLINKPROPERTYNAME: self._handler.message_handler.name
            }
        except AttributeError:
            application_properties = {}

        mgmt_msg = Message(body=message,
                           properties=MessageProperties(
                               reply_to=self.mgmt_target,
                               encoding=self.encoding,
                               **kwargs),
                           application_properties=application_properties)
        try:
            return self._handler.mgmt_request(mgmt_msg,
                                              operation,
                                              op_type=b"entity-mgmt",
                                              node=self.mgmt_target.encode(
                                                  self.encoding),
                                              timeout=5000,
                                              callback=callback)
        except Exception as exp:  # pylint: disable=broad-except
            raise ServiceBusError("Management request failed: {}".format(exp),
                                  exp)
Beispiel #4
0
def schedule_op(status_code, message, description):
    if status_code == 200:
        return message.get_data()[b'sequence-numbers']
    error = "Scheduling messages failed with status code: {}.\n".format(
        status_code)
    if description:
        error += "{}.".format(description)
    raise ServiceBusError(error)
Beispiel #5
0
def lock_renew_op(status_code, message, description):
    if status_code == 200:
        return message.get_data()
    if status_code == 410:
        raise MessageLockExpired(message=description)
    raise ServiceBusError(
        "Management request returned status code: {}. Description: {}, Data: {}"
        .format(status_code, description, message.get_data()))
Beispiel #6
0
def list_sessions_op(status_code, message, description):
    if status_code == 200:
        parsed = []
        for m in message.get_data()[b'sessions-ids']:
            parsed.append(m.decode('UTF-8'))
        return parsed
    if status_code in [202, 204]:
        return []
    error = "List sessions failed with status code: {}.\n".format(status_code)
    if description:
        error += "{}.".format(description)
    raise ServiceBusError(error)
Beispiel #7
0
def peek_op(status_code, message, description):
    if status_code == 200:
        parsed = []
        for m in message.get_data()[b'messages']:
            wrapped = uamqp.Message.decode_from_bytes(bytearray(m[b'message']))
            parsed.append(PeekMessage(wrapped))
        return parsed
    if status_code in [202, 204]:
        return []
    error = "Message peek failed with status code: {}.\n".format(status_code)
    if description:
        error += "{}.".format(description)
    raise ServiceBusError(error)
    def close(self, exception=None):
        """Close down the handler connection.

        If the handler has already closed, this operation will do nothing. An optional exception can be passed in to
        indicate that the handler was shutdown due to error.
        It is recommended to open a handler within a context manager as
        opposed to calling the method directly.

        .. note:: This operation is not thread-safe.

        :param exception: An optional exception if the handler is closing
         due to an error.
        :type exception: Exception
        """
        self.running = False
        if self.error:
            return
        if isinstance(exception, ServiceBusError):
            self.error = exception
        elif exception:
            self.error = ServiceBusError(str(exception))
        else:
            self.error = ServiceBusError("This message handler is now closed.")
        self._handler.close()
Beispiel #9
0
def deferred_message_op(status_code,
                        message,
                        description,
                        mode=1,
                        message_type=DeferredMessage):
    if status_code == 200:
        parsed = []
        for m in message.get_data()[b'messages']:
            wrapped = uamqp.Message.decode_from_bytes(bytearray(m[b'message']))
            parsed.append(message_type(wrapped, mode))
        return parsed
    if status_code in [202, 204]:
        return []
    error = "Retrieving deferred messages failed with status code: {}.\n".format(
        status_code)
    if description:
        error += "{}.".format(description)
    raise ServiceBusError(error)
Beispiel #10
0
    async def _mgmt_request_response(self, operation, message, callback,
                                     **kwargs):
        if not self.running:
            raise InvalidHandlerState("Client connection is closed.")

        mgmt_msg = Message(body=message,
                           properties=MessageProperties(
                               reply_to=self.mgmt_target,
                               encoding=self.encoding,
                               **kwargs))
        try:
            return await self._handler.mgmt_request_async(
                mgmt_msg,
                operation,
                op_type=b"entity-mgmt",
                node=self.mgmt_target.encode(self.encoding),
                timeout=5000,
                callback=callback)
        except Exception as exp:  # pylint: disable=broad-except
            raise ServiceBusError("Management request failed: {}".format(exp),
                                  exp)
Beispiel #11
0
def default(status_code, message, description):
    if status_code == 200:
        return message.get_data()
    raise ServiceBusError(
        "Management request returned status code: {}. Description: {}, Data: {}"
        .format(status_code, description, message.get_data()))