-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.cpp
executable file
·430 lines (362 loc) · 10.8 KB
/
server.cpp
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
#include <arpa/inet.h>
#include <boost/program_options.hpp>
#include <errno.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/event.h>
#include <event2/listener.h>
#include <event2/thread.h>
#include <fcntl.h>
#include <fstream>
#include <iostream>
#include <map>
#include <signal.h>
#include <stdio.h>
#include <string>
#include "badbaseexception.hpp"
#include "eventbase.hpp"
#include "network.hpp"
#include "tpool.h"
namespace po = boost::program_options;
using namespace dm;
#define DFLT_THREADS 16
#define DFLT_QUEUE 4096
#define DFLT_PORT 32000
#define LISTEN_BACKLOG 65535
struct clientStats
{
std::string hostName;
int port;
int requestsRecv;
unsigned long dataSent;
};
/**
* Perform the initialization required to use the libevent library.
*
* @author Dean Morin
* @param method The desired event method to use.
* @return The initialized event base. This is heap allocated and so the caller
* must call delete on it later.
*/
EventBase* initlibEvent(const char* method);
evutil_socket_t listenSock(const int port);
void runServer(EventBase* eb, const int port, const int numWorkerThreads,
const int maxQueueSize);
void runServerTh(const int port, const int numWorkerThreads,
const int maxQueueSize);
void updateClientStats(evutil_socket_t fd, int data);
/**
* Increment the count of connected clients. Thread safe.
*
* @author Dean Morin
* @param sa The address info on the new connection.
*/
void incrementClients(evutil_socket_t fd, struct sockaddr_in* sa);
/**
* Decrement the count of connected clients. Thread safe.
*
* @author Dean Morin
* @param fd The socket that is being closed.
*/
void decrementClients(evutil_socket_t fd);
pthread_mutex_t clientMutex;
pthread_mutex_t jobMutex;
int clientCount;
int maxClientCount;
std::map<evutil_socket_t, struct clientStats> clientStats;
/**
* A server intended to test the differences in efficiency between the various
* event handling methods.
*
* @author Dean Morin
*/
int main(int argc, char** argv)
{
int opt = 0;
int port = 0;
int threads = 0;
int queue = 0;
EventBase* eb = NULL;
std::string method = "";
po::options_description desc("Allowed options");
desc.add_options()
("kqueue,k", "use kqueue()")
("epoll,e", "use epoll()")
("select,s", "use select()")
("poll,p", "use poll()")
("port,P", po::value<int>(&opt)->default_value(DFLT_PORT),
"port to listen on")
("thread-pool,T", po::value<int>(&opt)->default_value(DFLT_THREADS),
"number of threads in the thread pool")
("max-queue,M", po::value<int>(&opt)->default_value(DFLT_QUEUE),
"max number of jobs in the pool queue")
("help", "show this message")
;
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
}
catch (const std::exception& e)
{
std::cerr << "Error: " << e.what() << "\n";
std::cerr << "\tuse --help to see program options\n";
return 1;
}
port = vm["port"].as<int>();
threads = vm["thread-pool"].as<int>();
queue = vm["max-queue"].as<int>();
if (pthread_mutex_init(&clientMutex, NULL))
{
std::cerr << "Error creating mutex\n";
exit(1);
}
if (pthread_mutex_init(&jobMutex, NULL))
{
std::cerr << "Error creating mutex\n";
exit(1);
}
clientCount = 0;
maxClientCount = 0;
if (vm.count("help"))
{
std::cout << desc << "\n";
}
else if (vm.count("kqueue"))
{
method = "kqueue";
}
else if (vm.count("epoll"))
{
method = "epoll";
}
else if (vm.count("select"))
{
method = "select";
}
else if (vm.count("poll"))
{
method = "poll";
}
// run server with libevent and the specified event base
eb = initlibEvent(method.c_str());
runServer(eb, port, threads, queue);
return 0;
}
EventBase* initlibEvent(const char* method)
{
try
{
EventBase* eb = new EventBase(method);
std::cout << "Using: " << eb->getMethod() << "\n";
return eb;
}
catch (const BadBaseException& e)
{
int i = 0;
const char** methods = EventBase::getAvailableMethods();
std::cerr << "Error: " << e.what() << "\n";
std::cerr << "\tThe available event bases are:\n";
for (i = 0; methods[i] != NULL; i++)
{
std::cerr << "\t - " << methods[i] << "\n";
}
exit(1);
}
catch (...)
{
std::cerr << "Error: pthreads are not available on this machine\n";
exit(1);
}
}
/**
* Display the maximum number of clients that were connected at one time, then
* shut down the server. Initiated by ctrl-c.
*
* @author Dean Morin
*/
void shutDown(int)
{
std::cout << "\nHighest number of simultaneous connections: "
<< maxClientCount << "\n\n";
pthread_mutex_lock(&clientMutex);
std::cout << "Clients still connected: \n\n";
std::map<evutil_socket_t, struct clientStats>::iterator it;
for (it = clientStats.begin(); it != clientStats.end(); ++it)
{
struct clientStats c = it->second;
std::cout << "\tHost name:\t\t" << c.hostName << "\n"
<< "\tPort:\t\t\t" << c.port << "\n"
<< "\tRequests received:\t" << c.requestsRecv << "\n"
<< "\tData sent:\t\t" << c.dataSent << "\n\n";
}
pthread_mutex_unlock(&clientMutex);
exit(0);
}
void handleSigurg(evutil_socket_t, short, void*)
{
std::cout << "Out of band data arrived. Probably best to just ignore it...\n";
}
/**
* When ctrl-c is pressed and libevent is being used, this function frees the
* listen socket, then calls shutDown().
*
* @param arg The struct responsible for the listening socket.
* @author Dean Morin
*/
void handleSigint(evutil_socket_t, short, void* arg)
{
evconnlistener_free((struct evconnlistener*) arg);
shutDown(0);
}
void cancelJobs(tPool* tpool, struct bufferevent* bev)
{
pthread_mutex_lock(&tpool->queueLock);
tPoolJob* currentJob = tpool->queueHead;
struct bufferevent* currentBev;
while(currentJob != NULL)
{
currentBev = (struct bufferevent*) currentJob->arg;
if (currentBev == bev)
{
currentJob->arg = NULL;
}
currentJob = currentJob->next;
}
pthread_mutex_unlock(&tpool->queueLock);
}
static void sockEvent(struct bufferevent* bev, short events, void* arg)
{
if (events & BEV_EVENT_ERROR)
{
perror("Error from bufferevent");
}
if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR))
{
decrementClients(bufferevent_getfd(bev));
pthread_mutex_lock(&jobMutex);
cancelJobs((tPool*)arg, bev);
bufferevent_free(bev);
pthread_mutex_unlock(&jobMutex);
}
}
void handleRequest(void* args)
{
pthread_mutex_lock(&jobMutex);
if (!args)
{
// bufferevent has been freed; this is a stale job
pthread_mutex_unlock(&jobMutex);
return;
}
struct bufferevent* bev = (struct bufferevent*) args;
evutil_socket_t fd = bufferevent_getfd(bev);
struct evbuffer *input = bufferevent_get_input(bev);
struct evbuffer *output = bufferevent_get_output(bev);
uint32_t msgSize;
if (evbuffer_copyout(input, &msgSize, sizeof(uint32_t)) == -1)
{
std::cerr << "Error: evbuffer_copyout\n";
}
char* buf = new char[msgSize];
// fill the packet with random characters
for (size_t i = 0; i < msgSize; i++)
{
buf[i] = rand() % 93 + 33;
}
evbuffer_add(output, buf, msgSize);
pthread_mutex_unlock(&jobMutex);
updateClientStats(fd, msgSize);
delete[] buf;
}
static void readSock(struct bufferevent* bev, void* arg)
{
if (tPoolAddJob((tPool*) arg, handleRequest, bev))
{
std::cerr << "Error adding new job to thread pool\n";
exit(1);
}
}
static void acceptErr(struct evconnlistener* listener, void*)
{
struct event_base *base = evconnlistener_get_base(listener);
int err = EVUTIL_SOCKET_ERROR();
std::cerr << "Error " << err << "(" << evutil_socket_error_to_string(err)
<< ") on listening socket. Shutting down.\n";
event_base_loopexit(base, NULL);
}
static void acceptClient(struct evconnlistener* listener, evutil_socket_t fd,
struct sockaddr* sa, int, void* arg)
{
incrementClients(fd, (sockaddr_in*) sa);
struct event_base* base = evconnlistener_get_base(listener);
struct bufferevent* bev = bufferevent_socket_new(base, fd,
BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, readSock, NULL, sockEvent, arg);
bufferevent_enable(bev, EV_READ | EV_WRITE);
}
void runServer(EventBase* eb, const int port, const int numWorkerThreads,
const int maxQueueSize)
{
struct sockaddr_in addr;
struct evconnlistener* listener;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
tPool* pool = NULL;
int blockWhenQueueFull = 1;
if (tPoolInit(&pool, numWorkerThreads, maxQueueSize, blockWhenQueueFull))
{
std::cerr << "Error initializing thread pool\n";
exit(1);
}
if (!(listener = evconnlistener_new_bind(eb->getBase(), acceptClient, pool,
LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, LISTEN_BACKLOG,
(struct sockaddr*) &addr, sizeof(addr))))
{
exit(sockError("evconnlistener_new_bind()", 0));
}
evconnlistener_set_error_cb(listener, acceptErr);
struct event* sigint;
sigint = evsignal_new(eb->getBase(), SIGINT, handleSigint, listener);
evsignal_add(sigint, NULL);
struct event* sigurg;
sigurg = evsignal_new(eb->getBase(), SIGURG, handleSigurg, NULL);
evsignal_add(sigurg, NULL);
event_base_dispatch(eb->getBase());
event_del(sigint);
}
void updateClientStats(evutil_socket_t fd, int data)
{
pthread_mutex_lock(&clientMutex);
clientStats[fd].requestsRecv++;
clientStats[fd].dataSent += data;
pthread_mutex_unlock(&clientMutex);
}
void incrementClients(evutil_socket_t fd, struct sockaddr_in* sa)
{
pthread_mutex_lock(&clientMutex);
if (++clientCount > maxClientCount)
{
maxClientCount = clientCount;
}
#ifdef DEBUG
std::cout << "Clients++ " << clientCount << "\n";
#endif
// add client to map
clientStats[fd].hostName = inet_ntoa(sa->sin_addr);
clientStats[fd].port = sa->sin_port;
pthread_mutex_unlock(&clientMutex);
}
void decrementClients(evutil_socket_t fd)
{
pthread_mutex_lock(&clientMutex);
clientCount--;
#ifdef DEBUG
std::cout << "Clients-- " << clientCount << "\n";
#endif
clientStats.erase(fd);
pthread_mutex_unlock(&clientMutex);
}