コード例 #1
0
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))

        if message.body == "exit":
            print("Last message for me...good bye")
            event.receiver.close()
            event.connection.close()
        time.sleep(1)


subscriber = Subscriber(ADDRESS, SOURCE)
container = Container(subscriber)
container.run()
コード例 #2
0
ファイル: client.py プロジェクト: ted-ross/demo2-amq
        except:
            pass

    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", "127.0.0.1")
    container = Container(Client(host))
    container.container_id = os.getenv("HOSTNAME", "client")
    container.run()
except KeyboardInterrupt:
    pass
コード例 #3
0
 def run(self):
     Container(self).run()
コード例 #4
0
 def run(self):
     container = Container(self)
     container.container_id = 'LRC'
     container.run()
コード例 #5
0
    def on_start(self, event):
        """Event callback for when the client starts"""
        connection = event.container.connect(url=self.broker_url,
                                             sasl_enabled=False)
        event.container.create_receiver(connection, source=self.queue_name)

    def on_message(self, event):
        """Event callback when a message is received by the client"""
        if event.message.id and event.message.id < self.received:
            return  # ignore duplicate message
        if self.received < self.expected:
            pass  # do something here
        if self.received >= self.expected:
            event.receiver.close()
            event.connection.close()


# --- main ---
# Args: 1: Broker address (ip-addr:port)
#       2: Queue name
#       ...
try:
    RECEIVER = AmqpDtxTestReceiver(sys.argv[1], sys.argv[2])
    Container(RECEIVER).run()
except KeyboardInterrupt:
    pass
except Exception as exc:
    print os.path.basename(sys.argv[0]), 'EXCEPTION', exc
    print format_exc()
コード例 #6
0
                          body=self.requests[0])
            self.sender.send(req)
            print("Message '%s' sent" % self.requests.pop(0))

    def on_sendable(self, event):
        while event.sender.credit and self.requests:
            self.next_request()

    def on_message(self, event):
        self.received += 1
        print("Message '%s' received" % event.message.body)
        if self.received == self.total:
            event.connection.close()


REQUESTS = [
    "Twas brillig, and the slithy toves", "Did gire and gymble in the wabe.",
    "All mimsy were the borogroves,", "And the mome raths outgrabe."
]

parser = optparse.OptionParser(
    usage="usage: %prog [options]",
    description="Send requests to the supplied address and print responses.")
parser.add_option("-a",
                  "--address",
                  default="localhost:5672/examples",
                  help="address to which messages are sent (default %default)")
opts, args = parser.parse_args()

Container(Client(opts.address, args or REQUESTS)).run()
コード例 #7
0
    # Called once the sender has been created
    def on_link_opened(self, event):
        if event.link.is_sender:
            self.receiver = event.container.create_receiver(
                self.conn, self.receive_destination)

    # the on_transport_error event catches socket and authentication failures
    def on_transport_error(self, event):
        print("Transport error:", event.transport.condition)

    def on_disconnected(self, event):
        print("Disconnected")


# parse arguments and get options
opts = get_options()
"""
The amqp address can be a topic or a queue.
Do not use a prefix or use 'queue://' in the amqp address for
the amqp receiver source address to receiver messages from a queue.
Use the prefix 'topic://' for a topic address
"""

try:
    Container(
        SendOnReceive(opts.url, opts.username, opts.password,
                      opts.send_destination, opts.receive_destination)).run()
except KeyboardInterrupt:
    pass
コード例 #8
0
ファイル: perf_send.py プロジェクト: pgillet/poc-messaging
            if env.throttle > 0:
                time.sleep(env.throttle)

    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

parser = optparse.OptionParser(usage="usage: %prog [options]",
                               description="Send messages to the supplied address.")
parser.add_option("-u", "--urls", default=env.server_addr,
                  help="list of URL strings of process to try to connect to. Ex: [host1:5672, host2:5672, host2:5672]")
parser.add_option("-a", "--address", default=env.address,
                  help="address to which messages are sent (default %default)")
