2018-01-26 14:15:05 +00:00
|
|
|
import json
|
2019-06-10 13:32:45 +00:00
|
|
|
import logging
|
2018-03-25 13:43:59 +00:00
|
|
|
|
2017-11-17 14:47:22 +00:00
|
|
|
from tornado.websocket import WebSocketHandler
|
|
|
|
|
2019-07-24 15:22:08 +00:00
|
|
|
from .tfw_router import TFWRouter
|
2018-03-25 14:06:59 +00:00
|
|
|
|
|
|
|
LOG = logging.getLogger(__name__)
|
2018-01-29 16:24:17 +00:00
|
|
|
|
2017-11-17 14:47:22 +00:00
|
|
|
|
2019-06-04 11:58:03 +00:00
|
|
|
class ZMQWebSocketRouter(WebSocketHandler):
|
2019-07-15 09:09:57 +00:00
|
|
|
# pylint: disable=abstract-method,attribute-defined-outside-init
|
2018-02-16 16:47:30 +00:00
|
|
|
instances = set()
|
|
|
|
|
2019-07-15 09:09:57 +00:00
|
|
|
def initialize(self, **kwargs):
|
2019-05-26 16:26:33 +00:00
|
|
|
self.event_handler_connector = kwargs['event_handler_connector']
|
|
|
|
self.tfw_router = TFWRouter(self.send_to_zmq, self.send_to_websockets)
|
|
|
|
|
|
|
|
def send_to_zmq(self, message):
|
|
|
|
self.event_handler_connector.send_message(message)
|
|
|
|
|
2019-06-04 11:58:03 +00:00
|
|
|
@classmethod
|
|
|
|
def send_to_websockets(cls, message):
|
|
|
|
for instance in cls.instances:
|
2019-05-26 16:26:33 +00:00
|
|
|
instance.write_message(message)
|
2018-04-06 14:04:25 +00:00
|
|
|
|
2018-02-16 16:47:30 +00:00
|
|
|
def prepare(self):
|
2019-06-04 11:58:03 +00:00
|
|
|
type(self).instances.add(self)
|
2018-02-16 16:47:30 +00:00
|
|
|
|
|
|
|
def on_close(self):
|
2019-06-04 11:58:03 +00:00
|
|
|
type(self).instances.remove(self)
|
2018-02-05 13:23:46 +00:00
|
|
|
|
2017-11-17 14:47:22 +00:00
|
|
|
def open(self, *args, **kwargs):
|
2019-05-26 16:26:33 +00:00
|
|
|
LOG.debug('WebSocket connection initiated!')
|
|
|
|
self.event_handler_connector.register_callback(self.zmq_callback)
|
|
|
|
|
|
|
|
def zmq_callback(self, message):
|
|
|
|
LOG.debug('Received on ZMQ pull socket: %s', message)
|
|
|
|
self.tfw_router.route(message)
|
2018-07-30 07:25:32 +00:00
|
|
|
|
2017-11-17 14:47:22 +00:00
|
|
|
def on_message(self, message):
|
2018-06-28 15:33:20 +00:00
|
|
|
message = json.loads(message)
|
2018-03-25 14:25:01 +00:00
|
|
|
LOG.debug('Received on WebSocket: %s', message)
|
2019-05-26 16:26:33 +00:00
|
|
|
self.tfw_router.route(message)
|
2018-04-11 13:22:54 +00:00
|
|
|
|
2017-11-17 14:47:22 +00:00
|
|
|
# much secure, very cors, wow
|
|
|
|
def check_origin(self, origin):
|
|
|
|
return True
|