def setUp(self):
     config = {
         'moksha.livesocket': True,
         'moksha.livesocket.backend': 'websocket',
         'moksha.socket.notify': True,
         'moksha.livesocket.websocket.port': 8009,
         "zmq_publish_endpoints": "tcp://*:6543",
         "zmq_subscribe_endpoints": "tcp://127.0.0.1:6543",
         "zmq_enabled": True,
         'zmq_strict': False,
     }
     self.hub = CentralMokshaHub(config=config)
     self.topic = str(uuid4())
Exemple #2
0
    def test_open_and_close(self):
        """ Test that a central hub with a consumer can be closed.. ;) """
        class TestConsumer(moksha.hub.api.consumer.Consumer):
            topic = "whatever"

            def consume(self, message):
                pass

        # Just a little fake config.
        config = dict(
            zmq_enabled=True,
            zmq_subscribe_endpoints='',
            zmq_published_endpoints='',
        )
        central = CentralMokshaHub(config, [TestConsumer], [])
        central.close()
Exemple #3
0
    def test_open_and_close(self):
        """ Test that a central hub with a consumer can be closed.. ;) """

        class TestConsumer(moksha.hub.api.consumer.Consumer):
            topic = "whatever"

            def consume(self, message):
                pass

        # Just a little fake config.
        config = dict(
            zmq_enabled=True,
            zmq_subscribe_endpoints='',
            zmq_published_endpoints='',
        )
        central = CentralMokshaHub(config, [TestConsumer], [])
        central.close()
Exemple #4
0
def main(options=None, consumers=None, producers=None, framework=True):
    """ The main MokshaHub method """

    # If we're running as a framework, then we're strictly calling other
    # people's code.  So, as the outermost piece of software in the stack, we're
    # responsible for setting up logging.
    # If we're not running as a framework, but as a library, then someone else
    # is calling us.  Therefore, we'll let them set up the logging themselves.
    if framework:
        setup_logger('-v' in sys.argv or '--verbose' in sys.argv)

    config = {}

    if not options:
        if sys.argv[-1].endswith('.ini'):
            config_path = os.path.abspath(sys.argv[-1])
        else:
            config_path = get_moksha_config_path()

        if not config_path:
            print NO_CONFIG_MESSAGE
            return

        cfg = appconfig('config:' + config_path)
        config.update(cfg)
    else:
        config.update(options)

    hub = CentralMokshaHub(config, consumers=consumers, producers=producers)
    global _hub
    _hub = hub

    def handle_signal(signum, stackframe):
        from moksha.hub.reactor import reactor
        if signum in [signal.SIGHUP, signal.SIGINT]:
            hub.stop()
            try:
                reactor.stop()
            except ReactorNotRunning:
                pass

    signal.signal(signal.SIGHUP, handle_signal)
    signal.signal(signal.SIGINT, handle_signal)

    log.info("Running the MokshaHub reactor")
    from moksha.hub.reactor import reactor
    reactor.run(installSignalHandlers=False)
    log.info("MokshaHub reactor stopped")
Exemple #5
0
    def test_dynamic_topic(self):
        """ Test that a topic can be set at runtime (not import time) """
        class TestConsumer(moksha.hub.api.consumer.Consumer):
            topic = "bad topic"

            def __init__(self, *args, **kw):
                super(TestConsumer, self).__init__(*args, **kw)
                self.topic = "good topic"

            def consume(self, message):
                pass

        # Just a little fake config.
        config = dict(
            zmq_enabled=True,
            zmq_subscribe_endpoints='',
            zmq_published_endpoints='',
        )
        central = CentralMokshaHub(config, [TestConsumer], [])

        # Guarantee that "bad topic" is not in the topics list.
        eq_(central.topics.keys(), ["good topic"])