parser.add_option("-m", "--messages", type="int", default=env.num_messages,
                  help="number of messages to send (default %default)")
opts, args = parser.parse_args()

# From command line string option
if isinstance(opts.urls, str):
    opts.urls = opts.urls.strip('[]').split(', ')

try:
    Container(Send(opts.urls, opts.address, opts.messages)).run()
except KeyboardInterrupt: pass
コード例 #9
0
    def on_start(self, event):
        self.container = event.container
        self.conn = self.container.connect(self.url)
        self.receiver = self.container.create_receiver(self.conn, self.address)
        self.acct_sender = self.container.create_sender(
            self.conn, self.accounting)
        self.anon_sender = self.container.create_sender(self.conn, None)

    def on_message(self, event):
        reply_to = event.message.reply_to
        cid = event.message.correlation_id
        msg = Message(address=reply_to,
                      correlation_id=cid,
                      body="SubService.A (%s)" % os.uname()[1])
        self.anon_sender.send(msg)

        if self.acct_sender.credit > 0:
            acct_msg = Message(body=reply_to)
            self.acct_sender.send(acct_msg)


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", "127.0.0.1")
    Container(Service(host)).run()
except KeyboardInterrupt:
    pass
コード例 #10
0
    def _reset_stats(self):
        self._received = 0
        self._e2e_times = list()


# Main flow for sender app
if __name__ == "__main__":
    parsed_opts, args = common.parse_opts(False)

    # same message body and properties will be used by all sender instances
    expected_body_size = parsed_opts.message_size
    expected_properties_size = parsed_opts.properties_size

    # initializing logging
    common.initialize_logging(parsed_opts.log_level)

    # list of spawned sender processes
    processes = list()

    # spawning receiver processes
    for i in range(parsed_opts.processes):
        proc = multiprocessing.Process(target=Container(Receiver(parsed_opts)).run)
        proc.start()
        processes.append(proc)

    # waiting on all processes to finish
    for proc in processes:
        proc.join()

    print("Exiting")
コード例 #11
0
        self.transaction.commit()

    def on_abort(self, event):
        self.transaction.abort()

    def on_fetch(self, event):
        self.receiver.flow(1)

    def on_quit(self, event):
        c = self.receiver.connection
        self.receiver.close()
        c.close()


try:
    reactor = Container(TxRecv())
    events = reactor.get_event_trigger()
    thread = threading.Thread(target=reactor.run)
    thread.daemon = True
    thread.start()

    print "Enter 'fetch', 'commit' or 'abort'"
    while True:
        line = sys.stdin.readline()
        if line:
            events.trigger(ApplicationEvent(line.strip()))
        else:
            break
except KeyboardInterrupt:
    pass
コード例 #12
0
            self.container.declare_transaction(self.conn, handler=self)

    def on_disconnected(self, event):
        self.current_batch = 0


parser = optparse.OptionParser(
    usage="usage: %prog [options]",
    description="Send messages transactionally to the supplied address.")
parser.add_option("-a",
                  "--address",
                  default="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)")
parser.add_option(
    "-b",
    "--batch-size",
    type="int",
    default=10,
    help="number of messages in each transaction (default %default)")
opts, args = parser.parse_args()

try:
    Container(TxSend(opts.address, opts.messages, opts.batch_size)).run()
except KeyboardInterrupt:
    pass
コード例 #13
0
            print(event.message.body)
            self.received += 1
            if self.received == self.expected:
                print('received all', self.expected, 'messages')
                event.receiver.close()
                event.connection.close()

    # the on_transport_error event catches socket and authentication failures
    def on_transport_error(self, event):
        print("Transport error:", event.transport.condition)
        MessagingHandler.on_transport_error(self, event)

    def on_disconnected(self, event):
        print("Disconnected")


# parse arguments and get options
opts = get_options()
"""
The amqp address can be a topic or a queue.
Do not use a prefix or use 'queue://' in the amqp address for
the amqp receiver source address to receiver messages from a queue.
"""

