File: testMonitorPerformance.cpp

package info (click to toggle)
epics-base 7.0.8.1%2Bdfsg1-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 22,532 kB
  • sloc: cpp: 130,870; ansic: 115,274; perl: 10,647; makefile: 3,477; yacc: 1,307; python: 594; lex: 236; sh: 108; csh: 36
file content (494 lines) | stat: -rw-r--r-- 15,129 bytes parent folder | download | duplicates (2)
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
#include <iostream>
#include <fstream>
#include <pv/clientFactory.h>
#include <pv/pvAccess.h>

#include <stdio.h>
#include <epicsStdlib.h>
#include <epicsGetopt.h>
#include <epicsThread.h>
#include <epicsTime.h>
#include <pv/logger.h>
#include <pv/lock.h>

#include <vector>
#include <string>

#include <stdlib.h>

#ifdef _WIN32
#include <winsock2.h>
#else
#include <sys/time.h>
#endif

#include <pv/event.h>

using namespace std;
namespace TR1 = std::tr1;
using namespace epics::pvData;
using namespace epics::pvAccess;

#define DEFAULT_TIMEOUT 600.0
#define DEFAULT_REQUEST "record[velocious=true]field(value)"
#define DEFAULT_ITERATIONS 10000
#define DEFAULT_CHANNELS 1
#define DEFAULT_ARRAY_SIZE 0
#define DEFAULT_RUNS 1

bool verbose = false;

int iterations = DEFAULT_ITERATIONS;
int channels = DEFAULT_CHANNELS;
int runs = DEFAULT_RUNS;
int arraySize = DEFAULT_ARRAY_SIZE;          // 0 means scalar
Mutex waitLoopPtrMutex;
TR1::shared_ptr<Event> waitLoopEvent;

double timeOut = DEFAULT_TIMEOUT;
string request(DEFAULT_REQUEST);

PVStructure::shared_pointer pvRequest;

class RequesterImpl : public Requester,
    public TR1::enable_shared_from_this<RequesterImpl>
{
public:

    virtual string getRequesterName()
    {
        return "RequesterImpl";
    };

    virtual void message(std::string const & message,MessageType messageType)
    {
        std::cout << "[" << getRequesterName() << "] message(" << message << ", " << getMessageTypeName(messageType) << ")" << std::endl;
    }
};

void usage (void)
{
    fprintf (stderr, "\nUsage: testMonitorPerformance [options] <PV name>...\n\n"
             "  -h: Help: Print this message\n"
             "options:\n"
             "  -r <pv request>:   pvRequest string, specifies what fields to return and options, default is '%s'\n"
             "  -i <iterations>:   number of iterations per each run, default is '%d'\n"
             "  -c <channels>:     number of channels, default is '%d'\n"
             "  -s <array size>:   number of array elements (0 means scalar), default is '%d'\n"
             "  -l <runs>:         number of runs (0 means execute runs continuously), default is '%d'\n"
             "  -f <filename>:     read configuration file that contains list of tests to be performed\n"
             "                         each test is defined by a \"<c> <s> <i> <l>\" line\n"
             "                         output is a space separated list of get operations per second for each run, one line per test\n"
             "  -v                 enable verbose output when configuration is read from the file\n"
             "  -w <sec>:          wait time, specifies timeout, default is %f second(s)\n\n"
             , DEFAULT_REQUEST, DEFAULT_ITERATIONS, DEFAULT_CHANNELS, DEFAULT_ARRAY_SIZE, DEFAULT_RUNS, DEFAULT_TIMEOUT);
}

// TODO thread-safety
ChannelProvider::shared_pointer provider;
vector<Monitor::shared_pointer> channelMonitorList;
int channelCount = 0;
int iterationCount = 0;
int runCount = 0;
double sum = 0;

void reset()
{
    channelMonitorList.clear();
    channelCount = 0;
    iterationCount = 0;
    runCount = 0;
    sum = 0;
}

epicsTimeStamp startTime;

void monitor_all()
{
    for (vector<Monitor::shared_pointer>::const_iterator i = channelMonitorList.begin();
            i != channelMonitorList.end();
            i++)
        (*i)->start();
}


// NOTE: it is assumed that all the callbacks are called from the same thread, i.e. same TCP connection
class ChannelMonitorRequesterImpl : public MonitorRequester
{
private:
    Event m_event;
    Event m_connectionEvent;
    string m_channelName;

public:

    ChannelMonitorRequesterImpl(std::string channelName) :
        m_channelName(channelName)
    {
    }

    virtual string getRequesterName()
    {
        return "ChannelMonitorRequesterImpl";
    }

    virtual void message(std::string const & message,MessageType messageType)
    {
        std::cout << "[" << getRequesterName() << "] message(" << message << ", " << getMessageTypeName(messageType) << ")" << std::endl;
    }