class TestWebSocketServer(unittest.TestCase):

    def setUp(self):
        config = {
            'moksha.livesocket': True,
            'moksha.livesocket.backend': 'websocket',
            'moksha.socket.notify': True,
            'moksha.livesocket.websocket.port': 8009,
            "zmq_publish_endpoints": "tcp://*:6543",
            "zmq_subscribe_endpoints": "tcp://127.0.0.1:6543",
            "zmq_enabled": True,
            'zmq_strict': False,
        }
        self.hub = CentralMokshaHub(config=config)
        self.topic = str(uuid4())

    def tearDown(self):
        self.hub.close()
        # It can take some time to unregister our WS server from its port
        simulate_reactor(sleep_duration)

    def test_ws_subscribe_and_recv(self):
        """ Test that we can subscribe for and receive a message. """

        self.received_message = None
        import threading

        class client_thread(threading.Thread):
            def run(thread):
                ws = websocket.WebSocket()
                ws.settimeout(5)
                ws.connect("ws://127.0.0.1:{port}/".format(
                    port=self.hub.config['moksha.livesocket.websocket.port'],
                ))

                ws.send(json.dumps(dict(
                    topic="__topic_subscribe__",
                    body=self.topic,
                )))

                # Receive that..
                self.received_message = json.loads(ws.recv())['body']
                ws.close()

        client = client_thread()
        client.start()

        # Process the connection from the client-thread.
        simulate_reactor(sleep_duration)

        # Now, send a message...
        self.hub.send_message(
            topic=self.topic,
            message=secret,
        )

        # Process the sending of our special message.
        simulate_reactor(sleep_duration)

        client.join()
        eq_(self.received_message, secret)

    def test_ws_subscribe_multiple(self):
        """ Test that we can subscribe to a few different topics. """

        self.received_messages = []
        import threading

        num_topics = 3

        class client_thread(threading.Thread):
            def run(thread):
                ws = websocket.WebSocket()
                ws.settimeout(5)
                ws.connect("ws://127.0.0.1:{port}/".format(
                    port=self.hub.config['moksha.livesocket.websocket.port'],
                ))

                for i in range(num_topics):
                    ws.send(json.dumps(dict(
                        topic="__topic_subscribe__",
                        body=self.topic + "_" + str(i),
                    )))

                # Receive that..
                for i in range(num_topics):
                    try:
                        self.received_messages.append(
                            json.loads(ws.recv())['body']
                        )
                    except Exception:
                        pass

                ws.close()

        client = client_thread()
        client.start()

        # Process the connection from the client-thread.
        simulate_reactor(sleep_duration)

        # Now, send a message...
        for i in range(num_topics):
            self.hub.send_message(
                topic=self.topic + "_" + str(i),
                message=secret,
            )

        # Process the sending of our special message.
        simulate_reactor(sleep_duration)

        client.join()
        eq_(self.received_messages, [secret] * num_topics)

    def test_ws_subscribe_filter(self):
        """ Test that the WS server only sends desired topics. """

        self.received_messages = []
        import threading

        num_topics = 1

        class client_thread(threading.Thread):
            def run(thread):
                ws = websocket.WebSocket()
                ws.settimeout(5)
                ws.connect("ws://127.0.0.1:{port}/".format(
                    port=self.hub.config['moksha.livesocket.websocket.port'],
                ))

                for i in range(num_topics):
                    ws.send(json.dumps(dict(
                        topic="__topic_subscribe__",
                        body=self.topic + "_" + str(i),
                    )))

                # Receive that..
                for i in range(num_topics + 1):
                    try:
                        self.received_messages.append(
                            json.loads(ws.recv())['body']
                        )
                    except Exception:
                        pass

                ws.close()

        client = client_thread()
        client.start()

        # Process the connection from the client-thread.
        simulate_reactor(sleep_duration)

        # Now, send a message...
        for i in range(num_topics + 1):
            self.hub.send_message(
                topic=self.topic + "_" + str(i),
                message=secret,
            )

        # Process the sending of our special message.
        simulate_reactor(sleep_duration)

        client.join()
        eq_(self.received_messages, [secret] * num_topics)

    def test_ws_multiple_clients_different_topics(self):
        """ Test that the WS server can differentiate clients. """

        import threading

        num_topics = 2

        class client_thread(threading.Thread):
            def run(thread):
                thread.received_messages = []
                ws = websocket.WebSocket()
                ws.settimeout(5)
                ws.connect("ws://127.0.0.1:{port}/".format(
                    port=self.hub.config['moksha.livesocket.websocket.port'],
                ))

                for i in range(num_topics):
                    ws.send(json.dumps(dict(
                        topic="__topic_subscribe__",
                        body=thread.topic + "_" + str(i),
                    )))

                # Receive that..
                for i in range(num_topics + 2):
                    try:
                        thread.received_messages.append(
                            json.loads(ws.recv())['body']
                        )
                    except Exception:
                        pass

                ws.close()

        client1 = client_thread()
        client2 = client_thread()
        client1.topic = self.topic + "_topic_1"
        client2.topic = self.topic + "_topic_2"
        client1.received_messages = []
        client2.received_messages = []
        client1.start()
        client2.start()

        # Process the connection from the client-thread.
        simulate_reactor(sleep_duration)

        # Now, send a message...
        for i in range(num_topics):
            self.hub.send_message(
                topic=self.topic + "_topic_1" + "_" + str(i),
                message=secret + "_1",
            )
            self.hub.send_message(
                topic=self.topic + "_topic_2" + "_" + str(i),
                message=secret + "_2",
            )

        # Process the sending of our special message.
        simulate_reactor(sleep_duration)

        client1.join()
        client2.join()
        eq_(client1.received_messages, [secret + "_1"] * num_topics)
        eq_(client2.received_messages, [secret + "_2"] * num_topics)