try:
    Container(
        Recv(opts.url, opts.address, opts.messages, opts.username,
             opts.password)).run()
except KeyboardInterrupt:
    pass
コード例 #14
0
from proton import Message
from proton.handlers import MessagingHandler
from proton.reactor import Container

class Handler (MessagingHandler):
    def __init__ (self, url, target):
        super (Handler, self).__init__ ()
        self.url = url
        self.target = target

    def on_start (self, event):
        conn = event.container.connect (self.url)
        event.container.create_receiver (conn, self.target)

    def on_message (self, event):
        print ("Got message: {0}".format (event.message.body))
        if event.message.body == 'quit':
            print ("Stopping listener")
            event.receiver.close ()
            event.connection.close ()

try:
    Container (Handler ("localhost:5672", "topic://exam.ple.top.ic")).run ()
except KeyboardInterrupt:
    pass
コード例 #15
0
        print(event._attrs)
        if self.received == self.total:
            event.connection.close()
            event.container.stop()

    def on_disconnected(self, event):
        print(18)
        self.sent = self.confirmed


parser = optparse.OptionParser(
    usage="usage: %prog [options]",
    description="Send messages to the supplied address.")
parser.add_option("-a",
                  "--address",
                  default="localhost:5672/examples",
                  help="address to which messages are sent (default %default)")
parser.add_option("-m",
                  "--messages",
                  type="int",
                  default=1,
                  help="number of messages to send (default %default)")
opts, args = parser.parse_args()

try:
    container = Container(MyHandler(opts.address, opts.messages))
    # container.container_id = 'myqueue'
    container.run()
except KeyboardInterrupt:
    pass
コード例 #16
0
from proton import Url


class Recv(MessagingHandler):
    def __init__(self, url):
        super(Recv, self).__init__()
        self.url = Url(url)
        self.received = 0

    def on_start(self, event):
        conn = event.container.connect(self.url)
        event.container.create_receiver(conn, self.url.path)

    def on_message(self, event):
        print("Message '%s' received" % event.message.body)
        self.received += 1


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)")
opts, args = parser.parse_args()

try:
    Container(Recv(opts.address)).run()
except KeyboardInterrupt:
    pass
コード例 #17
0
                logger.error("%s: %s: %s" %
                             (event.transport.condition.name,
                              event.transport.condition.description,
                              event.transport.condition.info))
            else:
                logger.error("%s: %s" %
                             (event.transport.condition.name,
                              event.transport.condition.description))
        else:
            logging.error("Unspecified transport error")

    # 当收到消息时被调用。
    def on_message(self, event):
        message = event.message
        content = message.body.decode('utf-8')
        topic = message.properties.get("topic")
        message_id = message.properties.get("messageId")
        print()
        logger.info("receive message: message_id=%s, topic=%s, content=%s" %
                    (message_id, topic, content))
        print()
        self.update.receive_new_message(content)
        event.receiver.flow(1)


try:
    Container(AmqpClient()).run()
except Exception as e:
    logging.error(e)
    Container(AmqpClient()).run()
コード例 #18
0
            self.conn, self.address)
        self.senders = {}
        self.relay = None

    def on_message(self, event):
        sender = self.relay
        if not sender:
            sender = 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

        response = Message(address=event.message.reply_to,
                           body=event.message.body.upper(),
                           correlation_id=event.message.correlation_id)
        self.container.declare_transaction(self.conn,
                                           handler=TxRequest(
                                               response, sender,
                                               event.delivery))

    def on_connection_open(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)


try:
    Container(TxServer("localhost:5672", "examples")).run()
except KeyboardInterrupt:
    pass
コード例 #19
0
 def run(self):
     container = Container(self)
     container.run()
