-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheasy_server.cpp
619 lines (529 loc) · 16.9 KB
/
easy_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
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
/*
* easy_server.cpp
*
* Created on: 2016年9月28日
* Author: chenms
*/
#include "easy_server.h"
#include "common_structs.h"
#include "worker_thread.h"
thread_local int thread_local_port=-1;
thread_local bool isworkerthread=false;
EasyServer::EasyServer(int num_of_workers, int num_of_threads_in_threadpool)
{
num_of_workers_=num_of_workers;
num_of_threads_in_threadpool_=num_of_threads_in_threadpool;
last_thread_index_=-1;
getresultcb_=NULL;
tcpclosecb_=NULL;
}
EasyServer::~EasyServer()
{
for(auto pos=vec_tcp_listeners_.begin();pos!=vec_tcp_listeners_.end();++pos)
{
if(pos->tcp_listen_base)
event_base_free(pos->tcp_listen_base);
if(pos->tcp_listener)
evconnlistener_free(pos->tcp_listener);
}
for(auto pos=vec_udp_listeners_.begin();pos!=vec_udp_listeners_.end();++pos)
{
if(pos->udp_listen_base)
event_base_free(pos->udp_listen_base);
if(pos->udp_listen_event)
event_free(pos->udp_listen_event);
if(pos->udp_listen_socket!=-1)
close(pos->udp_listen_socket);
}
for(auto pos=vec_overtime_listeners_.begin();pos!=vec_overtime_listeners_.end();++pos)
{
if(pos->overtime_listen_base)
event_base_free(pos->overtime_listen_base);
if(pos->overtime_listen_event)
event_free(pos->overtime_listen_event);
}
}
// bool EasyServer::AddTcpListener(int port)
// {
// TcpListener tl;
// if(!StartTcpListen(tl,port)){
// return false;
// }
// vec_tcp_listeners_.push_back(tl);
// return true;
// }
bool EasyServer::AddTcpListener(int port,TcpPacketHandleCb& tphcb)
{
TcpListener tl;
if(!StartTcpListen(tl,port)){
return false;
}
vec_tcp_listeners_.push_back(tl);
vec_tcppackethandlecbs_.push_back(tphcb);
return true;
}
// bool EasyServer::AddUdpListener(int port)
// {
// UdpListener ul;
// if(!StartUdpListen(ul,port))
// {
// return false;
// }
// vec_udp_listeners_.push_back(ul);
// return true;
// }
bool EasyServer::AddUdpListener(int port,UdpPacketHandleCb& udpcb)
{
UdpListener ul;
if(!StartUdpListen(ul,port))
{
return false;
}
vec_udp_listeners_.push_back(ul);
vec_udppackethandlecbs_.push_back(udpcb);
return true;
}
bool EasyServer::AddOvertimeListener(int tm,overtime_cb cb,void * arg)
{
OvertimeListener ol;
if(!StartOvertimeListen(ol,tm,cb,arg))
{
return false;
}
vec_overtime_listeners_.push_back(ol);
return true;
}
bool EasyServer::StartTcpListen(TcpListener& tl,int port)
{
event_base * base=NULL;
evconnlistener *listener=NULL;
std::shared_ptr<std::thread> listen_thread;
do{
struct sockaddr_in sin;
base = event_base_new();
if (!base)
break;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(0);
sin.sin_port = htons(port);
listener = evconnlistener_new_bind(base,EasyServer::AcceptTcpConn, this,LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1, (struct sockaddr*)&sin, sizeof(sin));
if (!listener)
break;
evconnlistener_set_error_cb(listener,EasyServer::AcceptTcpError);
try{
listen_thread.reset(new std::thread([this,port,base]
{
thread_local_port=port;
event_base_dispatch(base);
}
));
}catch(...){
break;
}
tl.tcp_listen_base=base;
tl.tcp_listener=listener;
tl.tcp_listen_thread=listen_thread;
return true;
}while(0);
if(base)
event_base_free(base);
if(listener)
evconnlistener_free(listener);
LOG(ERROR)<<"Tcp listen on the port "<<port<<" failed";
return false;
}
bool EasyServer::StartUdpListen(UdpListener& ul,int port)
{
event_base * base=NULL;
struct event * listen_event=NULL;
int listen_socket=-1;
std::shared_ptr<std::thread> listen_thread;
do{
listen_socket=socket(AF_INET,SOCK_DGRAM,0);
if(listen_socket==-1)
{
break;
}
struct sockaddr_in sin;
base = event_base_new();
if (!base)
break;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(0);
sin.sin_port = htons(port);
if(bind(listen_socket,(const sockaddr *)&sin,sizeof(sin))==-1)
{
break;
}
listen_event=event_new(base,listen_socket,EV_READ | EV_PERSIST,EasyServer::AcceptUdpConn,(void *)this);
if(!listen_event)
break;
if(event_add(listen_event, 0))
break;
try{
listen_thread.reset(new std::thread([this,port,base]
{
thread_local_port=port;
event_base_dispatch(base);
}
));
}catch(...){
break;
}
ul.udp_listen_base=base;
ul.udp_listen_event=listen_event;
ul.udp_listen_socket=listen_socket;
ul.udp_listen_thread=listen_thread;
return true;
}while(0);
if(base)
event_base_free(base);
if(listen_event)
event_free(listen_event);
if(listen_socket!=-1)
close(listen_socket);
LOG(ERROR)<<"Udp listen on the port "<<port<<" failed";
return false;
}
bool EasyServer::StartOvertimeListen(OvertimeListener& ol,int timespan,overtime_cb cb,void * arg)
{
struct event * listen_event=NULL;
event_base * base=NULL;
std::shared_ptr<std::thread> listen_thread;
do{
try{
base=event_base_new();
if(!base)
break;
listen_event=event_new(base,-1,EV_TIMEOUT|EV_PERSIST,cb,arg);
if(!listen_event)
break;
timeval tv={timespan,0};
if(event_add(listen_event,&tv)==-1)
break;
listen_thread.reset(new std::thread([this,base]
{
event_base_dispatch(base);
}
));
}
catch(...){
break;
}
ol.overtime_listen_base=base;
ol.overtime_listen_event=listen_event;
ol.overtime_listen_thread=listen_thread;
return true;
}while (0);
LOG(ERROR)<<"Start the overtime listen thread failed";
if(base)
event_base_free(base);
if(listen_event)
event_free(listen_event);
return false;
}
void EasyServer::Start()
{
if(!factory_){
factory_.reset(new TcpConnFactory);
if(!factory_)
{
LOG(ERROR)<<"create tcp conn factory failed!";
return;
}
LOG(INFO)<<"using default tcp conn factory";
}
else {
LOG(INFO)<<"using selfdefined tcp conn factory";
}
// if(!CreateAllWorkerThreads()){
// LOG(ERROR)<<"Create worker threads failed";
// return;
// }
for(auto pos=vec_tcp_listeners_.begin();pos!=vec_tcp_listeners_.end();++pos)
{
pos->tcp_listen_thread->join();
}
for(auto pos=vec_udp_listeners_.begin();pos!=vec_udp_listeners_.end();++pos)
{
pos->udp_listen_thread->join();
}
for(auto pos=vec_overtime_listeners_.begin();pos!=vec_overtime_listeners_.end();++pos)
{
pos->overtime_listen_thread->join();
}
LOG(ERROR)<<"You haven't added a listener yet";
}
bool EasyServer::CreateAllWorkerThreads()
{
bool ret=true;
try {
thread_pool_.reset(new ThreadPool(num_of_threads_in_threadpool_));
for(int i=0;i<num_of_workers_;++i){
std::shared_ptr<WorkerThread> pti(new WorkerThread(this,i));
if(!pti->Run())
{
ret=false;
break;
}
vec_workers_.push_back(pti);
}
} catch (...) {
ret=false;
}
return ret;
}
void EasyServer::AcceptTcpError(evconnlistener *listener, void *ptr)
{
//TODO
LOG(ERROR)<<"TCP Listen Thread Accept Error";
}
void EasyServer::AcceptTcpConn(evconnlistener * listener, int sock, sockaddr * addr, int len, void *ptr)
{
void * ipaddr=nedalloc::nedmalloc(len);
if(ipaddr){
memcpy(ipaddr,addr,len);
}
EasyServer * es=static_cast<EasyServer *>(ptr);
int cur_thread_index=es->GetIndexOfIdleWorker();
SocketPort sp{sock,thread_local_port,ipaddr};
if(!es->GetWorkerByIndex(cur_thread_index)->PushTcpConnIntoQueueAndSendNotify(sp)){
LOG(WARNING)<<"tcp notify worker failed,close the tcp socket!";
close(sock);
}
}
void EasyServer::AcceptUdpConn(evutil_socket_t fd, short what, void * arg){
LOG(DEBUG)<<"Accept udp Conn";
EasyServer * es=static_cast<EasyServer *>(arg);
socklen_t addr_len=sizeof(sockaddr_in);
struct sockaddr_in * addr=NULL;
int datalen=-1;
void * data=NULL;
int dupfd=-1;
do{
addr=(struct sockaddr_in *)nedalloc::nedcalloc(addr_len,1);
if(!addr)
{
LOG(WARNING)<<"nedalloc::nedcalloc failed for udp addr";
break;
}
else{
LOG(DEBUG)<<"Allocated "<<addr_len<<" bytes data for udp addr ";
}
char buf[65535]={0};
if((datalen=recvfrom(fd,buf,65535,0,(struct sockaddr *)addr,&addr_len))<=0){
LOG(WARNING)<<"read data from udp failed";
break;
}
data=nedalloc::nedmalloc(datalen);
if(!data)
{
LOG(WARNING)<<"nedalloc::nedmalloc failed for udp packet";
break;
}
else{
LOG(DEBUG)<<"Allocated "<<datalen<<" bytes data for udp packet ";
}
memcpy(data,buf,datalen);
dupfd=dup(fd);
if(dupfd==-1){
LOG(WARNING)<<"dup udp fd failed";
break;
}
else{
LOG(DEBUG)<<"dup udp fd success!"<<dupfd;
}
bool packethandled=false;
for(auto pos=es->vec_udppackethandlecbs_.begin();pos!=es->vec_udppackethandlecbs_.end();++pos){
if(pos->port==thread_local_port){
if(pos->cb){
es->thread_pool_->enqueue(*pos,es,(unsigned char *)data,(int)datalen,(void *)addr,(int)addr_len,dupfd);
packethandled=true;
}
}
}
if(!packethandled)
LOG(WARNING)<<"packet can't get handle cb for port "<<thread_local_port;
return;
}while(0);
//error occurs
if(addr){
LOG(DEBUG)<<"Free "<<addr_len<<" bytes data for udp addr ";
nedalloc::nedfree(addr);
}
if(data){
LOG(DEBUG)<<"Free "<<datalen<<" bytes data for udp packet ";
nedalloc::nedfree(data);
}
if(dupfd!=-1){
LOG(DEBUG)<<"close duplicated fd for udp fd"<<dupfd;
close(dupfd);
}
}
void EasyServer::SendDataToTcpConnection(int threadindex,const std::string& sessionid,void * data,unsigned int len,void *arg,int arglen,bool hasResultCb)
{
if(threadindex<0||sessionid.empty())
return;
std::shared_ptr<WorkerThread> worker=vec_workers_[threadindex];
if(worker){
char tmp[1000]={0};
const char * hexstr=ConvertBytes2HexString((const unsigned char *)data,len,tmp,1000);
// LOG(DEBUG)<<hexstr;
if(!isworkerthread){//in thread pool
SessionData sd(data,len,sessionid,arg,arglen);
sd.hasResultCb=hasResultCb;
if(!worker->PushDataIntoQueueAndSendNotify(sd,'d')){
LOG(WARNING)<<"PushDataIntoQueueAndSendNotify failed";
}
else{
LOG(DEBUG)<<"send data back to tcp connection from threadpool "<<sessionid<<" "<<hexstr;
}
}
else{//send directly
LOG(DEBUG)<<"send data back to tcp connection from worker "<<sessionid<<" "<<hexstr;
worker->SendDataToTcpConnection(data,len,sessionid,arg,arglen,hasResultCb);
}
}
else{
LOG(WARNING)<<"wrong thread index";
}
}
void EasyServer::SendDataToTcpConnection(int threadindex,const std::string& sessionid,const std::string& strdata,const std::string& strarg,bool hasResultCb)
{
if(threadindex<0||sessionid.empty())
return;
std::shared_ptr<WorkerThread> worker=vec_workers_[threadindex];
if(worker){
char tmp[1000]={0};
const char * hexstr=ConvertBytes2HexString((const unsigned char *)strdata.c_str(),strdata.length(),tmp,1000);
if(!isworkerthread){//in thread pool
SessionData sd(sessionid,strdata,strarg);
sd.hasResultCb=hasResultCb;
if(!worker->PushDataIntoQueueAndSendNotify(sd,'e')){
LOG(WARNING)<<"PushDataIntoQueueAndSendNotify failed";
}
else{
LOG(DEBUG)<<"send data back to tcp connection from threadpool "<<hexstr;
}
}
else{//send directly
LOG(DEBUG)<<"send data back to tcp connection from worker "<<hexstr;
worker->SendDataToTcpConnection(sessionid,strdata,strarg,hasResultCb);
}
}
else{
LOG(WARNING)<<"wrong thread index";
}
}
void EasyServer::CloseTcpConnection(int threadindex,const std::string& sessionid)
{
std::shared_ptr<WorkerThread> worker=vec_workers_[threadindex];
if(worker){
if(!isworkerthread){//in thread pool
SessionKill sk(sessionid);
if(!worker->PushKillIntoQueueAndSendNotify(sk)){
LOG(WARNING)<<"PushKillIntoQueueAndSendNotify failed";
}
else{
LOG(DEBUG)<<"send kill notification to tcp connection from threadpool";
}
}
else{//send directly
LOG(DEBUG)<<"send kill notification to tcp connection from worker";
worker->KillTcpConnection(sessionid);
}
}
else{
LOG(WARNING)<<"wrong thread index";
}
}
std::shared_ptr<TcpConnItem> EasyServer::GetTcpConnection(int threadindex,const std::string& sessionid){
if(threadindex<0||sessionid.empty())
return std::shared_ptr<TcpConnItem>(nullptr);
return vec_workers_[threadindex]->FindTcpConnItem(sessionid);
}
bool EasyServer::IsTcpConnectionExist(int threadindex,const std::string& sessionid)
{
bool ret=true;
do{
if(threadindex<0||sessionid.empty()){
ret=false;
break;
}
ret=vec_workers_[threadindex]->IsTcpConnItemExist(sessionid);
}while(0);
return ret;
}
bool EasyServer::Init()
{
if(!CreateAllWorkerThreads()){
LOG(ERROR)<<"Create worker threads failed";
return false;
}
return true;
}
void EasyServer::SendDataToCaptureThread(const std::string& strdata)
{
boost::shared_lock<boost::shared_mutex> lock(mutex_un_map_capture);
for(auto pos=un_map_capture.begin();pos!=un_map_capture.end();++pos){
SendDataToTcpConnection(pos->second,pos->first,strdata);
}
}
int EasyServer::GetKillQueueSize(){
int ret=0;
for(auto pos=vec_workers_.begin();pos!=vec_workers_.end();++pos){
ret+=(*pos)->GetKillSize();
}
return ret;
}
int EasyServer::GetDownloadQueueSize(){
int ret=0;
for(auto pos=vec_workers_.begin();pos!=vec_workers_.end();++pos){
ret+=(*pos)->GetDownloadSize();
}
return ret;
}
int EasyServer::GetSocketQueueSize(){
int ret=0;
for(auto pos=vec_workers_.begin();pos!=vec_workers_.end();++pos){
ret+=(*pos)->GetSocketQueueSize();
}
return ret;
}
int EasyServer::GetTotalSessionNum(){
int ret=0;
for(auto pos=vec_workers_.begin();pos!=vec_workers_.end();++pos){
ret+=(*pos)->GetSessionMapSize();
}
return ret;
}
int EasyServer::GetThreadPoolQueueSize(){
return thread_pool_->GetQueueSize();
}
void EasyServer::ClearAllContainers(){
for(auto pos=vec_workers_.begin();pos!=vec_workers_.end();++pos){
(*pos)->ClearAll();
}
thread_pool_->ClearQueue();
}
std::string EasyServer::GetTotalSessionString()
{
std::string ret;
for(auto pos=vec_workers_.begin();pos!=vec_workers_.end();++pos){
ret+=(*pos)->GetSessionString();
}
return ret;
}
//reponse the cmd from the terminal
// extern void MonitorServer(EasyServer * server,int threadindex,const std::string& sessionid,unsigned char * data,int len);
extern void ReleaseCapture(TcpConnItem * tci);
bool EasyServer::AddMonitorListener(int port,tcppackethandle_cb tcpcb)
{
TcpPacketHandleCb cb(tcpcb,port,false,true,NULL,-1,NULL,ReleaseCapture,NULL);
if(!AddTcpListener(port,cb)){
return false;
}
return true;
}