summaryrefslogtreecommitdiff
path: root/qpid/cpp/src/tests/latencytest.cpp
blob: e1c47eab05ae96c4ed08ea0f37863c01c6b49be9 (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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/*
 *
 * 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.
 *
 */


#include <algorithm>
#include <limits>
#include <iostream>
#include <memory>
#include <sstream>
#include <vector>

#include "TestOptions.h"
#include "qpid/sys/Thread.h"
#include "qpid/client/Connection.h"
#include "qpid/client/Message.h"
#include "qpid/client/AsyncSession.h"
#include "qpid/client/SubscriptionManager.h"
#include "qpid/sys/Time.h"

using namespace qpid;
using namespace qpid::client;
using namespace qpid::sys;
using std::string;

typedef std::vector<std::string> StringSet;

struct Args : public qpid::TestOptions {
    uint size;
    uint count;
    uint rate;
    bool sync;
    uint reportFrequency;
    uint timeLimit;
    uint concurrentConnections;
    uint prefetch;
    uint ack;
    bool cumulative;
    bool csv;
    bool durable;
    string base;
    bool singleConnect;

    Args() : size(256), count(1000), rate(0), reportFrequency(1000),
	     timeLimit(0), concurrentConnections(1),
             prefetch(100), ack(0),
             durable(false), base("latency-test"), singleConnect(false)

    {
        addOptions()            

            ("size", optValue(size, "N"), "message size")
            ("concurrentTests", optValue(concurrentConnections, "N"), "number of concurrent test setups, will create another publisher,\
 subcriber, queue, and connections")
            ("single-connection", optValue(singleConnect, "yes|no"), "Use one connection for multiple sessions.")
            ("count", optValue(count, "N"), "number of messages to send")
            ("rate", optValue(rate, "N"), "target message rate (causes count to be ignored)")
            ("sync", optValue(sync), "send messages synchronously")
            ("report-frequency", optValue(reportFrequency, "N"), 
             "number of milliseconds to wait between reports (ignored unless rate specified)")
            ("time-limit", optValue(timeLimit, "N"), 
             "test duration, in seconds")
            ("prefetch", optValue(prefetch, "N"), "prefetch count (0 implies no flow control, and no acking)")
            ("ack", optValue(ack, "N"), "Ack frequency in messages (defaults to half the prefetch value)")
            ("durable", optValue(durable, "yes|no"), "use durable messages")
            ("csv", optValue(csv), "print stats in csv format (rate,min,max,avg)")
            ("cumulative", optValue(cumulative), "cumulative stats in csv format")
            ("queue-base-name", optValue(base, "<name>"), "base name for queues");
    }
};

const std::string chars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");

Args opts;
double c_min, c_avg, c_max;
Connection globalConnection;

uint64_t current_time()
{
    Duration t(now());
    return t;
}

struct Stats 
{
    Mutex lock;
    uint count;
    double minLatency;
    double maxLatency;
    double totalLatency;

    Stats();
    void update(double l);
    void print();
    void reset();
};

class Client : public Runnable
{
protected:
    Connection* connection;
    Connection localConnection;
    AsyncSession session;
    Thread thread;
    string queue;

public:
    Client(const string& q);
    virtual ~Client();

    void start();
    void join();
    void run();
    virtual void test() = 0;
};

class Receiver : public Client, public MessageListener
{    
    SubscriptionManager mgr;
    uint count;
    Stats& stats;

public:
    Receiver(const string& queue, Stats& stats);
    void test();
    void received(Message& msg);
    Stats getStats();
    uint getCount() { return count; }
    void stop() {  mgr.stop(); mgr.cancel(queue); }
};


class Sender : public Client
{
    string generateData(uint size);
    void sendByRate();
    void sendByCount();
    Receiver& receiver;
    const string data;

public:
    Sender(const string& queue, Receiver& receiver);
    void test();
};


class Test
{
    const string queue;
    Stats stats;
    Receiver receiver;
    Sender sender;
    AbsTime begin;
    
public:
    Test(const string& q) : queue(q), receiver(queue, stats), sender(queue, receiver), begin(now()) {}
    void start();
    void join();
    void report();
};


Client::Client(const string& q) : queue(q)
{
    if (opts.singleConnect){
        connection = &globalConnection;
        if (!globalConnection.isOpen()) opts.open(globalConnection);
    }else{
        connection = &localConnection;
        opts.open(localConnection);
    }
    session = connection->newSession();       
}

void Client::start()
{
    thread = Thread(this);
}

void Client::join()
{
    thread.join();
}

void Client::run()
{
    try{
        test();
    } catch(const std::exception& e) {
        std::cout << "Error in receiver: " << e.what() << std::endl;
    }
}

Client::~Client()
{
    try{
        session.close();
        connection->close();
    } catch(const std::exception& e) {
        std::cout << "Error in receiver: " << e.what() << std::endl;
    }
}

Receiver::Receiver(const string& q, Stats& s) : Client(q), mgr(session), count(0), stats(s)
{
    session.queueDeclare(arg::queue=queue, arg::durable=opts.durable, arg::autoDelete=true);
    uint msgCount = session.queueQuery(arg::queue=queue).get().getMessageCount();
    if (msgCount) {
        std::cout << "Warning: found " << msgCount << " msgs on " << queue << ". Purging..." << std::endl;
        session.queuePurge(arg::queue=queue);
        session.sync();
    }
    SubscriptionSettings settings;
    if (opts.prefetch) {
        settings.autoAck = (opts.ack ? opts.ack : (opts.prefetch / 2));
        settings.flowControl = FlowControl::messageWindow(opts.prefetch);
    } else {
        settings.acceptMode = ACCEPT_MODE_NONE;
        settings.flowControl = FlowControl::unlimited();
    }
    mgr.subscribe(*this, queue, settings);    
}

void Receiver::test()
{
    mgr.run();
    mgr.cancel(queue);
}

void Receiver::received(Message& msg)
{
    ++count;
    uint64_t receivedAt = current_time();
    uint64_t sentAt = msg.getDeliveryProperties().getTimestamp();

    stats.update(((double) (receivedAt - sentAt)) / TIME_MSEC);

    if (!opts.rate && count >= opts.count) {
        mgr.stop();
    }
}

void Stats::update(double latency)
{
    Mutex::ScopedLock l(lock);
    count++;
    minLatency = std::min(minLatency, latency);
    maxLatency = std::max(maxLatency, latency);
    totalLatency += latency;
}

Stats::Stats() : count(0), minLatency(std::numeric_limits<double>::max()), maxLatency(0), totalLatency(0) {}

void Stats::print()
{
    static bool already_have_stats = false;
    uint value;

    if (opts.rate)
        value = opts.rate;
    else
        value = opts.count;
    Mutex::ScopedLock l(lock);
    double aux_avg = (totalLatency / count);
    if (!opts.cumulative) {
        if (!opts.csv) {
            if (count) {
                std::cout << "Latency(ms): min=" << minLatency << ", max=" <<
	                 maxLatency << ", avg=" << aux_avg; 
            } else {
                std::cout << "Stalled: no samples for interval";
            }
        } else {
            if (count) {
          	    std::cout << value << "," << minLatency << "," << maxLatency <<
    				     "," << aux_avg;
            } else {
          	    std::cout << value << "," << minLatency << "," << maxLatency <<
    				     ", Stalled";
            }
        }
    } else {
       if (count) {
            if (already_have_stats) {
                c_avg = (c_min + aux_avg) / 2;
                if (c_min > minLatency) c_min = minLatency;
                if (c_max < maxLatency) c_max = maxLatency;
            } else {
                c_avg = aux_avg;
                c_min = minLatency;
                c_max = maxLatency;
                already_have_stats = true;
            }
  	        std::cout << value << "," << c_min << "," << c_max <<
    				     "," << c_avg;
        } else {
            std::cout << "Stalled: no samples for interval";
        }
    }
}

void Stats::reset()
{
    Mutex::ScopedLock l(lock);
    count = 0;
    totalLatency = maxLatency = 0;
    minLatency = std::numeric_limits<double>::max();
}

Sender::Sender(const string& q, Receiver& receiver) : Client(q), receiver(receiver), data(generateData(opts.size)) {}

void Sender::test()
{
    if (opts.rate) sendByRate();
    else sendByCount();
}

void Sender::sendByCount()
{
    Message msg(data, queue);
    if (opts.durable) {
        msg.getDeliveryProperties().setDeliveryMode(framing::PERSISTENT);
    }

    for (uint i = 0; i < opts.count; i++) {
        uint64_t sentAt(current_time());
        msg.getDeliveryProperties().setTimestamp(sentAt);
        async(session).messageTransfer(arg::content=msg, arg::acceptMode=1);
        if (opts.sync) session.sync();
    }
    session.sync();
}

void Sender::sendByRate()
{
    Message msg(data, queue);
    if (opts.durable) {
        msg.getDeliveryProperties().setDeliveryMode(framing::PERSISTENT);
    }
    uint64_t interval = TIME_SEC/opts.rate;
    int64_t timeLimit = opts.timeLimit * TIME_SEC;
    uint64_t sent = 0, missedRate = 0;
    AbsTime start = now();
    while (true) {
        AbsTime sentAt=now();
        msg.getDeliveryProperties().setTimestamp(Duration(sentAt));
        async(session).messageTransfer(arg::content=msg, arg::acceptMode=1);
        if (opts.sync) session.sync();
        ++sent;
        AbsTime waitTill(start, sent*interval);
        Duration delay(sentAt, waitTill);
        if (delay < 0)
            ++missedRate;
        else 
            sys::usleep(delay / TIME_USEC);
        if (timeLimit != 0 && Duration(start, now()) > timeLimit) {
            session.sync();
            receiver.stop();
            break;
        }
    }
}

string Sender::generateData(uint size)
{
    if (size < chars.length()) {
        return chars.substr(0, size);
    }   
    std::string data;
    for (uint i = 0; i < (size / chars.length()); i++) {
        data += chars;
    }
    data += chars.substr(0, size % chars.length());
    return data;
}


void Test::start() 
{ 
    receiver.start(); 
    begin = AbsTime(now());
    sender.start(); 
}

void Test::join() 
{ 
    sender.join(); 
    receiver.join(); 
    AbsTime end = now();
    Duration time(begin, end);
    double msecs(time / TIME_MSEC);
    if (!opts.csv) {
        std::cout << "Sent " << receiver.getCount() << " msgs through " << queue 
                  << " in " << msecs << "ms (" << (receiver.getCount() * 1000 / msecs) << " msgs/s) ";
    }
    stats.print();
    std::cout << std::endl;
}

void Test::report() 
{ 
    stats.print();
    std::cout << std::endl;
    stats.reset();
}

int main(int argc, char** argv)
{
    try {
        opts.parse(argc, argv);
        if (opts.cumulative)
            opts.csv = true;

        Connection localConnection;
        AsyncSession session;

        boost::ptr_vector<Test> tests(opts.concurrentConnections);
        for (uint i = 0; i < opts.concurrentConnections; i++) {
            std::ostringstream out;
            out << opts.base << "-" << (i+1);
            tests.push_back(new Test(out.str()));
        }
        for (boost::ptr_vector<Test>::iterator i = tests.begin(); i != tests.end(); i++) {
            i->start();
        }
        if (opts.rate && !opts.timeLimit) {
            while (true) {
                qpid::sys::usleep(opts.reportFrequency * 1000);
                //print latency report:
                for (boost::ptr_vector<Test>::iterator i = tests.begin(); i != tests.end(); i++) {
                    i->report();
                }
            }
        } else {
            for (boost::ptr_vector<Test>::iterator i = tests.begin(); i != tests.end(); i++) {
                i->join();
            }
        }

        return 0;
    } catch(const std::exception& e) {
	std::cout << e.what() << std::endl;
    }
    return 1;
}