コード例 #20
0
    def on_connection_closing(self, event):
        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):
        address = event.link.target.address
        if address is None:
            address = event.message.address
        self._queue(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
コード例 #21
0
        if self.conf.amqpd.archive_policy_name:
            return self.conf.amqpd.archive_policy_name
        # NOTE(sileht): We didn't catch NoArchivePolicyRuleMatch to log it
        ap = self.indexer.get_archive_policy_for_metric(metric_name)
        return ap.name


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)"
)

conf = service.prepare_service()
#if conf.statsd.resource_id is None:
#raise cfg.RequiredOptError("resource_id", cfg.OptGroup("amqpd"))

try:
    Container(Amqp(opts.address, opts.messages, conf)).run()
except KeyboardInterrupt:
    pass
コード例 #22
0
 def run(self):
     container = Container(self)
     container.container_id = "LRC"
     container.run()
コード例 #23
0
 def run(self):
     container = Container(self)
     container.container_id = self.container_id
     container.run()
コード例 #24
0
            # 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
コード例 #25
0
    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.server = self.container.create_sender(self.conn, self.address)

    def on_message(self, event):
        print("Received", event.message)
        self.server.send(
            Message(address=event.message.reply_to,
                    body=event.message.body.upper(),
                    correlation_id=event.message.correlation_id))


parser = optparse.OptionParser(usage="usage: %prog [options]")
parser.add_option(
    "-a",
    "--address",
    default=env.server_addr,
    help="address from which messages are received (default %default)")
opts, args = parser.parse_args()

url = Url(opts.address)

try:
    Container(Server(url, url.path)).run()
except KeyboardInterrupt:
    pass
コード例 #26
0
                'JmsMessagesTestSender._create_jms_streammessage: Unknown or unsupported subtype "%s"'
                % test_value_type)
        return Message(id=(self.sent + 1),
                       body=body_list,
                       inferred=True,
                       annotations=create_annotation('JMS_STREAMMESSAGE_TYPE'))

    def _create_jms_textmessage(self, test_value_text):
        """Create a JMS text message"""
        return Message(id=(self.sent + 1),
                       body=unicode(test_value_text),
                       annotations=create_annotation('JMS_TEXTMESSAGE_TYPE'))


# --- main ---
# Args: 1: Broker address (ip-addr:port)
#       2: Queue name
#       3: JMS message type
#       4: JSON Test parameters containing 3 maps: [testValueMap, testHeadersMap, testPropertiesMap]
#print '#### sys.argv=%s' % sys.argv
#print '>>> test_values=%s' % loads(sys.argv[4])
try:
    SENDER = JmsMessagesTestSender(sys.argv[1], sys.argv[2], sys.argv[3],
                                   loads(sys.argv[4]))
    Container(SENDER).run()
except KeyboardInterrupt:
    pass
except Exception as exc:
    print 'jms-sender-shim EXCEPTION:', exc
    print format_exc()
コード例 #27
0
 def run(self):
     Container(self).run()
     if self.error is not None:
         self.logger.dump()
コード例 #28
0
        if self.listener:
            self.listener.close()

    def on_connection_opening(self, event):
        # Sends an empty failover list.
        # This will test the case where we deliberately send an empty failover list so that the router
        # receiving this open frame will clean out its failover list.
        event.connection.properties = {symbol('failover-server-list'): []}


parser = optparse.OptionParser(usage="usage: %prog [options]",
                               description="Testing Router failover support")

parser.add_option("-a",
                  "--address",
                  default="localhost:55671",
                  help="address to listen on (default %default)")

opts, args = parser.parse_args()

handler = FailoverServer(opts.address)


def sigterm_handler(_signo, _stack_frame):
    sys.exit(0)


signal.signal(signal.SIGTERM, sigterm_handler)

Container(handler).run()
コード例 #29
0
ファイル: amqp_sub.py プロジェクト: zxteamorg/bitcoinz
        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
コード例 #30
0
ファイル: amqp_test.py プロジェクト: dennis-zheng/python
def thread_process2(index):
    logDS.info("begin %d"%index)
    Container(HelloWorld("examples")).run()
    logDS.info("exit %d"%index)