class Container(object): def __init__(self, *handlers, **kwargs): self.tornado_loop = kwargs.get('loop', tornado.ioloop.IOLoop.instance()) kwargs['global_handler'] = TornadoLoopHandler(self.tornado_loop, kwargs.get('handler_base', None)) self.container = BaseContainer(*handlers, **kwargs) def initialise(self): self.container.start() self.container.process() def run(self): self.initialise() self.tornado_loop.start() def stop(self): self.container.stop() def touch(self): self._process() def _process(self): self.container.process() if not self.container.quiesced: self.tornado_loop.add_callback(self._process)
# ignore duplicate message return if self.expected == 0 or self.received < self.expected: print(event.message.body) self.received += 1 if self.received == self.expected: event.receiver.close() event.connection.close() parser = optparse.OptionParser(usage="usage: %prog [options]") parser.add_option( "-a", "--address", default="localhost:5672/examples", help="address from which messages are received (default %default)") parser.add_option( "-m", "--messages", type="int", default=100, help= "number of messages to receive; 0 receives indefinitely (default %default)" ) opts, args = parser.parse_args() try: Container(Recv(opts.address, opts.messages)).run() except KeyboardInterrupt: pass
"""Event callback for when a sent message is accepted by the broker""" self.confirmed += 1 if self.confirmed == self.total: event.connection.close() def on_disconnected(self, event): """Event callback for when the broker disconnects with the client""" self.sent = self.confirmed def get_remote_properties(self): """Return the remote (broker) properties""" return self.remote_properties # --- main --- # Args: 1: Broker address (ip-addr:port) # 2: Queue name # 3: Test type # 4: Test args try: SENDER = AmqpFeaturesTestSender(sys.argv[1], sys.argv[2], sys.argv[3], loads(sys.argv[4])) Container(SENDER).run() print sys.argv[3] if sys.argv[3] == 'connection_property': print dumps(SENDER.get_remote_properties()) except KeyboardInterrupt: pass except Exception as exc: print os.path.basename(sys.argv[0]), 'EXCEPTION:', exc print format_exc()
def test_single_connection_protocol_trace(self): qd_manager = QdManager(self, self.address) # Turn off trace logging on all connections. qd_manager.update("org.apache.qpid.dispatch.log", {"enable": "info+"}, name="log/DEFAULT") TEST_ADDR_1 = "EnableConnectionLevelProtocolTraceTest1" MSG_BODY = "EnableConnectionLevelProtocolTraceTestMessage1" CONTAINER_ID_1 = "CONTAINERID_1" container_1 = Container() container_1.container_id = CONTAINER_ID_1 conn_1 = BlockingConnection(self.address, container=container_1) TEST_ADDR_2 = "EnableConnectionLevelProtocolTraceTest1" CONTAINER_ID_2 = "CONTAINERID_2" container_2 = Container() container_2.container_id = CONTAINER_ID_2 conn_2 = BlockingConnection(self.address, container=container_2) results = qd_manager.query("org.apache.qpid.dispatch.connection") conn_id = None for result in results: if result[u'container'] == CONTAINER_ID_1: conn_id = result[u'identity'] # Turn on trace logging for connection with identity conn_id qd_manager.update("org.apache.qpid.dispatch.connection", {"enableProtocolTrace": "true"}, identity=conn_id) blocking_receiver_1 = conn_1.create_receiver(address=TEST_ADDR_1) blocking_sender_1 = conn_1.create_sender(address=TEST_ADDR_1, options=apply_options) blocking_receiver_2 = conn_2.create_receiver(address=TEST_ADDR_2) blocking_sender_2 = conn_2.create_sender(address=TEST_ADDR_2, options=apply_options) num_attaches_1 = 0 num_attaches_2 = 0 logs = qd_manager.get_log() for log in logs: if u'PROTOCOL' in log[0]: if "@attach" in log[2] and TEST_ADDR_1 in log[2]: num_attaches_1 += 1 elif "@attach" in log[2] and TEST_ADDR_2 in log[2]: num_attaches_2 += 1 # num_attaches_1 for address TEST_ADDR_1 must be 4, two attaches to/from sender and receiver self.assertTrue(num_attaches_1 == 4) # num_attaches_2 for address TEST_ADDR_2 must be 0 since trace was not # turned on for that connection self.assertTrue(num_attaches_2 == 0) # Now turn off the connection tracing on that connection qd_manager.update("org.apache.qpid.dispatch.connection", {"enableProtocolTrace": "off"}, identity=conn_id) blocking_receiver_1.close() blocking_sender_1.close() # Since tracing was turned off, there should be no detaches logs = qd_manager.get_log() num_detaches = 0 for log in logs: if u'PROTOCOL' in log[0]: if "@detach" in log[2]: num_detaches += 1 self.assertTrue(num_detaches == 0) blocking_receiver_2.close() blocking_sender_2.close() conn_1.close() conn_2.close()
def on_accepted(self, event): if event.sender == self.service_sender: self.outstanding -= 1 self.send() def on_rejected(self, event): if event.sender == self.service_sender: self.outstanding -= 1 self.send() def on_released(self, event): if event.sender == self.service_sender: self.outstanding -= 1 self.send() try: ## ## Try to get the message bus hostname from the openshift environment ## Fall back to 127.0.0.1 (loopback) ## ## host = os.getenv("MESSAGING_SERVICE_HOST", "amqps://amqps-demo2-amq.apps.192.168.99.102.nip.io:443") host = os.getenv("MESSAGING_SERVICE_HOST", "amqps://amqps-demo2-amq.35.230.115.194.nip.io:443") container = Container(Client(host)) container.container_id = os.getenv("HOSTNAME", "client") container.run() except KeyboardInterrupt: pass
self.confirmed = 0 self.total = messages self.target = target def on_start(self, event): self.container = event.container conn = self.container.connect(self.url, allowed_mechs='PLAIN') self.sender = self.container.create_sender(conn, self.target) def on_sendable(self, event): while event.sender.credit and self.sent < self.total: msg = Message(id=(self.sent + 1), body={'sequence': (self.sent + 1)}) event.sender.send(msg) self.sent += 1 def on_accepted(self, event): self.confirmed += 1 if self.confirmed == self.total: print("all messages confirmed") event.connection.close() def on_disconnected(self, event): self.sent = self.confirmed try: Container(Send(ADDRESS, TOPIC_NAME, 100)).run() except KeyboardInterrupt: pass
self.target = target self.message_sent = False def on_start(self, event): print("on_start()") connection = event.container.connect(self.url) event.container.create_sender(connection, self.target) def on_sendable(self, event): print("on_sendable()") if not self.message_sent: message = Message(id=1, body="Hello world1") event.sender.send(message) self.message_sent = True print("Message has been sent") else: print("Already sent... do nothing") def on_accepted(self, event): print("on_accepted()") if self.message_sent: event.connection.close() def on_disconnected(self, event): print("on_disconnected()") publisher = Publisher(ADDRESS, TARGET) container = Container(publisher) container.run()
self.url = url self.address = address self.senders = {} def on_start(self, event): print "Listening on", self.url self.container = event.container self.conn = event.container.connect(self.url) self.receiver = event.container.create_receiver(self.conn, self.address) self.relay = None def on_connection_opened(self, event): if event.connection.remote_offered_capabilities and 'ANONYMOUS-RELAY' in event.connection.remote_offered_capabilities: self.relay = self.container.create_sender(self.conn, None) def on_message(self, event): print "Received", event.message sender = self.relay or self.senders.get(event.message.reply_to) if not sender: sender = self.container.create_sender(self.conn, event.message.reply_to) self.senders[event.message.reply_to] = sender sender.send(Message(address=event.message.reply_to, body=event.message.body.upper(), correlation_id=event.message.correlation_id)) try: Container(Server("0.0.0.0:5672", "examples")).run() except KeyboardInterrupt: pass
self._messages = messages self._message_index = 0 self._sent_count = 0 self._confirmed_count = 0 def on_start(self, event): event.container.create_sender(self.url) def on_sendable(self, event): while event.sender.credit and self._sent_count < len(self._messages): message = self._messages[self._message_index] print(message) event.sender.send(message) self._message_index += 1 self._sent_count += 1 def on_accepted(self, event): self._confirmed_count += 1 if self._confirmed_count == len(self._messages): event.connection.close() def on_transport_error(self, event): raise Exception(event.transport.condition) if __name__ == "__main__": try: Container(Sender(address.url, content.messages)).run() except KeyboardInterrupt: pass
self.rate = perftest.PerfRate() def on_start(self, event): self.container = event.container conn = event.container.connect(self.url, allowed_mechs='PLAIN') event.container.create_receiver(conn, self.path, options=Copy(), name=SUBSCRIPTION_NAME) self.container.schedule(1, self) def on_message(self, event): # msg = event.message # print(msg.body) self.rate.increment() if random.random() < 0.5: self.release(event.delivery, delivered=False) else: self.accept(event.delivery) def on_timer_task(self, event): print("consumer received {}".format(self.rate.print_rate())) self.container.schedule(1, self) try: receiver = Recv(CONN_STR, TOPIC_NAME) consumer = Recurring(0.001) container = Container(receiver, consumer) container.run() except KeyboardInterrupt: container.stop() print()
from proton.handlers import MessagingHandler from proton.reactor import Container ADDRESS = "localhost:5672" SOURCE = "queue://test" class Subscriber(MessagingHandler): def __init__(self, url, source): super(Subscriber, self).__init__() self.url = url self.source = source def on_start(self, event): print("on_start()") connection = event.container.connect(self.url) event.container.create_receiver(connection, self.source) def on_message(self, event): message = event.message print("Received message '{m}'".format(m=message.body)) event.receiver.close() event.connection.close() subscriber = Subscriber(ADDRESS, SOURCE) container = Container(subscriber) container.run()
def run(self): container = Container(self) container.container_id = "LRC" container.run()
self.senders = {} def on_start(self, event): print "Listening on:", self.url self.container = event.container self.acceptor = event.container.listen(self.url) def on_message(self, event): m = event.message topic = m.subject body = m.body sequence = str(m.properties['x-opt-sequence-number']) if topic == "hashablock": print '- HASH BLOCK (' + sequence + ') -' print binascii.hexlify(body) elif topic == "hashtx": print '- HASH TX (' + sequence + ') -' print binascii.hexlify(body) elif topic == "rawblock": print '- RAW BLOCK HEADER (' + sequence + ') -' print binascii.hexlify(body[:80]) elif topic == "rawtx": print '- RAW TX (' + sequence + ') -' print binascii.hexlify(body) try: Container(Server("127.0.0.1:%i" % port)).run() except KeyboardInterrupt: pass
def __init__(self, host, address): super(Server, self).__init__() self.container = Container(self) self.conn = self.container.connect(host) self.receiver = self.container.create_receiver(self.conn, address) self.sender = self.container.create_sender(self.conn, None)
def run(self): container = Container(self) container.container_id = 'LRC_R' container.run()
def on_link_opening(self, event): if event.link.is_sender: if event.link.remote_source and event.link.remote_source.dynamic: event.link.source.address = str(generate_uuid()) self.senders[event.link.source.address] = event.link elif event.link.remote_target and event.link.remote_target.address: event.link.target.address = event.link.remote_target.address self.senders[event.link.remote_target.address] = event.link elif event.link.remote_source: event.link.source.address = event.link.remote_source.address elif event.link.remote_target: event.link.target.address = event.link.remote_target.address def on_message(self, event): print "Received", event.message sender = self.senders.get(event.message.reply_to) if not sender: print "No link for reply" return sender.send( Message(address=event.message.reply_to, body=event.message.body.upper(), correlation_id=event.message.correlation_id)) try: Container(Server("0.0.0.0:8888")).run() except KeyboardInterrupt: pass
self.remove_stale_consumers(event.connection) def on_disconnected(self, event): self.remove_stale_consumers(event.connection) def remove_stale_consumers(self, connection): l = connection.link_head(Endpoint.REMOTE_ACTIVE) while l: if l.is_sender: self._unsubscribe(l) l = l.next(Endpoint.REMOTE_ACTIVE) def on_sendable(self, event): self._queue(event.link.source.address).dispatch(event.link) def on_message(self, event): self._queue(event.link.target.address).publish(event.message) parser = optparse.OptionParser(usage="usage: %prog [options]") parser.add_option("-a", "--address", default="localhost:5672", help="address router listens on (default %default)") opts, args = parser.parse_args() try: Container(Broker(opts.address)).run() except KeyboardInterrupt: pass
# specific language governing permissions and limitations # under the License. # from proton import Message from proton.handlers import MessagingHandler from proton.reactor import Container class HelloWorld(MessagingHandler): def __init__(self, server, address): super(HelloWorld, self).__init__() self.server = server self.address = address def on_start(self, event): conn = event.container.connect(self.server) event.container.create_receiver(conn, self.address) event.container.create_sender(conn, self.address) def on_sendable(self, event): event.sender.send(Message(body="Hello World!")) event.sender.close() def on_message(self, event): print(event.message.body) event.connection.close() Container(HelloWorld("localhost:5672", "examples")).run()
# Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # from proton.reactor import Container, Selector from proton.handlers import MessagingHandler class Recv(MessagingHandler): def __init__(self): super(Recv, self).__init__() def on_start(self, event): conn = event.container.connect("localhost:5672") event.container.create_receiver(conn, "examples", options=Selector(u"colour = 'green'")) def on_message(self, event): print event.message.body try: Container(Recv()).run() except KeyboardInterrupt: pass
def run(self): container = Container(self) container.container_id = 'container.1' container.run()
self.container = event.container conn = self.container.connect(self.url, allowed_mechs='PLAIN') self.sender = self.container.create_sender(conn, self.target) self.container.schedule(1, self) def on_sendable(self, event): self.send() def send(self): while self.sender.credit and not self.queue.empty(): msg = Message(body=self.queue.get(False)) self.sender.send(msg) self.rate.increment() def on_accepted(self, event): pass def on_timer_task(self, event): print("producer sent {}".format(self.rate.print_rate())) self.send() self.container.schedule(1, self) try: sender = Sender(CONN_STR, TOPIC_NAME) producer = Producer(0.001, sender.queue) Container(sender, producer).run() except KeyboardInterrupt: pass
def run(self): container = Container(self) container.container_id = self.cid container.run()
class Receiver(MessagingHandler): def __init__(self, url, messages_to_receive=10): super(Receiver, self).__init__() self.url = url self._messages_to_receive = messages_to_receive self._messages_actually_received = 0 self._stopping = False def on_start(self, event): event.container.create_receiver(self.url) def on_message(self, event): if self._stopping: return print(event.message) self._messages_actually_received += 1 if self._messages_actually_received == self._messages_to_receive: event.connection.close() self._stopping = True def on_transport_error(self, event): raise Exception(event.transport.condition) if __name__ == "__main__": try: Container(Receiver(address.url)).run() except KeyboardInterrupt: pass
def run(self): container = Container(self) container.run()
self.confirmed += 1 if self.confirmed == self.total: print("all messages confirmed") event.connection.close() def on_disconnected(self, event): self.sent = self.confirmed parser = optparse.OptionParser( usage="usage: %prog [options]", description="Send messages to the supplied address.") parser.add_option("-a", "--address", default="topic://localhost:5672/examples", help="address to which messages are sent (default %default)") parser.add_option("-m", "--messages", type="int", default=100, help="number of messages to send (default %default)") opts, args = parser.parse_args() try: Container(Send(opts.address, opts.messages)).run() except KeyboardInterrupt: pass
# self.isSwitchedOff = True # else: # print('unknown value') threading.Timer(1, self.start_metrics_logger).start() parser = optparse.OptionParser(usage="usage: %prog [options]") parser.add_option( "-a", "--address", default="localhost:5672/examples", help="address from which messages are received (default %default)") parser.add_option( "-m", "--messages", type="int", default=100, help= "number of messages to receive; 0 receives indefinitely (default %default)" ) opts, args = parser.parse_args() recv = None try: print('start container') recv = Recv(opts.address, opts.messages) Container(recv).run() except KeyboardInterrupt: recv.display_stats() pass
# Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # from proton.reactor import Container, Handler class Recurring(Handler): def __init__(self, period): self.period = period def on_reactor_init(self, event): self.container = event.reactor self.container.schedule(self.period, self) def on_timer_task(self, event): print("Tick...") self.container.schedule(self.period, self) try: container = Container(Recurring(1.0)) container.run() except KeyboardInterrupt: container.stop() print()
# from __future__ import print_function, unicode_literals from proton import Message from proton.handlers import MessagingHandler from proton.reactor import Container import env class HelloWorld(MessagingHandler): def __init__(self, address): super(HelloWorld, self).__init__() self.address = address def on_start(self, event): conn = event.container.connect(env.server_addr) event.container.create_receiver(conn, self.address) event.container.create_sender(conn, self.address) def on_sendable(self, event): event.sender.send(Message(body="Hello World!")) event.sender.close() def on_message(self, event): print(event.message.body) event.connection.close() Container(HelloWorld("examples")).run()
def run(self): Container(self).run()
def __init__(self, *handlers, **kwargs): self.tornado_loop = kwargs.get('loop', tornado.ioloop.IOLoop.instance()) kwargs['global_handler'] = TornadoLoopHandler( self.tornado_loop, kwargs.get('handler_base', None)) self.container = BaseContainer(*handlers, **kwargs)
def __init__(self, *handlers, **kwargs): self.tornado_loop = kwargs.get('loop', tornado.ioloop.IOLoop.instance()) kwargs['global_handler'] = TornadoLoopHandler(self.tornado_loop, kwargs.get('handler_base', None)) self.container = BaseContainer(*handlers, **kwargs)
def main(): initLogging() LOG.info("Starting Amqp Client") oAmqpClient = AmqpClient() Container(Recv(oAmqpClient), EndPointHandler()).run()