Source

araldo / araldo / router.py

Full commit
""" Routing of messages from inbound to outbound endpoints
"""
import logging
import gevent


class Router:
    """ Routing of messages
        : param sub_config: *routes* configuration sub-object
    """
    def __init__(self, sub_config, plugin_manager):
        self._log = logging.getLogger("araldo")
        self._routes = sub_config
        self._plugin_manager = plugin_manager
        for source, destinations in self._routes.items():
            self._log.debug(
                "Using route: %s --> %s",
                source, ", ".join(destinations))
        self._outbound = self._plugin_manager.plugin_instances()[
            "araldo.endpoints.endpoint"]

    def routes(self):
        """ :return: configured routes
        :rtype:  {str: [str]}
        """
        return self._routes

    def route(self, origin, message):
        """ Send message via all configured outgoing endpoints
        """
        #self._log.debug(
        #    "_routes: %s, _outbound: %s",
        #    self._routes, self._outbound)
        route = self._routes.get(origin, None)
        if route is None:
            self._log.debug(
                "No routes defined for origin '%s'",
                origin)
        else:
            for destination in route:
                self._log.debug(
                    "Routing %s: %s --> %s",
                    str(message), origin, destination)
                if destination not in self._outbound:
                    self._log.warning(
                        "Destination '%s' not found; not routing",
                        destination)
                    continue
                try:
                    self._outbound[destination].send(message)
                except Exception as error:
                    self._log.error(
                        "Exception while sending message to %s: %s",
                        destination, error)
                gevent.sleep(0)