    virtual void monitorConnect(const epics::pvData::Status& status,
                                Monitor::shared_pointer const & /*monitor*/,
                                epics::pvData::Structure::const_shared_pointer const & /*structure*/)
    {
        if (status.isSuccess())
        {
            // show warning
            if (!status.isOK())
            {
                std::cout << "[" << m_channelName << "] channel monitor create: " << status << std::endl;
            }

            m_connectionEvent.signal();
        }
        else
        {
            std::cout << "[" << m_channelName << "] failed to create channel monitor: " << status << std::endl;
        }
    }

    virtual void monitorEvent(Monitor::shared_pointer const & monitor)
    {

        MonitorElement::shared_pointer element;
        while ((element = monitor->poll()))
        {
            channelCount++;
            if (channelCount == channels)
            {
                iterationCount++;
                channelCount = 0;
            }

            if (iterationCount == iterations)
            {
                epicsTimeStamp endTime;
                epicsTimeGetCurrent(&endTime);

                double duration = epicsTime(endTime) - epicsTime(startTime);
                double getPerSec = iterations*channels/duration;
                double gbit = getPerSec*arraySize*sizeof(double)*8/(1000*1000*1000); // * bits / giga; NO, it's really 1000 and not 1024
                if (verbose)
                    printf("%5.6f seconds, %.3f (x %d = %.3f) monitors/s, data throughput %5.3f Gbits/s\n",
                           duration, iterations/duration, channels, getPerSec, gbit);
                sum += getPerSec;

                iterationCount = 0;
                epicsTimeGetCurrent(&startTime);

                runCount++;
                if (runs == 0 || runCount < runs)
                {
                    // noop
                }
                else
                {
                    printf("%d %d %d %d %.3f\n", channels, arraySize, iterations, runs, sum/runs);

                    Lock guard(waitLoopPtrMutex);
                    waitLoopEvent->signal();    // all done
                }
            }
            else if (channelCount == 0)
            {
                // noop
            }

            monitor->release(element);
        }

    }

    virtual void unlisten(Monitor::shared_pointer const & /*monitor*/)
    {
        std::cerr << "unlisten" << std::endl;
    }

    bool waitUntilConnected(double timeOut)
    {
        return m_connectionEvent.wait(timeOut);
    }
};

class ChannelRequesterImpl : public ChannelRequester
{
private:
    Event m_event;

public:

    virtual string getRequesterName()
    {
        return "ChannelRequesterImpl";
    };

    virtual void message(std::string const & message,MessageType messageType)
    {
        std::cout << "[" << getRequesterName() << "] message(" << message << ", " << getMessageTypeName(messageType) << ")" << std::endl;
    }

    virtual void channelCreated(const epics::pvData::Status& status,
                                Channel::shared_pointer const & channel)
    {
        if (status.isSuccess())
        {
            // show warning
            if (!status.isOK())
            {
                std::cout << "[" << channel->getChannelName() << "] channel create: " << status << std::endl;
            }
        }
        else
        {
            std::cout << "[" << channel->getChannelName() << "] failed to create a channel: " << status << std::endl;
        }
    }

    virtual void channelStateChange(Channel::shared_pointer const & /*channel*/, Channel::ConnectionState connectionState)
    {
        if (connectionState == Channel::CONNECTED)
        {
            m_event.signal();
        }
        else
        {
            // ups... connection loss
            std::cout << Channel::ConnectionStateNames[connectionState] << std::endl;
            exit(3);
        }
    }

    bool waitUntilConnected(double timeOut)
    {
        return m_event.wait(timeOut);
    }
};

