summaryrefslogtreecommitdiff
path: root/qpid/cpp/src/tests/qpid-cpp-benchmark
blob: 85efff9a369bb8279b989be4df3b21084ebf3ab7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
#

import optparse, time, qpid.messaging, re
from threading import Thread
from subprocess import Popen, PIPE, STDOUT

op = optparse.OptionParser(usage="usage: %prog [options]",
                           description="simple performance benchmarks")
op.add_option("-b", "--broker", default=[], action="append", type="str",
              help="url of broker(s) to connect to, round robin on multiple brokers")
op.add_option("-c", "--client-host", default=[], action="append", type="str",
              help="host(s) to run clients on via ssh, round robin on mulple hosts")
op.add_option("-q", "--queues", default=1, type="int", metavar="N",
              help="create N queues (default %default)")
op.add_option("-s", "--senders", default=1, type="int", metavar="N",
              help="start N senders per queue (default %default)")
op.add_option("-r", "--receivers", default=1, type="int", metavar="N",
              help="start N receivers per queue (default %default)")
op.add_option("-m", "--messages", default=100000, type="int", metavar="N",
              help="send N messages per sender (default %default)")
op.add_option("--queue-name", default="benchmark", metavar="NAME",
               help="base name for queues (default %default)")
op.add_option("--send-rate", default=0, metavar="R",
              help="send rate limited to R messages/second, 0 means no limit (default %default)")
op.add_option("--content-size", default=1024, type="int", metavar="BYTES",
              help="message size in bytes (default %default)")
op.add_option("--ack-frequency", default=0, metavar="N", type="int",
              help="receiver ack's every N messages, 0 means unconfirmed (default %default)")
op.add_option("--no-report-header", dest="report_header", default=True,
              action="store_false", help="don't print header on report")
op.add_option("--repeat", default=1, metavar="N", help="repeat N times", type="int")
op.add_option("--send-option", default=[], action="append", type="str",
              help="Additional option for sending addresses")
op.add_option("--receive-option", default=[], action="append", type="str",
              help="Additional option for receiving addresses")
op.add_option("--no-timestamp", dest="timestamp", default=True,
              action="store_false", help="don't add a timestamp, no latency results")

single_quote_re = re.compile("'")

def posix_quote(string):
    """ Quote a string for use as an argument in a posix shell"""
    return "'" + single_quote_re.sub("\\'", string) + "'";

def ssh_command(host, command):
    """Convert command into an ssh command on host with quoting"""
    return ["ssh", host] + [posix_quote(arg) for arg in command]

def start_receive(queue, opts, ready_queue, broker, host):
    address="%s;{%s}"%(queue,",".join(["create:always"]+opts.receive_option))
    command = ["qpid-receive",
               "-b", broker,
               "-a", address,
               "--forever",
               "--print-content=no",
               "--report-total",
               "--ack-frequency", str(opts.ack_frequency),
               "--ready-address", ready_queue,
               "--report-header=no"]
    if host: command = ssh_command(host, command)
    return Popen(command, stdout=PIPE, stderr=STDOUT)

def start_send(queue, opts, broker, host):
    address="%s;{%s}"%(queue,",".join(opts.send_option))
    command = ["qpid-send",
               "-b", broker,
               "-a", address,
               "--messages", str(opts.messages),
               "--send-eos", str(opts.receivers),
               "--content-size", str(opts.content_size),
               "--send-rate", str(opts.send_rate),
               "--report-total",
               "--report-header=no",
               "--timestamp=%s"%(opts.timestamp and "yes" or "no"),
               "--sequence=no"]
    if host: command = ssh_command(host, command)
    return Popen(command, stdout=PIPE, stderr=STDOUT)

def wait_for_output(p):
    out,err=p.communicate()
    if p.returncode != 0: raise Exception("ERROR:\n%s"%(out))
    return out

def delete_queues(queues, broker):
    c = qpid.messaging.Connection(broker)
    c.open()
    for q in queues:
        try: s = c.session().sender("%s;{delete:always}"%(q))
        except qpid.messaging.exceptions.NotFound: pass # Ignore "no such queue"
    c.close()

def print_output(senders, receivers, want_header):
    send_stats = sum([wait_for_output(p).split("\n")[:-1] for p in senders],[])
    recv_stats = sum([wait_for_output(p).split("\n")[:-1] for p in receivers],[])
    def empty_if_none(s):
        if s: return s
        else: return ""
    stats = map(lambda s,r: empty_if_none(s)+"\t\t"+empty_if_none(r),
                send_stats, recv_stats)
    if want_header: print "send-tp\t\trecv-tp\tl-min\tl-max\tl-avg"
    for s in stats: print s;

class ReadyReceiver:
    """A receiver for ready messages"""
    def __init__(self, queue, broker):
        delete_queues([queue], broker)
        self.connection = qpid.messaging.Connection(broker)
        self.connection.open()
        self.receiver = self.connection.session().receiver(
            "%s;{create:always,delete:always}"%(queue))
        self.timeout=2

    def wait(self, receivers):
        try:
            for i in xrange(len(receivers)): self.receiver.fetch(self.timeout)
            self.connection.close()
        except qpid.messaging.Empty:
            for r in receivers:
                if (r.poll()): raise "Receiver error: %s"%(wait_for_output(r))
            raise "Timed out waiting for receivers to be ready"

def flatten(l): return sum(map(lambda s: s.split(","), l),[])

class RoundRobin:
    def __init__(self,items):
        self.items = items
        self.index = 0

    def next(self):
        if not self.items: return None
        ret = self.items[self.index]
        self.index = (self.index+1)%len(self.items)
        return ret

def main():
    opts, args = op.parse_args()
    if not opts.broker: opts.broker = ["127.0.0.1"] # Deafult to local broker
    opts.broker = flatten(opts.broker)
    opts.client_host = flatten(opts.client_host)
    brokers = RoundRobin(opts.broker)
    client_hosts = RoundRobin(opts.client_host)
    send_out = ""
    receive_out = ""
    ready_queue="%s-ready"%(opts.queue_name)
    queues = ["%s-%s"%(opts.queue_name, i) for i in xrange(opts.queues)]
    for i in xrange(opts.repeat):

        delete_queues(queues, opts.broker[0])
        ready_receiver = ReadyReceiver(ready_queue, opts.broker[0])
        receivers = [start_receive(q, opts, ready_queue, brokers.next(), client_hosts.next())
                     for q in queues for j in xrange(opts.receivers)]
        ready_receiver.wait(receivers) # Wait for receivers to be ready.
        senders = [start_send(q, opts,brokers.next(), client_hosts.next())
                   for q in queues for j in xrange(opts.senders)]
        print_output(senders, receivers, opts.report_header and i == 0)
        delete_queues(queues, opts.broker[0])

if __name__ == "__main__": main()