-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservant.cpp
More file actions
2012 lines (1687 loc) · 51.1 KB
/
Copy pathservant.cpp
File metadata and controls
2012 lines (1687 loc) · 51.1 KB
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "includes.h"
#include "constants.h"
#include "startup.h"
#include "init.h"
#include "error.h"
#include "msg.h"
#include "neighbor_list.h"
#include "event.h"
#include "util.h"
#include "dispatch.h"
#include "bitvector.h"
#include "indice.h"
#include "globals.h"
#include "lru.h"
map<int, struct Meta> g_ui2meta;
string g_getextfile;
FILE *fp_stat_file;
void *keep_alive_th(void* arg)
{
struct timeval _tv;
_tv.tv_sec = ini.keepaliveto / 2;
_tv.tv_usec = 0;
while(1) {
struct timeval tv = _tv;
select(0, NULL, NULL, NULL, &tv);
if(g_time2die > -1) { //@
return NULL;
}
// Create Hdr
char uoid[20];
char obj_type[] = "msg";
getuoid(ini.node_inst_id, obj_type, uoid, 20);
// Hdr * hdr = new Hdr(KPAV, uoid, 2);
Hdr * hdr = new Hdr(KPAV, uoid, 1); //!
// Create Event
Event ev(EV_MSG, SD_KPAV, hdr, NULL); // -1 for cmd_th. -2 for keep_alive_th. -3 for CKRQ
pthread_mutex_lock(&g_mutex1);
{
g_que1.push(ev);
pthread_cond_signal(&g_cv1);
}
pthread_mutex_unlock(&g_mutex1);
/* Old way of waking up sleeping threads .. efficient on network but may cause deadlocks
pthread_mutex_lock(&g_mutex_hostid2sd);
{
if(DEBUG_PRO_EV) printf("/## 1\n");
std::map<string, int>::iterator itr;
// For every sd currently available,
for(itr = g_hostid2sd.begin(); itr != g_hostid2sd.end(); itr++) {
int sd = itr->second;
pthread_mutex_lock(&g_mutex_sd2conn);
{
conn = g_sd2conn[sd];
pthread_mutex_lock(&conn->mutex);
{
pthread_cond_signal(&conn->cv);
}
pthread_mutex_unlock(&conn->mutex);
}
pthread_mutex_unlock(&g_mutex_sd2conn);
}
}
pthread_mutex_unlock(&g_mutex_hostid2sd);
*/
}
return NULL;
}
void* read_th(void* arg) {
int sd = *((int*) arg);
Hdr* hdr = NULL;
void* vmsg = NULL;
int x;
Connection *conn;
pthread_mutex_lock(&g_mutex_sd2conn);
{
std::map<int, Connection* >::iterator sd2conn_iter;
sd2conn_iter = g_sd2conn.find(sd);
if(sd2conn_iter == g_sd2conn.end()) {
pthread_mutex_unlock(&g_mutex_sd2conn);
return NULL;
}
conn = g_sd2conn[sd];
}
pthread_mutex_unlock(&g_mutex_sd2conn);
while(1) {
// Fill the message
if(g_time2die > -1) { //@
return NULL;
}
x = recv_msg(sd, &hdr, &vmsg);
if(x == -1) {
pthread_mutex_lock(&(conn->mutex));
conn->time2die = 1;
//printf("Error in recv message: in read th\n");
/*
if(conn->is_beacon != -1) {
pthread_mutex_lock(&(g_mutex_beacon_status));
g_beacon_status[conn->is_beacon] = 0;
pthread_mutex_unlock(&(g_mutex_beacon_status));
pthread_mutex_lock(&(g_mutex_hostid2sd));
map<string, int>::iterator it = g_hostid2sd.find(conn->peerid);
g_hostid2sd.erase(it);
pthread_mutex_unlock(&(g_mutex_hostid2sd));
}
*/
pthread_mutex_unlock(&(conn->mutex));
return NULL ;
}
//Not enough space to remove the packet .. only happens when we are out of space for temp_file
if(x == -2) {
printf("Not Enough space to recive a file .. Please clear some space.\n");
continue;
}
// Create an level-1 event
Event ev1(EV_MSG, sd, hdr, vmsg);
// Push the event into the level-1 event queue
pthread_mutex_lock(&g_mutex1);
{
g_que1.push(ev1);
pthread_cond_signal(&g_cv1);
}
pthread_mutex_unlock(&g_mutex1);
}
return NULL;
} // end of read_th
void* write_th(void* arg) {
int sd = *((int*) arg);
Connection *conn;
Event ev;
pthread_mutex_lock(&g_mutex_sd2conn);
{
std::map<int, Connection* >::iterator sd2conn_iter;
sd2conn_iter = g_sd2conn.find(sd);
if(sd2conn_iter == g_sd2conn.end()) {
pthread_mutex_unlock(&g_mutex_sd2conn);
return NULL;
}
conn = g_sd2conn[sd];
}
pthread_mutex_unlock(&g_mutex_sd2conn);
while(1) {
// Get connection info.
// Pop an Level-2 event
pthread_mutex_lock(&(conn->mutex));
{
// Wait while queue is empty
while(conn->que.size() == 0) {
// If time to die, send notify to the other node on the socket
if(conn->time2die > -1) {
pthread_mutex_unlock(&(conn->mutex));
//send_notify(conn->time2die, sd);
return NULL;
}
if(g_time2die > -1) {
pthread_mutex_unlock(&(conn->mutex));
if(DEBUG) printf("write th():Sending Notify msg.\n");
send_notify(g_time2die, sd);
return NULL;
}
pthread_cond_wait(&(conn->cv), &(conn->mutex));
}
// Retrieve an event from L2 queue
ev = conn->que.front();
conn->que.pop();
if(DEBUG) printf("write th():Pop L2 event. msg_type: 0x%02x.\n", (unsigned char) ev.hdr->msg_type);
}
pthread_mutex_unlock(&(conn->mutex));
if(conn->time2die > -1) {
ev.cleanup();
// Evacuate the Level-2 queue
pthread_mutex_lock(&(conn->mutex));
{
while(conn->que.size() > 0){
ev = conn->que.front();
conn->que.pop();
ev.cleanup();
}
}
pthread_mutex_unlock(&(conn->mutex));
return NULL;
}
if(g_time2die > -1) {
// If time to die, send notify to the other node on the socket
if(DEBUG) printf("write th():Sending Notify msg.\n");
send_notify(g_time2die, sd);
ev.cleanup();
// Evacuate the Level-2 queue
pthread_mutex_lock(&(conn->mutex));
{
while(conn->que.size() > 0){
ev = conn->que.front();
conn->que.pop();
ev.cleanup();
}
}
pthread_mutex_unlock(&(conn->mutex));
return NULL;
}
// Send the message in the event
if(DEBUG) printf("write th():Sending msg: 0x%02x.\n", (unsigned char) ev.hdr->msg_type);
int send_err = send_msg(ev.sd, ev.hdr, ev.vmsg);
// Log sent msg
if(send_err == 0) {
pthread_mutex_lock(&g_mutex_log_msg);
log_msg(g_log_file, ev.hdr, ev.vmsg, ev.rfs, ev.sd);
pthread_mutex_unlock(&g_mutex_log_msg);
}
if(send_err == -1) {
//printf("Error Sending message in write thread\n");
continue;
}
ev.cleanup();
}
return NULL;
} // end of write_th()
int explore_neighbors() {
string beacon_name;
unsigned short beacon_port;
hostent* beacon = NULL;
sockaddr_in beacon_addr;
int result = ERR;
int num_neighbors = 0;
Hdr* request_hdr = NULL;
Join_req* request_msg = NULL;
Hdr* reply_hdr = NULL;
Join_res* reply_msg = NULL;
char init_neighbor_name[300] = "";
g_neighbor_list.nodes.clear();
sprintf(init_neighbor_name, "%sinit_neighbor_list", ini.homedir);
// if reset option is not given
if(g_reset == false) {
struct stat statbuff;
int status = stat(init_neighbor_name, &statbuff);
// check if file already exists.
if(status == 0) {
// No need to explore neighbors. Just read them from init_neighbor_list file.
g_neighbor_list.read_file();
if(DEBUG) printf("I read init_neighbor_list file!\n");
return 0;
}
}
else {
FILE *fp = fopen(init_neighbor_name, "w");
fclose(fp);
if(DEBUG) printf("init_neighbor_list file deleted.\n");
}
// Create a socket to send a join msg
int join_sock = socket(PF_INET, SOCK_STREAM, 0);
if(join_sock == -1) {
print_error_and_exit("socket() error!\n");
}
// Try sending a join msg to one of the beacons
unsigned int i = 0;
for(i = 0; i < ini.beacon_name.size(); i++) {
// Choose a beacon
beacon_name = ini.beacon_name[i];
beacon_port = ini.beacon_port[i];
beacon = gethostbyname(beacon_name.c_str());
// if the beacon is not reachable, try the next one
if(!beacon) {
if(DEBUG) print_error("Unable to resolve address of a beacon");
continue; // Try next beacon
}
memcpy(&beacon_addr.sin_addr, beacon->h_addr, beacon->h_length);
// Set beacon address and port
beacon_addr.sin_family = AF_INET;
beacon_addr.sin_port = beacon_port;
// Connect to the beacon
result = connect(join_sock, (struct sockaddr*) &beacon_addr, sizeof(beacon_addr));
if(result == 0) {
if(DEBUG) print_error("connect() success");
break; // beacon connected
}
//perror("connect()");
}
//No beacon found for connection
if(i == ini.beacon_name.size())
return -1;
// Store peer id of the beacon node... for one time use!
pthread_mutex_lock(&g_mutex_sd2conn);
{
Connection* conn = new Connection(-1, false);
conn->peerid = make_hostid(beacon_name, beacon_port);
g_sd2conn[join_sock] = conn;
}
pthread_mutex_unlock(&g_mutex_sd2conn);
// Create, send and delete a JNRQ message
result = join_req(&request_hdr, (void **)&request_msg);
int send_err = send_msg(join_sock, request_hdr, request_msg);
// Log sent msg
if(send_err == 0) {
pthread_mutex_lock(&g_mutex_log_msg);
log_msg(g_log_file, request_hdr, request_msg, 's', join_sock);
pthread_mutex_unlock(&g_mutex_log_msg);
}
delete request_hdr;
delete request_msg;
request_hdr = NULL;
request_msg = NULL;
// Wait "join time out" for Join_res messages
alarm(ini.jointo);
while(1) {
struct timeval time;
time.tv_sec = 1;
time.tv_usec = 0;
fd_set rset;
FD_ZERO(&rset);
FD_SET(join_sock, &rset);
result = 0;
// Waiting for a packet
while(!result) {
fd_set rset0 = rset;
timeval time0 = time;
result = select(join_sock + 1, &rset0, NULL, NULL, &time0);
if(g_flag == 1) {
break;
}
}
if(g_flag == 1) {
g_flag = 0;
break;
}
// Receive Join_res message
result = recv_msg(join_sock, &reply_hdr, (void **)&reply_msg);
if(result == 0) {
//Store the beacon info in g_neighbor_list
g_neighbor_list.add_node(reply_msg);
num_neighbors++;
// log JNRS msg
pthread_mutex_lock(&g_mutex_log_msg);
log_msg(g_log_file, reply_hdr, reply_msg, 'r', join_sock);
pthread_mutex_unlock(&g_mutex_log_msg);
delete reply_hdr;
delete reply_msg;
reply_hdr = NULL;
reply_msg = NULL;
}
}
// Delete peer id of the beacon node.
pthread_mutex_lock(&g_mutex_sd2conn);
{
Connection* conn = g_sd2conn[join_sock];
delete conn;
g_sd2conn.erase(join_sock);
}
pthread_mutex_unlock(&g_mutex_sd2conn);
// Delete nodes except closest ones.
result = g_neighbor_list.prune(ini.initneighbor);
if(DEBUG) printf("Num of init neighbors: %d\n", result);
// print of file: init_neighbor_list
g_neighbor_list.write_file();
// Close socket
close(join_sock);
return 0;
} // end of explore_neighbors()
// function printUsageAndExit
// Print commandline usage info.
// arguments
// none
//
void print_usage_and_exit() {
printf("Usage: sv_node [-reset] xxx.ini\n");
printf("where xxx is the name of the initialization file\n");
exit(1);
}
// function read_command_line
// read command line options
// arguments
// argc: from command line
// argv: from command line
//
void read_command_line(int argc, char *argv[]) {
// valid range of argc is 2 ~ 3
// ex) sv_node -reset startup.ini
if (argc == 1 || argc > 3) {
print_usage_and_exit();
}
g_reset = false;
// Walk through options
for(int i = 1; i < argc - 1; i++) {
if(argv[i][0] == '-') {
if(strcmp(&argv[i][1], "reset") == 0) {
g_reset = true;
}
else {
print_usage_and_exit();
}
}
else {
print_usage_and_exit();
}
}
if(argv[argc-1][0] == '-') {
print_usage_and_exit();
}
} // end of read_command_line()
// start_connection
// Spawn read_th, write_th.
//
int start_connection(int sock_fd, int is_beacon)
{
pthread_t r_thread, w_thread;
// Create connection info
Connection *con = new Connection(-1, is_beacon);
if(con == NULL) {
//printf("Memory Allocation Failure\n");
exit(1);
}
// Lock mutex before spawning reading/writing thread.
pthread_mutex_lock(&g_mutex_sd2conn);
{
// Create read thread
pthread_create(&r_thread, NULL, read_th, &sock_fd);
con->rth = r_thread;
// Create write thread
pthread_create(&w_thread, NULL, write_th, &sock_fd);
con->wth = w_thread;
// Add it to the map
g_sd2conn[sock_fd] = con;
}
pthread_mutex_unlock(&g_mutex_sd2conn);
return 0;
} // end of start_connection()
void* server_thread(void* arg)
{
struct sockaddr_in my_addr;
struct sockaddr_in client_addr;
int yes = 1;
int sockfd, new_fd;
my_addr.sin_family = AF_INET;
my_addr.sin_port = ini.port;
inet_aton((const char *)gethostbyname(ini.hostname), &(my_addr.sin_addr));
memset(my_addr.sin_zero, '\0', sizeof(my_addr.sin_zero));
// Create listening socket
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket()");
printf("Please Try again\n");
exit(1);
}
// Set socket
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
perror("setsockopt()");
printf("Please Try again\n");
exit(1);
}
// Bind
if(bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr))) {
perror("Bind()");
printf("Please Try again\n");
exit(1);
}
// Listen
if (listen(sockfd, BACKLOG) == -1) {
perror("listen()");
printf("Please Try again\n");
exit(1);
}
// Accept
while(1) {
socklen_t sin_size = sizeof(client_addr);
new_fd = accept(sockfd, (struct sockaddr *)&client_addr, &sin_size);
if (new_fd == -1) {
//perror(" server_thread(): Can't/Doesn't accept()");
return NULL; //@
}
else if(g_time2die > -1) { //@
//close(new_fd); // Don't reply. Let the peer give up.
continue;
}
if(DEBUG) printf("server_thread(): Client accepted.\n");
if(DEBUG) printf("server_thread(): Calling start-connection().\n");
// Spawn read/write thrread.
start_connection(new_fd, -1);
if(DEBUG) printf("server_thread(): Exiting start-connection().\n");
pthread_mutex_lock(&g_mutex_curr_neighbor); //@
g_curr_neighbor++;
pthread_mutex_unlock(&g_mutex_curr_neighbor);
}
return NULL;
} // end of server_thread()
void beacon_connect()
{
struct sockaddr_in my_addr;
unsigned int i;
int sockfd;
hostent *h;
my_addr.sin_family = AF_INET;
bool double_conn_closed = false;
// Set all beacon status to OFF
pthread_mutex_lock(&g_mutex_beacon_status);
{
for(i = 0; i< ini.beacon_name.size(); i++) {
g_beacon_status.push_back(0);
}
}
pthread_mutex_unlock(&g_mutex_beacon_status);
while(1) {
for(i = 0; i< ini.beacon_name.size(); i++) {
if(g_time2die > -1) {
return;
}
string peerid = "";
peerid += ini.beacon_name[i];
peerid += "_";
stringstream out_stream;
out_stream << ini.beacon_port[i];
string s_temp = out_stream.str();
peerid += s_temp;
// if beacon is connected, it's OK.
pthread_mutex_lock(&g_mutex_beacon_status);
if(g_beacon_status[i] == 1) {
pthread_mutex_unlock(&g_mutex_beacon_status);
continue;
}
pthread_mutex_unlock(&g_mutex_beacon_status);
// if I'm the beacon, set it to 'connected'
if(strcmp(ini.hostname, ini.beacon_name[i].c_str()) == 0) {
if(ini.port == ini.beacon_port[i]) {
pthread_mutex_lock(&g_mutex_beacon_status);
g_beacon_status[i] = 1;
pthread_mutex_unlock(&g_mutex_beacon_status);
continue;
}
}
//pthread_mutex_unlock(&g_mutex_beacon_status); // ??????
// It's a beacon not connected
my_addr.sin_port = ini.beacon_port[i];
const char *buffer = ini.beacon_name[i].c_str();
if((h = gethostbyname(buffer)) == NULL) {
//perror("Address Request");
continue;
}
memcpy(&my_addr.sin_addr, h->h_addr, h->h_length);
//inet_aton((const char *)gethostbyname(ini.beacon_name[i].c_str()), &(my_addr.sin_addr));
memset(my_addr.sin_zero, '\0', sizeof(my_addr.sin_zero));
// Create a socket
if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
perror("beacon-connect():socket()");
exit(1);
}
// Connect to the beacon
if(connect(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)) == -1) {
//perror("beacon-connect():connect()");
fflush(stdout);
pthread_mutex_lock(&g_mutex_beacon_status);
g_beacon_status[i] = 0;
pthread_mutex_unlock(&g_mutex_beacon_status);
continue;
//exit(1);
}
// Set it 'connected'
pthread_mutex_lock(&g_mutex_beacon_status);
g_beacon_status[i] = 1;
pthread_mutex_unlock(&g_mutex_beacon_status);
// Spawn read/write thrread.
if(DEBUG) printf("beacon-connect(): Calling start-connection().\n");
start_connection(sockfd, i);
if(DEBUG) printf("beacon-connect(): Exiting start-connection().\n");
// Set peer id
pthread_mutex_lock(&g_mutex_sd2conn);
{
std::map<int, Connection* >::iterator itr = g_sd2conn.find(sockfd);
if(itr == g_sd2conn.end()) {
pthread_mutex_unlock(&g_mutex_sd2conn);
continue;
}
Connection *conn = g_sd2conn[sockfd];
conn->peerid = peerid;
}
pthread_mutex_unlock(&g_mutex_sd2conn);
// Post a HELLO msg.
post_hello(sockfd);
pthread_mutex_lock(&g_mutex_hostid2sd);
map<string, int>::iterator itr = g_hostid2sd.find(peerid);
pthread_mutex_unlock(&g_mutex_hostid2sd);
if(itr != g_hostid2sd.end()) {
if(sockfd != itr->second) {
//printf("Double Connection found !!\n");
if(ini.port > ini.beacon_port[i]) {
//printf("The connection initiated by me wins\n");
close(itr->second);
pthread_mutex_lock(&g_mutex_hostid2sd);
itr->second = sockfd;
pthread_mutex_unlock(&g_mutex_hostid2sd);
}
else if(ini.port < ini.beacon_port[i]) {
//printf("The connection initiated by the peer wins\n");
close(sockfd);
}
else {
if((strcmp(ini.hostname, ini.beacon_name[i].c_str())) > 0) {
//printf("The connection initiated by me wins ... though the port is same\n");
close(itr->second);
pthread_mutex_lock(&g_mutex_hostid2sd);
itr->second = sockfd;
pthread_mutex_unlock(&g_mutex_hostid2sd);
}
else {
//printf("The connection initiated by the peer wins ... though the port is same\n");
close(sockfd);
}
}
double_conn_closed = true;
}
/*
// if double connection deleted,
// Delete an entry in sd2conn map
if(double_conn_closed) {
pthread_mutex_lock(&g_mutex_sd2conn);
g_sd2conn.erase(sockfd);
pthread_mutex_unlock(&g_mutex_sd2conn);
double_conn_closed = false;
}
*/
}
else {
pthread_mutex_lock(&(g_mutex_hostid2sd));
g_hostid2sd[peerid] = sockfd;
pthread_mutex_unlock(&(g_mutex_hostid2sd));
}
}
//sleep(1);
timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
select(0, NULL, NULL, NULL, &tv);
}
return;
} // end of beacon-connect()
int nonbeacon_connect()
{
struct sockaddr_in my_addr;
int sockfd;
hostent *h;
my_addr.sin_family = AF_INET;
pthread_mutex_lock(&g_mutex_curr_neighbor);
g_curr_neighbor = 0;
pthread_mutex_unlock(&g_mutex_curr_neighbor);
list<Node_info>::iterator it;
unsigned int i = 0;
for(it = g_neighbor_list.nodes.begin(); it != g_neighbor_list.nodes.end(); it++, i++) {
string peerid = "";
peerid += it->host_name;
peerid += "_";
stringstream out_stream;
out_stream << it->port;
string s_temp = out_stream.str();
peerid += s_temp;
my_addr.sin_port = it->port;
const char *buffer = it->host_name.c_str();
//printf("Hostname trying to connect is %s\n", buffer);
if((h = gethostbyname(buffer)) == NULL) {
//perror("Address Request");
continue;
}
memcpy(&my_addr.sin_addr, h->h_addr, h->h_length);
memset(my_addr.sin_zero, '\0', sizeof(my_addr.sin_zero));
// Create a socket
if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
perror("ERR nonbeacon-connect():socket()");
exit(1);
}
// Connect to the neighbouring node
if(connect(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)) == -1) {
//perror("ERR nonbeacon-connect():connect()");
fflush(stdout);
continue;
//exit(1);
}
// Spawn read/write thrread.
start_connection(sockfd, -1); //-1 for not beacon
pthread_mutex_lock(&g_mutex_curr_neighbor);
g_curr_neighbor++;
pthread_mutex_unlock(&g_mutex_curr_neighbor);
pthread_mutex_lock(&g_mutex_hostid2sd);
{
g_hostid2sd[peerid] = sockfd;
}
pthread_mutex_unlock(&g_mutex_hostid2sd);
pthread_mutex_lock(&g_mutex_sd2conn);
{
Connection *conn = g_sd2conn[sockfd];
conn->peerid = peerid;
}
pthread_mutex_unlock(&g_mutex_sd2conn);
// Post a HELLO msg.
post_hello(sockfd);
}
pthread_mutex_lock(&g_mutex_curr_neighbor);
if(g_curr_neighbor < ini.minneighbor) {
pthread_mutex_unlock(&g_mutex_curr_neighbor);
return -1;
}
pthread_mutex_unlock(&g_mutex_curr_neighbor);
return 0; //0 is for sucess and that we have more than min neighbors connected to us.
} // end of non-beacon-connect()
void beacon_main()
{
pthread_t se_th;
pthread_t dis_thread;
// Create dispatch thread
pthread_create(&dis_thread, NULL, dispatch_th, NULL);
if(DEBUG) printf("dispatch thread created.\n");
// Create server thread
pthread_create(&se_th, NULL, server_thread, NULL);
if(DEBUG) printf("server thread created ..................\n");
beacon_connect();
return;
} // end of beacon_main()
void kill_this_node(char err_code) {
g_time2die = err_code;
if(DEBUG_KILL) {
//printf("0. kill_this_node():err_code = %x\n", err_code);
fflush(stdout);
}
pthread_mutex_lock(&g_mutex_sd2conn);
void* thread_ret;
std::map<int, Connection* >::iterator iter;
if(DEBUG_KILL) printf("1. ");
for(iter = g_sd2conn.begin(); iter != g_sd2conn.end(); iter++) {
if(DEBUG_KILL) printf("1.1 ");
pthread_cond_broadcast(&(iter->second->cv));
pthread_mutex_unlock(&g_mutex_sd2conn);
if(DEBUG_KILL) printf("1.1 ");
pthread_join(iter->second->wth, &thread_ret);
if(DEBUG_KILL) printf("1.1 ");
pthread_mutex_lock(&g_mutex_sd2conn);
}
if(DEBUG_KILL) printf("2. ");
pthread_mutex_unlock(&g_mutex_sd2conn);
g_indice.write_index_file();
g_lru.write_lru_file();
write_fileid_index_file(g_fileid2fileno, ini.homedir, g_fileno, g_temp_fileno);
write_fileno2perm_index_file(g_fileno2perm, ini.homedir);
} // end of kill_this_node
void* sig_handler( void *)
{
sigset_t signal_set;
int sig;
//printf("Is sig handler created\n");
while(1) {
sigfillset( &signal_set);
sigwait( &signal_set, &sig);
switch(sig) {
case SIGALRM:
//traves the peerid2sockfd map
//and send notify to all and shutdown the connection
//printf("Auto shutdown time expired ... Sending NTFY msg to all peers\n");
g_flag = 1;
//**
//kill_this_node(1);
//exit(1);
break;
case SIGQUIT:
//exit_now = TRUE;
//return NULL;
////break;
case SIGINT:
//printf("Did I catch the sigint\n");
short_circuit = 1;
//break;
case SIGTRAP:
short_circuit = 1;
pthread_cond_signal(&g_cond_cmd_que);
}
}
return NULL;
} // end of sig_handler()
void * auto_shutdown(void *)
{
struct timeval tv;
tv.tv_sec = ini.autoshutdown;
tv.tv_usec = 0;
select(0, NULL, NULL, NULL, &tv);
kill_this_node(1);
exit(1);
return NULL;
}
void * cmd_status_neighbor(void *)
{
Event e1;
map<int, int> nodes_done;
map<int, int>::iterator itr;
Status_res *msg;
nodes_done[ini.port] = 1;
if(DEBUG_CMD_WR) printf("*** 0. \n");
while(1) {
if(DEBUG_CMD_WR) printf("*** 1. \n");
pthread_mutex_lock(&(g_mutex_cmd_que));
while(g_cmd_que.size() == 0) {
if(short_circuit == 1) {
if(DEBUG_CMD_WR) printf("*** 1.1 \n");
pthread_mutex_unlock(&(g_mutex_cmd_que));
//Please remove the UOID from the map so that no other packets can on the queue
pthread_mutex_lock(&g_mutex_suoid2sd);
pthread_mutex_unlock(&g_mutex_suoid2sd);
return NULL;
}
if(DEBUG_CMD_WR) printf("*** 1.2 \n");
pthread_cond_wait(&g_cond_cmd_que, &g_mutex_cmd_que);
}
if(DEBUG_CMD_WR) printf("*** 1.3 \n");
e1 = g_cmd_que.front();
g_cmd_que.pop();
pthread_mutex_unlock(&(g_mutex_cmd_que));
if(e1.hdr->msg_type != STRS)
continue;
if(short_circuit == 1) {
//Remove the entry from the map
return NULL;
}
if(DEBUG_CMD_WR) printf("*pthread_mutex_lock(&g_mutex_suoid2sd);** 2. \n");
msg = (Status_res *)e1.vmsg;
uint32_t temp,record_len, i = 0;
uint16_t stemp, port;
memcpy(&temp, msg->data, 4);
record_len = ntohl(temp);
//printf("The record length = %d\n", record_len);
i=4;
if(DEBUG_CMD_WR) printf("*** 3. \n");
while(record_len != 0) {
memcpy(&stemp, msg->data + i, 2);
//printf("Port in netowrk order %d\n" ,stemp);
if(DEBUG_CMD_WR) printf("*** 3.1 \n");
port = ntohs(stemp);
//printf("Neighbouring node = %d\n", port);
itr = nodes_done.find(port);
if(itr == nodes_done.end()) {
nodes_done[port] = 1;