void runTest()
{
    reset();

    if (verbose)
        printf("%d channel(s) of double array size of %d element(s) (0==scalar), %d iteration(s) per run, %d run(s) (0==forever)\n", channels, arraySize, iterations, runs);

    vector<string> channelNames;
    char buf[64];
    for (int i = 0; i < channels; i++)
    {
        if (arraySize > 0)
            sprintf(buf, "testArray%d_%d", arraySize, i);
        else
            sprintf(buf, "test%d", i);
        channelNames.push_back(buf);
    }

    vector<Channel::shared_pointer> channels;
    for (vector<string>::const_iterator i = channelNames.begin();
            i != channelNames.end();
            i++)
    {
        TR1::shared_ptr<ChannelRequesterImpl> channelRequesterImpl(
            new ChannelRequesterImpl()
        );
        Channel::shared_pointer channel = provider->createChannel(*i, channelRequesterImpl);
        channels.push_back(channel);
    }

    bool differentConnectionsWarningIssued = false;
    string theRemoteAddress;
    for (vector<Channel::shared_pointer>::iterator i = channels.begin();
            i != channels.end();
            i++)
    {
        Channel::shared_pointer channel = *i;
        TR1::shared_ptr<ChannelRequesterImpl> channelRequesterImpl =
            TR1::dynamic_pointer_cast<ChannelRequesterImpl>(channel->getChannelRequester());
        if (channelRequesterImpl->waitUntilConnected(5.0))
        {
            string remoteAddress = channel->getRemoteAddress();
            if (theRemoteAddress.empty())
            {
                theRemoteAddress = remoteAddress;
            }
            else if (theRemoteAddress != remoteAddress)
            {
                if (!differentConnectionsWarningIssued)
                {
                    std::cout << "not all channels are hosted by the same connection: " <<
                              theRemoteAddress << " != " << remoteAddress << std::endl;
                    differentConnectionsWarningIssued = true;
                    // we assumes same connection (thread-safety)
                    exit(2);
                }
            }

            TR1::shared_ptr<ChannelMonitorRequesterImpl> getRequesterImpl(
                new ChannelMonitorRequesterImpl(channel->getChannelName())
            );
            Monitor::shared_pointer monitor = channel->createMonitor(getRequesterImpl, pvRequest);

            bool allOK = getRequesterImpl->waitUntilConnected(timeOut);

            if (!allOK)
            {
                std::cout << "[" << channel->getChannelName() << "] failed to get all the monitors" << std::endl;
                exit(1);
            }

            channelMonitorList.push_back(monitor);

        }
        else
        {
            std::cout << "[" << channel->getChannelName() << "] connection timeout" << std::endl;
            exit(1);
        }
    }
    if (verbose)
        std::cout << "all connected" << std::endl;

    {
        Lock guard(waitLoopPtrMutex);
        waitLoopEvent.reset(new Event());
    }
    epicsTimeGetCurrent(&startTime);
    monitor_all();

    waitLoopEvent->wait();
}

int main (int argc, char *argv[])
{
    int opt;                    // getopt() current option
    std::string testFile;

    setvbuf(stdout,NULL,_IOLBF,BUFSIZ);    // Set stdout to line buffering

    while ((opt = getopt(argc, argv, ":hr:w:i:c:s:l:f:v")) != -1) {
        switch (opt) {
        case 'h':               // Print usage
            usage();
            return 0;
        case 'w':               // Set PVA timeout value
            if((epicsScanDouble(optarg, &timeOut)) != 1)
            {
                fprintf(stderr, "'%s' is not a valid timeout value "
                        "- ignored. ('cainfo -h' for help.)\n", optarg);
                timeOut = DEFAULT_TIMEOUT;
            }
            break;
        case 'r':               // pvRequest string
            request = optarg;
            break;
        case 'i':               // iterations
            iterations = atoi(optarg);
            break;
        case 'c':               // channels
            channels = atoi(optarg);
            break;
        case 's':               // arraySize
            arraySize = atoi(optarg);
            break;
        case 'l':               // runs
            runs = atoi(optarg);
            break;
        case 'f':               // testFile
            testFile = optarg;
            break;
        case 'v':               // testFile
            verbose = true;
            break;
        case '?':
            fprintf(stderr,
                    "Unrecognized option: '-%c'. ('testGetPerformance -h' for help.)\n",
                    optopt);
            return 1;
        case ':':
            fprintf(stderr,
                    "Option '-%c' requires an argument. ('testGetPerformance -h' for help.)\n",
                    optopt);
            return 1;
        default :
            usage();
            return 1;
        }
    }

    // typedef enum {logLevelInfo, logLevelDebug, logLevelError, errlogFatal} errlogSevEnum;
    SET_LOG_LEVEL(logLevelError);

    pvRequest = CreateRequest::create()->createRequest(request);
    if (pvRequest.get() == 0) {
        printf("failed to parse request string\n");
        return 1;
    }

    ClientFactory::start();
    provider = ChannelProviderRegistry::clients()->getProvider("pva");

    if (!testFile.empty())
    {
        ifstream ifs(testFile.c_str(), ifstream::in);
        if (ifs.good())
        {
            string line;
            while (true)
            {
                getline(ifs, line);
                if (ifs.good())
                {
                    // ignore lines that starts (no trimming) with '#'
                    if (line.find('#') != 0)
                    {
                        // <c> <s> <i> <l>
                        if (sscanf(line.c_str(), "%d %d %d %d", &channels, &arraySize, &iterations, &runs) == 4)
                        {
                            //printf("%d %d %d %d\n", channels, arraySize, iterations, runs);
                            runTest();

                            // wait a bit for a next test
                            epicsThreadSleep(1.0);
                        }
                        else
                        {
                            fprintf(stderr,
                                    "Failed to parse line '%s', ignoring...\n",
                                    line.c_str());
                        }
                    }
                }
                else
                    break;
            }
        }
        else
        {
            fprintf(stderr,
                    "Failed to open file '%s'\n",
                    testFile.c_str());
            return 2;
        }

        ifs.close();
    }
    else
    {
        // in non-file mode, verbose is true by default
        verbose = true;
        runTest();
    }

    //ClientFactory::stop();

    return 0;
}