示例#1
0
 def __init__(self, context, service):
     """Initialize the MDPClient.
     """
     cfg = Loader('mq').load()
     config = dict(cfg[1])
     if config['ip'].strip() == "*":
         config['ip'] = get_ip()
     self.endpoint = "tcp://{0}:{1}".format(config['ip'], config['req_rep_port'])
     socket = ZmqSocket(context, zmq.REQ)
     ioloop = IOLoop.instance()
     self.service = service
     self.stream = ZMQStream(socket, ioloop)
     self.stream.on_recv(self._on_message)
     self.can_send = True
     self._proto_prefix = [ PROTO_VERSION, service]
     self._tmo = None
     self.timed_out = False
     socket.connect(self.endpoint)
     return
示例#2
0
 def __init__(self, context):
     """Initialize the MDPClient.
     """
     cfg = Loader('mq').load()
     config = dict(cfg[1])
     if config['ip'].strip() == "*":
         config['ip'] = get_ip()
     endpoint = "tcp://{0}:{1}".format(config['ip'], config['req_rep_port'])
     self.socket = ZmqSocket(context, zmq.REQ)
     self.socket.connect(endpoint)
     return
示例#3
0
    def __init__(self, context, main_ep, opt_ep=None):
        """Init MDPBroker instance.
        """
        l = logger.Logger('mq_broker')
        self.log = l.get_logger()
        self.log.info("MDP broker startup...")

        socket = ZmqSocket(context, zmq.ROUTER)
        socket.bind(main_ep)
        self.log.info("Using {0} [BIND]".format(main_ep))
        self.main_stream = ZMQStream(socket)
        self.main_stream.on_recv(self.on_message)
        if opt_ep:
            socket = ZmqSocket(context, zmq.ROUTER)
            socket.bind(opt_ep)
            self.client_stream = ZMQStream(socket)
            self.client_stream.on_recv(self.on_message)
        else:
            self.client_stream = self.main_stream
        self.log.debug("Socket created...")
        self._workers = {}
        # services contain the worker queue and the request queue
        self._services = {}
        self._worker_cmds = { b'\x01': self.on_ready,
                              b'\x03': self.on_reply,
                              b'\x04': self.on_heartbeat,
                              b'\x05': self.on_disconnect,
                              }
        self.log.debug("Launch the timer...")
        self.hb_check_timer = PeriodicCallback(self.on_timer, HB_INTERVAL)
        self.hb_check_timer.start()
        self.log.info("MDP broker started")
        return
示例#4
0
class MQSyncReq(object):

    """Class for the MDP client side.

    Thin asynchronous encapsulation of a zmq.REQ socket.
    Provides a :func:`request` method with optional timeout.

    Objects of this class are ment to be integrated into the
    asynchronous IOLoop of pyzmq.

    :param context:  the ZeroMQ context to create the socket in.
    :type context:   zmq.Context
    :param endpoint: the enpoint to connect to.
    :type endpoint:  str
    :param service:  the service the client should use
    :type service:   str
    """

    _proto_version = b'MDPC01'

    def __init__(self, context):
        """Initialize the MDPClient.
        """
        cfg = Loader('mq').load()
        config = dict(cfg[1])
        if config['ip'].strip() == "*":
            config['ip'] = get_ip()
        endpoint = "tcp://{0}:{1}".format(config['ip'], config['req_rep_port'])
        self.socket = ZmqSocket(context, zmq.REQ)
        self.socket.connect(endpoint)
        return

    def shutdown(self):
        """Method to deactivate the client connection completely.

        Will delete the stream and the underlying socket.

        .. warning:: The instance MUST not be used after :func:`shutdown` has been called.

        :rtype: None
        """
        if not self.socket:
            return
        self.socket.setsockopt(zmq.LINGER, 0)
        self.socket.close()
        self.socket = None
        return

    def rawrequest(self, service, msg, timeout=None):
        if not timeout or timeout < 0.0:
            timeout = None
        if type(msg) is list:
            b = []
            for m in msg:
                b.append(str.encode(m))
            msg = b
        elif type(msg) is bytes:
            msg = [msg]
        elif type(msg) is str:
            msg = [str.encode(msg)]
        to_send = [self._proto_version, str.encode(service), str(timeout)]
        to_send.extend(msg)
        self.socket.send_multipart(to_send)
        ret = None
        rlist, _, _ = select([self.socket], [], [], timeout)
        if rlist and rlist[0] == self.socket:
            ret = self.socket.recv_multipart()
            ret.pop(0) # remove service from reply
            ret.pop(0)
        return ret

    def request(self, service, msg, timeout=None):
        """Send the given message.

        :param msg:     message parts to send.
        :type msg:      list of str
        :param timeout: time to wait in milliseconds.
        :type timeout:  int

        :rtype : message parts
        """
        ret = self.rawrequest( service, msg, timeout)
        msg = None
        if ret:
            msg = MQMessage()
            msg.set(ret)
        return msg