baseimage-tutorial-framework/tfw/internals/server/zmq_websocket_router.py

49 lines
1.3 KiB
Python
Raw Permalink Normal View History

import json
2019-06-10 13:32:45 +00:00
import logging
from tornado.websocket import WebSocketHandler
2019-07-24 15:22:08 +00:00
from .tfw_router import TFWRouter
LOG = logging.getLogger(__name__)
class ZMQWebSocketRouter(WebSocketHandler):
2019-07-15 09:09:57 +00:00
# pylint: disable=abstract-method,attribute-defined-outside-init
instances = set()
2019-07-15 09:09:57 +00:00
def initialize(self, **kwargs):
self._listener = kwargs['listener']
2019-05-26 16:26:33 +00:00
self.tfw_router = TFWRouter(self.send_to_zmq, self.send_to_websockets)
def send_to_zmq(self, message):
self._listener.send_message(message)
2019-05-26 16:26:33 +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)
def prepare(self):
type(self).instances.add(self)
def on_close(self):
type(self).instances.remove(self)
def open(self, *args, **kwargs):
2019-05-26 16:26:33 +00:00
LOG.debug('WebSocket connection initiated!')
self._listener.register_callback(self.zmq_callback)
2019-05-26 16:26:33 +00:00
def zmq_callback(self, message):
LOG.debug('Received on ZMQ pull socket: %s', message)
self.tfw_router.route(message)
def on_message(self, message):
message = json.loads(message)
LOG.debug('Received on WebSocket: %s', message)
2019-05-26 16:26:33 +00:00
self.tfw_router.route(message)
# much secure, very cors, wow
def check_origin(self, origin):
return True