def socket_unbind(socket: zmq.Socket, protocol, interface=None, port=None): if protocol == 'tcp': assert port is not None and interface is None socket.unbind(f'tcp://0.0.0.0:{port}') else: assert interface is not None socket.unbind(f'tcp://{interface}')
def readSendVideo(Videopath: str, socket: Socket): messagevid = {} with open(Videopath, 'rb') as vfile: file = vfile.read() messagevid['VIDEO'] = file socket.send_pyobj(messagevid) return True
def modify_measurement_window_cycles( makai_send_socket: zmq.Socket, box_ids: typing.List[str], measurement_window_cycles: int, box_optimization_records: BoxOptimizationRecords, logger: BoxOptimizationPluginLogger): """ Dynamically modifies the measurement rate of boxes. :param makai_send_socket: The ZMQ socket to send modification requests to. :param box_ids: A list of box ids to modify. :param measurement_window_cycles: Number of cycles in a measurement. :param box_optimization_records: Thread safe req/resp of records. :param logger: The logger. """ if measurement_window_cycles <= 0: logger.error( "measurement_window_cycles must be strictly larger than 0") return logger.debug("Modifying measurement_window_cycles=%d for %s" % (measurement_window_cycles, str(box_ids))) box_commands = pb_util.build_makai_rate_change_commands( box_ids, measurement_window_cycles) for (box_command, identity) in box_commands: serialized_box_command = pb_util.serialize_message(box_command) makai_send_socket.send(serialized_box_command) box_optimization_records.add_record(identity) logger.debug("Sent optimization request command with identity=%s" % identity)
def recv_array(socket: zmq.Socket, **kw) -> np.ndarray: """ Receive an ndarray over a zmq socket. """ md = socket.recv_json() buf = memoryview(socket.recv(**kw)) return np.frombuffer(buf, dtype=md['dtype']).reshape(md['shape'])
def socket_disconnect(socket: zmq.Socket, protocol, interface, port=None): if protocol == 'tcp': assert port is not None socket.disconnect(f'{protocol}://{interface}:{port}') else: assert port is None socket.disconnect(f'{protocol}://{interface}')
async def push_game_state(game_state: GameState, sock: Socket) -> None: try: while True: sock.send_string(game_state.to_json()) await asyncio.sleep(1 / SERVER_TICK) except asyncio.CancelledError: pass
def bindSocket(cls, socket: zmq.Socket, server_address: str, port: int): test_port = port if (port > 0) else cls.DefaultPort while (True): try: socket.bind("tcp://{0}:{1}".format(server_address, test_port)) return test_port except Exception as err: test_port = test_port + 1
def send_array(socket: zmq.Socket, data: np.ndarray, **kw) -> None: """ Send a ndarray. """ md = {'shape': data.shape, 'dtype': str(data.dtype)} socket.send_json(md, zmq.SNDMORE) socket.send(data, **kw)
def pubData(publisher: zmq.Socket, topic: str): while True: for i in range(100): publisher.send_string("%s 1" % topic) time.sleep(0.10) # 10hz for i in range(100): publisher.send_string("%s 0" % topic) time.sleep(0.10) # 10hz
def req_server_meta(dealer: zmq.Socket) -> ServerMeta: dealer.send(_server_meta_req_cache) server_meta = serializer.loads(dealer.recv()) if server_meta.version != __version__: raise RuntimeError( "The server version didn't match. " "Please make sure the server (%r) is using the same version of ZProc as this client (%r)." % (server_meta.version, __version__)) return server_meta
def recv(sock: zmq.Socket, serializer, *, silent=True): if silent: while True: try: return serializer.loads(sock.recv()) except itsdangerous.BadSignature: continue else: return serializer.loads(sock.recv())
def udpate_progress(progress_sock:zmq.Socket, step:str, global_progress:float,step_detail:str, step_progress:float): progress_sock.send_json(json.dumps( { "step":step, "global_progress":global_progress, "step_detail":step_detail, "step_progress":step_progress } ))
def recv_frame(socket: zmq.Socket, flags: int = 0, **kw) -> Frame: """ Receive a `Frame` object over a zmq socket. """ md = socket.recv_json(flags) buf = memoryview(socket.recv(**kw)) data = np.frombuffer(buf, dtype=md['dtype']).reshape(md['shape']) return Frame(data, index=md['index'], time=md['time'])
def __init__(self, socket: zmq.Socket, stream, pt_print): self.socket = socket socket.setsockopt(zmq.SUBSCRIBE, b"") # Listen to everything self.stream = stream threading.Thread.__init__(self) self.daemon = True self.sync_condition = threading.Condition() self.last_sync_seq = -1 self.pt_print = pt_print
def __init__(self, factory, endpoint=None, identity=None): """ Constructor. One endpoint is passed to the constructor, more could be added via call to :meth:`addEndpoints`. :param factory: ZeroMQ Twisted factory :type factory: :class:`ZmqFactory` :param endpoint: ZeroMQ address for connect/bind :type endpoint: :class:`ZmqEndpoint` :param identity: socket identity (ZeroMQ), don't set unless you know how it works :type identity: str """ self.factory = factory self.endpoints = [] self.identity = identity self.socket = Socket(factory.context, self.socketType) self.queue = deque() self.recv_parts = [] self.read_scheduled = None self.fd = self.socket.get(constants.FD) self.socket.set(constants.LINGER, factory.lingerPeriod) if not ZMQ3: self.socket.set(constants.MCAST_LOOP, int(self.allowLoopbackMulticast)) self.socket.set(constants.RATE, self.multicastRate) if not ZMQ3: self.socket.set(constants.HWM, self.highWaterMark) else: self.socket.set(constants.SNDHWM, self.highWaterMark) self.socket.set(constants.RCVHWM, self.highWaterMark) if ZMQ3 and self.tcpKeepalive: self.socket.set(constants.TCP_KEEPALIVE, self.tcpKeepalive) self.socket.set(constants.TCP_KEEPALIVE_CNT, self.tcpKeepaliveCount) self.socket.set(constants.TCP_KEEPALIVE_IDLE, self.tcpKeepaliveIdle) self.socket.set(constants.TCP_KEEPALIVE_INTVL, self.tcpKeepaliveInterval) if self.identity is not None: self.socket.set(constants.IDENTITY, self.identity) if endpoint: self.addEndpoints([endpoint]) self.factory.connections.add(self) self.factory.reactor.addReader(self) self.doRead()
def __send_message(self, socket: zmq.Socket, msg: Union[SeedMsg, FuzzerCtrlMsg]) -> None: if type(msg) == FuzzerCtrlMsg: msg_type = _MessageType.CONTROL.value elif type(msg) == SeedMsg: msg_type = _MessageType.SEED.value else: raise ValueError(f"Unknown message type: {type(msg)}") socket.send_multipart((msg_type, msg.SerializeToString()))
def addClientAuth( self, socket: zmq.Socket ): self.logger.info( f"Adding ZMQ client auth using keys from dir: {self.cert_dir}") client_secret_file = os.path.join( self.secret_keys_dir, "client.key_secret") client_public, client_secret = zmq.auth.load_certificate(client_secret_file) socket.curve_secretkey = client_secret socket.curve_publickey = client_public server_public_file = os.path.join( self.public_keys_dir, "server.key") server_public, _ = zmq.auth.load_certificate(server_public_file) socket.curve_serverkey = server_public
def _set_curve_keypair(self, socket: zmq.Socket): """ Generate a client keypair using CURVE encryption mechanism, and set the server key for encryption. :param socket: (zmq.Socket) The socket to set CURVE key. """ client_public, client_secret = zmq.curve_keypair() socket.curve_publickey = client_public socket.curve_secretkey = client_secret socket.setsockopt_string(zmq.CURVE_SERVERKEY, self._SERVER_ZMQ_ENCRYPTION_KEY)
def socket_bind(socket: zmq.Socket, protocol, interface=None, port=None): if protocol == 'tcp': assert interface is None if port is None: port = socket.bind_to_random_port('tcp://0.0.0.0') else: socket.bind(f'tcp://0.0.0.0:{port}') return port else: assert interface is not None socket.bind(f'tcp://{interface}')
def __poll_socket(self, socket: zmq.Socket) -> int: waited_time = timedelta() report_timeout_ms = self.REPORT_TIMEOUT / timedelta(milliseconds=1) while socket.poll(report_timeout_ms) == 0: waited_time += self.REPORT_TIMEOUT logger.warning(f"Polled socket for {waited_time}") if waited_time >= self.MAX_SOCKET_TIMEOUT: raise ConnectionException(f"Polling timed out") return socket.poll()
def recv_array( socket: zmq.Socket, flags: int = 0, copy: bool = True, track: bool = False, ) -> np.ndarray: """ Receive an ndarray over a zmq socket. """ md = socket.recv_json(flags) buf = memoryview(socket.recv(flags, copy, track)) return np.frombuffer(buf, dtype=md['dtype']).reshape(md['shape'])
def recv_array(socket: zmq.Socket, flags: int = 0, copy: int = True, track: bool = False): """ Receive a numpy array """ dictionary = socket.recv_json(flags=flags) message = socket.recv(flags=flags, copy=copy, track=track) buffer = memoryview(message) array = np.frombuffer(buffer, dtype=dictionary['dtype']) return array.reshape(dictionary['shape'])
def send_msg(message_parts: List[bytes], socket: zmq.Socket): """ Send multipart message over socket Parameters ---------- message_parts messages to send socket socket to send over """ socket.send_multipart([message for message in message_parts])
def casting_address_handler(store: DirectoryServerStore, sock: Socket, argframes: List[Frame], id_frame: Frame) -> None: device_name = str(argframes.pop(0).bytes, encoding='utf8') address = str(argframes.pop(0).bytes, encoding='utf8') if device_name not in store.devices: store.devices[device_name] = Device(device_name, []) device = store.devices[device_name] if address not in device.cast_addresses: device.cast_addresses.append(address) print("Device {} casted entry point {}".format(device_name, address)) reply = [id_frame, Frame(), Frame(bytes([0]))] sock.send_multipart(reply)
def send_frame(socket: zmq.Socket, fm: Frame, flags: int = 0, **kw) -> None: """ Send a `Frame` object over a zmq socket. """ data = fm.data md = { 'shape': data.shape, 'dtype': str(data.dtype), 'index': fm.index, 'time': fm.time } socket.send_json(md, flags | zmq.SNDMORE) socket.send(data, **kw)
async def periodic_send(socket: zmq.Socket): rate = 100.0 while True: bid = await get_rate(rate) ask = await get_rate(rate) if bid > ask: tmp = bid bid = ask ask = tmp rateobj = {"ask": ask, "bid": bid} print(rateobj) socket.send_multipart([b"TEST", json.dumps(rateobj).encode('utf-8')]) await asyncio.sleep(1.0)
def send_array( socket: zmq.Socket, data: np.ndarray, flags: int = 0, copy: bool = True, track: bool = False, ) -> None: """ Send a ndarray. """ md = {'shape': data.shape, 'dtype': str(data.dtype)} socket.send_json(md, flags | zmq.SNDMORE) socket.send(data, flags, copy, track)
def file_get_handler(store: DirectoryServerStore, sock: Socket, argframes: List[Frame], id_frame: Frame) -> None: filename = str(argframes.pop(0).bytes, encoding='utf8') if filename in store.files: vfile = store.files[filename] device_names = list(map(lambda d: d.name, vfile.declared_devices)) sock.send_multipart([ id_frame, Frame(), Frame(bytes([0])), Frame(bytes(json.dumps(device_names), 'utf8')) ]) else: sock.send_multipart([id_frame, Frame(), Frame(bytes([1]))])
def send_array(socket: zmq.Socket, array: np.array, flags: int = 0, copy: bool = True, track: bool = False): """ Send a numpy array with metadata, type and shape """ dictionary = dict( dtype=str(array.dtype), shape=array.shape, ) socket.send_json(dictionary, flags | zmq.SNDMORE) return socket.send(array, flags, copy=copy, track=track)
def _publish_data(publish_socket: zmq.Socket, machine_name: str, machine_data: Dict[Any, str]): """Publishes machine data over publish socket Parameters ---------- publish_socket : zmq.Socket socket to publish machine_name : str name of machine interface, used as topic for publishing machine_data : Dict[Any, str] machine data dictionary to publish """ publish_socket.send_multipart( [bytes(machine_name, "utf-8"), machine_data])
def __init__(self, factory, endpoint=None, identity=None): """ Constructor. One endpoint is passed to the constructor, more could be added via call to :meth:`addEndpoints`. :param factory: ZeroMQ Twisted factory :type factory: :class:`ZmqFactory` :param endpoint: ZeroMQ address for connect/bind :type endpoint: :class:`ZmqEndpoint` :param identity: socket identity (ZeroMQ), don't set unless you know how it works :type identity: str """ self.factory = factory self.endpoints = [] self.identity = identity self.socket = Socket(factory.context, self.socketType) self.queue = deque() self.recv_parts = [] self.read_scheduled = None self.fd = self.socket.get(constants.FD) self.socket.set(constants.LINGER, factory.lingerPeriod) if not ZMQ3: self.socket.set(constants.MCAST_LOOP, int(self.allowLoopbackMulticast)) self.socket.set(constants.RATE, self.multicastRate) if not ZMQ3: self.socket.set(constants.HWM, self.highWaterMark) else: self.socket.set(constants.SNDHWM, self.highWaterMark) self.socket.set(constants.RCVHWM, self.highWaterMark) if ZMQ3 and self.tcpKeepalive: self.socket.set(constants.TCP_KEEPALIVE, self.tcpKeepalive) self.socket.set(constants.TCP_KEEPALIVE_CNT, self.tcpKeepaliveCount) self.socket.set(constants.TCP_KEEPALIVE_IDLE, self.tcpKeepaliveIdle) self.socket.set(constants.TCP_KEEPALIVE_INTVL, self.tcpKeepaliveInterval) if ZMQ3 and self.reconnectInterval: self.socket.set(constants.RECONNECT_IVL, self.reconnectInterval) if ZMQ3 and self.reconnectIntervalMax: self.socket.set(constants.RECONNECT_IVL_MAX, self.reconnectIntervalMax) if self.identity is not None: self.socket.set(constants.IDENTITY, self.identity) if endpoint: self.addEndpoints([endpoint]) self.factory.connections.add(self) self.factory.reactor.addReader(self) self.doRead()
async def async_recv_pull_msg(subscriber_socket: zmq.Socket) -> dict: while True: try: data = subscriber_socket.recv_json(flags=zmq.NOBLOCK) return data except zmq.error.Again: pass await asyncio.sleep(0.1)
def __init__(self, factory, endpoint=None, identity=None): """ Constructor. One endpoint is passed to the constructor, more could be added via call to C{addEndpoints}. @param factory: ZeroMQ Twisted factory @type factory: L{ZmqFactory} @param endpoint: ZeroMQ address for connect/bind @type endpoint: C{list} of L{ZmqEndpoint} @param identity: socket identity (ZeroMQ) @type identity: C{str} """ self.factory = factory self.endpoints = [] self.identity = identity self.socket = Socket(factory.context, self.socketType) self.queue = deque() self.recv_parts = [] self.read_scheduled = None self.fd = self.socket_get(constants.FD) self.socket_set(constants.LINGER, factory.lingerPeriod) if not ZMQ3: self.socket_set( constants.MCAST_LOOP, int(self.allowLoopbackMulticast)) self.socket_set(constants.RATE, self.multicastRate) if not ZMQ3: self.socket_set(constants.HWM, self.highWaterMark) else: self.socket_set(constants.SNDHWM, self.highWaterMark) self.socket_set(constants.RCVHWM, self.highWaterMark) if ZMQ3 and self.tcpKeepalive: self.socket_set( constants.TCP_KEEPALIVE, self.tcpKeepalive) self.socket_set( constants.TCP_KEEPALIVE_CNT, self.tcpKeepaliveCount) self.socket_set( constants.TCP_KEEPALIVE_IDLE, self.tcpKeepaliveIdle) self.socket_set( constants.TCP_KEEPALIVE_INTVL, self.tcpKeepaliveInterval) if self.identity is not None: self.socket_set(constants.IDENTITY, self.identity) if endpoint: self.addEndpoints([endpoint]) self.factory.connections.add(self) self.factory.reactor.addReader(self) self.doRead()
def __init__(self, endpoints, identity=None, **kwargs): """ Constructor. :param factory: ZeroMQ Twisted factory :type factory: :class:`ZmqFactory` :param identity: socket identity (ZeroMQ), don't set unless you know how it works :type identity: str """ super(ZmqConnection, self).__init__() self.factory = ZmqContextManager() self.endpoints = [] self.identity = identity self.socket = Socket(self.factory.context, self.socketType) self.queue = deque() self.recv_parts = [] self.read_scheduled = None self.shutted_down = False self.pickles_compression = "snappy" self._last_read_time = 0.0 self.fd = self.socket.get(constants.FD) self.socket.set(constants.LINGER, self.factory.lingerPeriod) self.socket.set(constants.RATE, self.multicastRate) self.socket.set(constants.SNDHWM, self.highWaterMark) self.socket.set(constants.RCVHWM, self.highWaterMark) if ZMQ3 and self.tcpKeepalive: self.socket.set(constants.TCP_KEEPALIVE, self.tcpKeepalive) self.socket.set(constants.TCP_KEEPALIVE_CNT, self.tcpKeepaliveCount) self.socket.set(constants.TCP_KEEPALIVE_IDLE, self.tcpKeepaliveIdle) self.socket.set(constants.TCP_KEEPALIVE_INTVL, self.tcpKeepaliveInterval) if self.identity is not None: self.socket.set(constants.IDENTITY, self.identity) self.endpoints = endpoints self.rnd_vals = self._connectOrBind(endpoints) self.factory.connections.add(self) self.factory.reactor.addReader(self) self.doRead()
def __init__(self, context, socket_type): _original_Socket.__init__(self, context, socket_type) self.__in_send_multipart = False self.__in_recv_multipart = False self.__setup_events()
class ZmqConnection(object): """ Connection through ZeroMQ, wraps up ZeroMQ socket. @cvar socketType: socket type, from ZeroMQ @cvar allowLoopbackMulticast: is loopback multicast allowed? @type allowLoopbackMulticast: C{boolean} @cvar multicastRate: maximum allowed multicast rate, kbps @type multicastRate: C{int} @cvar highWaterMark: hard limit on the maximum number of outstanding messages 0MQ shall queue in memory for any single peer @type highWaterMark: C{int} @ivar factory: ZeroMQ Twisted factory reference @type factory: L{ZmqFactory} @ivar socket: ZeroMQ Socket @type socket: L{Socket} @ivar endpoints: ZeroMQ addresses for connect/bind @type endpoints: C{list} of L{ZmqEndpoint} @ivar fd: file descriptor of zmq mailbox @type fd: C{int} @ivar queue: output message queue @type queue: C{deque} """ implements(IReadDescriptor, IFileDescriptor) socketType = None allowLoopbackMulticast = False multicastRate = 100 highWaterMark = 0 # Only supported by zeromq3 and pyzmq>=2.2.0.1 tcpKeepalive = 0 tcpKeepaliveCount = 0 tcpKeepaliveIdle = 0 tcpKeepaliveInterval = 0 def __init__(self, factory, endpoint=None, identity=None): """ Constructor. One endpoint is passed to the constructor, more could be added via call to C{addEndpoints}. @param factory: ZeroMQ Twisted factory @type factory: L{ZmqFactory} @param endpoint: ZeroMQ address for connect/bind @type endpoint: C{list} of L{ZmqEndpoint} @param identity: socket identity (ZeroMQ) @type identity: C{str} """ self.factory = factory self.endpoints = [] self.identity = identity self.socket = Socket(factory.context, self.socketType) self.queue = deque() self.recv_parts = [] self.read_scheduled = None self.fd = self.socket_get(constants.FD) self.socket_set(constants.LINGER, factory.lingerPeriod) if not ZMQ3: self.socket_set( constants.MCAST_LOOP, int(self.allowLoopbackMulticast)) self.socket_set(constants.RATE, self.multicastRate) if not ZMQ3: self.socket_set(constants.HWM, self.highWaterMark) else: self.socket_set(constants.SNDHWM, self.highWaterMark) self.socket_set(constants.RCVHWM, self.highWaterMark) if ZMQ3 and self.tcpKeepalive: self.socket_set( constants.TCP_KEEPALIVE, self.tcpKeepalive) self.socket_set( constants.TCP_KEEPALIVE_CNT, self.tcpKeepaliveCount) self.socket_set( constants.TCP_KEEPALIVE_IDLE, self.tcpKeepaliveIdle) self.socket_set( constants.TCP_KEEPALIVE_INTVL, self.tcpKeepaliveInterval) if self.identity is not None: self.socket_set(constants.IDENTITY, self.identity) if endpoint: self.addEndpoints([endpoint]) self.factory.connections.add(self) self.factory.reactor.addReader(self) self.doRead() def addEndpoints(self, endpoints): """ Add more connection endpoints. Connection may have many endpoints, mixing protocols and types. @param endpoints: list of endpoints to add @type endpoints: C{list} """ self.endpoints.extend(endpoints) self._connectOrBind(endpoints) def shutdown(self): """ Shutdown connection and socket. """ self.factory.reactor.removeReader(self) self.factory.connections.discard(self) self.socket.close() self.socket = None self.factory = None if self.read_scheduled is not None: self.read_scheduled.cancel() self.read_scheduled = None def __repr__(self): return "%s(%r, %r)" % ( self.__class__.__name__, self.factory, self.endpoints) def fileno(self): """ Part of L{IFileDescriptor}. @return: The platform-specified representation of a file descriptor number. """ return self.fd def connectionLost(self, reason): """ Called when the connection was lost. Part of L{IFileDescriptor}. This is called when the connection on a selectable object has been lost. It will be called whether the connection was closed explicitly, an exception occurred in an event handler, or the other end of the connection closed it first. @param reason: A failure instance indicating the reason why the connection was lost. L{error.ConnectionLost} and L{error.ConnectionDone} are of special note, but the failure may be of other classes as well. """ if self.factory: self.factory.reactor.removeReader(self) def _readMultipart(self): """ Read multipart in non-blocking manner, returns with ready message or raising exception (in case of no more messages available). """ while True: self.recv_parts.append(self.socket.recv(constants.NOBLOCK)) if not self.socket_get(constants.RCVMORE): result, self.recv_parts = self.recv_parts, [] return result def doRead(self): """ Some data is available for reading on your descriptor. ZeroMQ is signalling that we should process some events, we're starting to to receive incoming messages. Part of L{IReadDescriptor}. """ if self.read_scheduled is not None: if not self.read_scheduled.called: self.read_scheduled.cancel() self.read_scheduled = None while True: if self.factory is None: # disconnected return events = self.socket_get(constants.EVENTS) if (events & constants.POLLIN) != constants.POLLIN: return try: message = self._readMultipart() except error.ZMQError as e: if e.errno == constants.EAGAIN: continue raise e log.callWithLogger(self, self.messageReceived, message) def logPrefix(self): """ Part of L{ILoggingContext}. @return: Prefix used during log formatting to indicate context. @rtype: C{str} """ return 'ZMQ' def send(self, message): """ Send message via ZeroMQ. Sending is performed directly to ZeroMQ without queueing. If HWM is reached on ZeroMQ side, sending operation is aborted with exception from ZeroMQ (EAGAIN). @param message: message data @type message: message could be either list of parts or single part (str) """ if not hasattr(message, '__iter__'): self.socket.send(message, constants.NOBLOCK) else: for m in message[:-1]: self.socket.send(m, constants.NOBLOCK | constants.SNDMORE) self.socket.send(message[-1], constants.NOBLOCK) if self.read_scheduled is None: self.read_scheduled = reactor.callLater(0, self.doRead) def messageReceived(self, message): """ Called on incoming message from ZeroMQ. @param message: message data """ raise NotImplementedError(self) def _connectOrBind(self, endpoints): """ Connect and/or bind socket to endpoints. """ for endpoint in endpoints: if endpoint.type == ZmqEndpointType.connect: self.socket.connect(endpoint.address) elif endpoint.type == ZmqEndpointType.bind: self.socket.bind(endpoint.address) else: assert False, "Unknown endpoint type %r" % endpoint # Compatibility shims def socket_get(self, constant): return self.socket.get(constant) def socket_set(self, constant, value): return self.socket.set(constant, value)
class ZmqConnection(Logger): """ Connection through ZeroMQ, wraps up ZeroMQ socket. This class isn't supposed to be used directly, instead use one of the descendants like :class:`ZmqPushConnection`. :class:`ZmqConnection` implements glue between ZeroMQ and Twisted reactor: putting polling ZeroMQ file descriptor into reactor, processing events, reading data from socket. :var socketType: socket type, from ZeroMQ :var allowLoopbackMulticast: is loopback multicast allowed? :vartype allowLoopbackMulticast: bool :var multicastRate: maximum allowed multicast rate, kbps :vartype multicastRate: int :var highWaterMark: hard limit on the maximum number of outstanding messages 0MQ shall queue in memory for any single peer :vartype highWaterMark: int :var socket: ZeroMQ Socket :vartype socket: zmq.Socket :var endpoints: ZeroMQ addresses for connect/bind :vartype endpoints: list of :class:`ZmqEndpoint` :var fd: file descriptor of zmq mailbox :vartype fd: int :var queue: output message queue :vartype queue: deque """ class IOOverflow(Exception): pass socketType = None allowLoopbackMulticast = False multicastRate = 100 highWaterMark = 0 # Only supported by zeromq3 and pyzmq>=2.2.0.1 tcpKeepalive = 0 tcpKeepaliveCount = 0 tcpKeepaliveIdle = 0 tcpKeepaliveInterval = 0 PICKLE_START = b"vpb" PICKLE_END = b"vpe" CODECS = {None: b"\x00", "": b"\x00", "gzip": b"\x01", "snappy": b"\x02", "xz": b"\x03"} def __init__(self, endpoints, identity=None, **kwargs): """ Constructor. :param factory: ZeroMQ Twisted factory :type factory: :class:`ZmqFactory` :param identity: socket identity (ZeroMQ), don't set unless you know how it works :type identity: str """ super(ZmqConnection, self).__init__() self.factory = ZmqContextManager() self.endpoints = [] self.identity = identity self.socket = Socket(self.factory.context, self.socketType) self.queue = deque() self.recv_parts = [] self.read_scheduled = None self.shutted_down = False self.pickles_compression = "snappy" self._last_read_time = 0.0 self.fd = self.socket.get(constants.FD) self.socket.set(constants.LINGER, self.factory.lingerPeriod) self.socket.set(constants.RATE, self.multicastRate) self.socket.set(constants.SNDHWM, self.highWaterMark) self.socket.set(constants.RCVHWM, self.highWaterMark) if ZMQ3 and self.tcpKeepalive: self.socket.set(constants.TCP_KEEPALIVE, self.tcpKeepalive) self.socket.set(constants.TCP_KEEPALIVE_CNT, self.tcpKeepaliveCount) self.socket.set(constants.TCP_KEEPALIVE_IDLE, self.tcpKeepaliveIdle) self.socket.set(constants.TCP_KEEPALIVE_INTVL, self.tcpKeepaliveInterval) if self.identity is not None: self.socket.set(constants.IDENTITY, self.identity) self.endpoints = endpoints self.rnd_vals = self._connectOrBind(endpoints) self.factory.connections.add(self) self.factory.reactor.addReader(self) self.doRead() def shutdown(self): """ Shutdown (close) connection and ZeroMQ socket. """ if self.shutted_down: return self.shutted_down = True self.factory.reactor.removeReader(self) self.factory.connections.discard(self) self.socket.close() self.socket = None self.factory = None if self.read_scheduled is not None: self.read_scheduled.cancel() self.read_scheduled = None def __repr__(self): return "%s(%r, %r)" % (self.__class__.__name__, self.factory, self.endpoints) def fileno(self): """ Implementation of :class:`IFileDescriptor <twisted.internet.interfaces.IFileDescriptor>`. Returns ZeroMQ polling file descriptor. :return: The platform-specified representation of a file descriptor number. """ return self.fd @property def pickles_compression(self): return self._pickles_compression @pickles_compression.setter def pickles_compression(self, value): if value not in (None, "", "gzip", "snappy", "xz"): raise ValueError() self._pickles_compression = value def connectionLost(self, reason): """ Called when the connection was lost. Implementation of :class:`IFileDescriptor <twisted.internet.interfaces.IFileDescriptor>`. This is called when the connection on a selectable object has been lost. It will be called whether the connection was closed explicitly, an exception occurred in an event handler, or the other end of the connection closed it first. """ if self.factory: self.factory.reactor.removeReader(self) def _readMultipart(self, unpickler): """ Read multipart in non-blocking manner, returns with ready message or raising exception (in case of no more messages available). """ while True: part = self.socket.recv(constants.NOBLOCK) if part.startswith(ZmqConnection.PICKLE_START): self.messageHeaderReceived(self.recv_parts) unpickler.active = True unpickler.codec = part[len(ZmqConnection.PICKLE_START)] continue if part == ZmqConnection.PICKLE_END: unpickler.active = False obj = unpickler.object if isinstance(obj, SharedIO): obj = pickle.load(obj) self.recv_parts.append(obj) elif not unpickler.active: self.recv_parts.append(part) else: unpickler.consume(part) continue if not self.socket.get(constants.RCVMORE): result, self.recv_parts = self.recv_parts, [] return result class Unpickler(object): def __init__(self): self._data = [] self._active = False self._decompressor = None @property def active(self): return self._active @active.setter def active(self, value): self._active = value if not value: buffer = self.merge_chunks() self._object = pickle.loads(buffer if six.PY3 else str(buffer)) self._data = [] @property def codec(self): return self._codec @codec.setter def codec(self, value): self._codec = value if six.PY3 else ord(value) if self.codec == 0: pass elif self.codec == 1: self._decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS) elif self.codec == 2: self._decompressor = snappy.StreamDecompressor() elif self.codec == 3: self._decompressor = lzma.LZMADecompressor() else: raise ValueError("Unknown compression type") @property def object(self): return self._object def merge_chunks(self): if self.codec > 0 and not isinstance(self._decompressor, lzma.LZMADecompressor): self._data.append(self._decompressor.flush()) size = sum([len(d) for d in self._data]) buffer = bytearray(size) pos = 0 for d in self._data: ld = len(d) buffer[pos : pos + ld] = d pos += ld return buffer def consume(self, data): if self.codec > 0: data = self._decompressor.decompress(data) self._data.append(data) def doRead(self): """ Some data is available for reading on ZeroMQ descriptor. ZeroMQ is signalling that we should process some events, we're starting to receive incoming messages. Implementation of :class:`IReadDescriptor <twisted.internet.interfaces.IReadDescriptor>`. """ if self.shutted_down: return if self.read_scheduled is not None: if not self.read_scheduled.called: self.read_scheduled.cancel() self.read_scheduled = None unpickler = ZmqConnection.Unpickler() while True: if self.factory is None: # disconnected return events = self.socket.get(constants.EVENTS) if (events & constants.POLLIN) != constants.POLLIN: return timestamp = time.time() try: message = self._readMultipart(unpickler) except error.ZMQError as e: if e.errno == constants.EAGAIN: continue raise e finally: self._last_read_time = time.time() - timestamp log.callWithLogger(self, self.messageReceived, message) @property def last_read_time(self): return self._last_read_time def logPrefix(self): """ Implementation of :class:`ILoggingContext <twisted.internet.interfaces.ILoggingContext>`. :return: Prefix used during log formatting to indicate context. :rtype: str """ return "ZMQ" def send(self, *message, **kwargs): """ Send message via ZeroMQ socket. Sending is performed directly to ZeroMQ without queueing. If HWM is reached on ZeroMQ side, sending operation is aborted with exception from ZeroMQ (EAGAIN). After writing read is scheduled as ZeroMQ may not signal incoming messages after we touched socket with write request. :param message: message data, a series of objects; if an object is\ an instance of bytes, it will be sent as-is, otherwise, it will be\ pickled and optionally compressed. Object must not be a string. :param pickles_compression: the compression to apply to pickled\ objects. Supported values are None or "", "gzip", "snappy" and "xz". :type pickles_compression: str :param io: a SharedIO object where to put pickles into instead of the\ socket. Can be None. """ if self.shutted_down: return pickles_compression = kwargs.get("pickles_compression", "snappy") pickles_size = 0 io = kwargs.get("io") io_overflow = False def send_part(msg, last): flag = constants.SNDMORE if not last else 0 if isinstance(msg, bytes): self.socket.send(msg, constants.NOBLOCK | flag) return 0 if isinstance(msg, str): raise ValueError("All strings must be encoded into bytes") return self._send_pickled(msg, last, pickles_compression, io if not io_overflow else None) for i, m in enumerate(message): try: pickles_size += send_part(m, i == len(message) - 1) except ZmqConnection.IOOverflow: io_overflow = True if self.read_scheduled is None: self.read_scheduled = reactor.callLater(0, self.doRead) if io_overflow: raise ZmqConnection.IOOverflow() return pickles_size class SocketFile(object): def __init__(self, socket): self._socket = socket self._size = 0 @property def size(self): return self._size @property def mode(self): return "wb" def write(self, data): self._size += len(data) self._socket.send(data, constants.NOBLOCK | constants.SNDMORE) def flush(self): pass class CompressedFile(object): def __init__(self, fileobj, compressor): self._file = fileobj self._compressor = compressor @property def mode(self): return "wb" def write(self, data): self._file.write(self._compressor.compress(data)) def flush(self): last = self._compressor.flush() if last is not None: self._file.write(last) self._file.flush() class Pickler(object): def __init__(self, socket, codec): self._codec = codec if six.PY3 else ord(codec) self._socketobj = ZmqConnection.SocketFile(socket) if self.codec == 0: self._compressor = self._socketobj elif self.codec == 1: self._compressor = gzip.GzipFile(fileobj=self._socketobj) elif self.codec == 2: self._compressor = ZmqConnection.CompressedFile(self._socketobj, snappy.StreamCompressor()) elif self.codec == 3: self._compressor = ZmqConnection.CompressedFile(self._socketobj, lzma.LZMACompressor(lzma.FORMAT_XZ)) else: raise ValueError("Unknown compression type") @property def size(self): return self._socketobj.size @property def codec(self): return self._codec @property def mode(self): return "wb" def write(self, data): self._compressor.write(data) def flush(self): self._compressor.flush() def _send_pickled(self, message, last, compression, io): if self.shutted_down: return codec = ZmqConnection.CODECS.get(compression) if codec is None: raise ValueError("Unknown compression type: %s" % compression) def send_pickle_beg_marker(codec): self.socket.send(ZmqConnection.PICKLE_START + codec, constants.NOBLOCK | constants.SNDMORE) def dump(file): pickle.dump(message, file, protocol=best_protocol) def send_pickle_end_marker(): self.socket.send(ZmqConnection.PICKLE_END, constants.NOBLOCK | (constants.SNDMORE if not last else 0)) def send_to_socket(): send_pickle_beg_marker(codec) pickler = ZmqConnection.Pickler(self.socket, codec[0]) dump(pickler) pickler.flush() send_pickle_end_marker() return pickler.size if io is None: return send_to_socket() else: try: initial_pos = io.tell() dump(io) new_pos = io.tell() send_pickle_beg_marker(b"\x00") io.seek(initial_pos) self.socket.send(pickle.dumps(io, protocol=best_protocol), constants.NOBLOCK | constants.SNDMORE) io.seek(new_pos) send_pickle_end_marker() return new_pos - initial_pos except ValueError: send_to_socket() raise ZmqConnection.IOOverflow() def messageReceived(self, message): """ Called when complete message is received. Not implemented in :class:`ZmqConnection`, should be overridden to handle incoming messages. :param message: message data """ raise NotImplementedError(self) def messageHeaderReceived(self, header): pass def _connectOrBind(self, endpoints): """ Connect and/or bind socket to endpoints. """ rnd_vals = [] for endpoint in endpoints: if endpoint.type == ZmqEndpointType.connect: self.debug("Connecting to %s...", endpoint) self.socket.connect(endpoint.address) elif endpoint.type == ZmqEndpointType.bind: self.debug("Binding to %s...", endpoint) if endpoint.address.startswith("rndtcp://") or endpoint.address.startswith("rndepgm://"): try: endpos = endpoint.address.find("://") + 3 proto = endpoint.address[3:endpos] splitted = endpoint.address[endpos:].split(":") min_port, max_port, max_tries = splitted[-3:] addr = ":".join(splitted[:-3]) except ValueError: raise from_none(ValueError("Failed to parse %s" % endpoint.address)) try: rnd_vals.append( self.socket.bind_to_random_port(proto + addr, int(min_port), int(max_port), int(max_tries)) ) except ZMQError as e: self.warning("Failed to bind to %s%s: ZMQError: %s", proto, addr, e) elif endpoint.address.startswith("rndipc://"): prefix, suffix = endpoint.address[9:].split(":") ipc_fd, ipc_fn = mkstemp(suffix, prefix) self.socket.bind("ipc://" + ipc_fn) rnd_vals.append(ipc_fn) os.close(ipc_fd) else: self.socket.bind(endpoint.address) else: assert False, "Unknown endpoint type %r" % endpoint return rnd_vals
class ZmqConnection(object): """ Connection through ZeroMQ, wraps up ZeroMQ socket. This class isn't supposed to be used directly, instead use one of the descendants like :class:`ZmqPushConnection`. :class:`ZmqConnection` implements glue between ZeroMQ and Twisted reactor: putting polling ZeroMQ file descriptor into reactor, processing events, reading data from socket. :var socketType: socket type, from ZeroMQ :var allowLoopbackMulticast: is loopback multicast allowed? :vartype allowLoopbackMulticast: bool :var multicastRate: maximum allowed multicast rate, kbps :vartype multicastRate: int :var highWaterMark: hard limit on the maximum number of outstanding messages 0MQ shall queue in memory for any single peer :vartype highWaterMark: int :var factory: ZeroMQ Twisted factory reference :vartype factory: :class:`ZmqFactory` :var socket: ZeroMQ Socket :vartype socket: zmq.Socket :var endpoints: ZeroMQ addresses for connect/bind :vartype endpoints: list of :class:`ZmqEndpoint` :var fd: file descriptor of zmq mailbox :vartype fd: int :var queue: output message queue :vartype queue: deque """ socketType = None allowLoopbackMulticast = False multicastRate = 100 highWaterMark = 0 # Only supported by zeromq3 and pyzmq>=2.2.0.1 tcpKeepalive = 0 tcpKeepaliveCount = 0 tcpKeepaliveIdle = 0 tcpKeepaliveInterval = 0 def __init__(self, factory, endpoint=None, identity=None): """ Constructor. One endpoint is passed to the constructor, more could be added via call to :meth:`addEndpoints`. :param factory: ZeroMQ Twisted factory :type factory: :class:`ZmqFactory` :param endpoint: ZeroMQ address for connect/bind :type endpoint: :class:`ZmqEndpoint` :param identity: socket identity (ZeroMQ), don't set unless you know how it works :type identity: str """ self.factory = factory self.endpoints = [] self.identity = identity self.socket = Socket(factory.context, self.socketType) self.queue = deque() self.recv_parts = [] self.read_scheduled = None self.fd = self.socket.get(constants.FD) self.socket.set(constants.LINGER, factory.lingerPeriod) if not ZMQ3: self.socket.set( constants.MCAST_LOOP, int(self.allowLoopbackMulticast)) self.socket.set(constants.RATE, self.multicastRate) if not ZMQ3: self.socket.set(constants.HWM, self.highWaterMark) else: self.socket.set(constants.SNDHWM, self.highWaterMark) self.socket.set(constants.RCVHWM, self.highWaterMark) if ZMQ3 and self.tcpKeepalive: self.socket.set( constants.TCP_KEEPALIVE, self.tcpKeepalive) self.socket.set( constants.TCP_KEEPALIVE_CNT, self.tcpKeepaliveCount) self.socket.set( constants.TCP_KEEPALIVE_IDLE, self.tcpKeepaliveIdle) self.socket.set( constants.TCP_KEEPALIVE_INTVL, self.tcpKeepaliveInterval) if self.identity is not None: self.socket.set(constants.IDENTITY, self.identity) if endpoint: self.addEndpoints([endpoint]) self.factory.connections.add(self) self.factory.reactor.addReader(self) self.doRead() def addEndpoints(self, endpoints): """ Add more connection endpoints. Connection may have many endpoints, mixing ZeroMQ protocols (TCP, IPC, ...) and types (connect or bind). :param endpoints: list of endpoints to add :type endpoints: list of :class:`ZmqEndpoint` """ self.endpoints.extend(endpoints) self._connectOrBind(endpoints) def shutdown(self): """ Shutdown (close) connection and ZeroMQ socket. """ self.factory.reactor.removeReader(self) self.factory.connections.discard(self) self.socket.close() self.socket = None self.factory = None if self.read_scheduled is not None: self.read_scheduled.cancel() self.read_scheduled = None def __repr__(self): return "%s(%r, %r)" % ( self.__class__.__name__, self.factory, self.endpoints) def fileno(self): """ Implementation of :tm:`IFileDescriptor <internet.interfaces.IFileDescriptor>`. Returns ZeroMQ polling file descriptor. :return: The platform-specified representation of a file descriptor number. """ return self.fd def connectionLost(self, reason): """ Called when the connection was lost. Implementation of :tm:`IFileDescriptor <internet.interfaces.IFileDescriptor>`. This is called when the connection on a selectable object has been lost. It will be called whether the connection was closed explicitly, an exception occurred in an event handler, or the other end of the connection closed it first. """ if self.factory: self.factory.reactor.removeReader(self) def _readMultipart(self): """ Read multipart in non-blocking manner, returns with ready message or raising exception (in case of no more messages available). """ while True: self.recv_parts.append(self.socket.recv(constants.NOBLOCK)) if not self.socket.get(constants.RCVMORE): result, self.recv_parts = self.recv_parts, [] return result def doRead(self): """ Some data is available for reading on ZeroMQ descriptor. ZeroMQ is signalling that we should process some events, we're starting to receive incoming messages. Implementation of :tm:`IReadDescriptor <internet.interfaces.IReadDescriptor>`. """ if self.read_scheduled is not None: if not self.read_scheduled.called: self.read_scheduled.cancel() self.read_scheduled = None while True: if self.factory is None: # disconnected return events = self.socket.get(constants.EVENTS) if (events & constants.POLLIN) != constants.POLLIN: return try: message = self._readMultipart() except error.ZMQError as e: if e.errno == constants.EAGAIN: continue raise e log.callWithLogger(self, self.messageReceived, message) def logPrefix(self): """ Implementation of :tm:`ILoggingContext <internet.interfaces.ILoggingContext>`. :return: Prefix used during log formatting to indicate context. :rtype: str """ return 'ZMQ' def send(self, message): """ Send message via ZeroMQ socket. Sending is performed directly to ZeroMQ without queueing. If HWM is reached on ZeroMQ side, sending operation is aborted with exception from ZeroMQ (EAGAIN). After writing read is scheduled as ZeroMQ may not signal incoming messages after we touched socket with write request. :param message: message data, could be either list of str (multipart message) or just str :type message: str or list of str """ if isinstance(message, bytes): self.socket.send(message, constants.NOBLOCK) else: for m in message[:-1]: self.socket.send(m, constants.NOBLOCK | constants.SNDMORE) self.socket.send(message[-1], constants.NOBLOCK) if self.read_scheduled is None: self.read_scheduled = reactor.callLater(0, self.doRead) def messageReceived(self, message): """ Called when complete message is received. Not implemented in :class:`ZmqConnection`, should be overridden to handle incoming messages. :param message: message data """ raise NotImplementedError(self) def _connectOrBind(self, endpoints): """ Connect and/or bind socket to endpoints. """ for endpoint in endpoints: if endpoint.type == ZmqEndpointType.connect: self.socket.connect(endpoint.address) elif endpoint.type == ZmqEndpointType.bind: self.socket.bind(endpoint.address) else: assert False, "Unknown endpoint type %r" % endpoint