forked from leileichrist/snapshot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocesses.cpp
More file actions
1278 lines (1131 loc) · 28.9 KB
/
processes.cpp
File metadata and controls
1278 lines (1131 loc) · 28.9 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 <iostream>
#include <map>
#include <vector>
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <netdb.h>
#include <ctype.h>
#include <arpa/inet.h>
#include <signal.h>
#include <thread> // std::this_thread::sleep_for
#include <chrono>
#include <algorithm> // std::max
#include <fstream>
#include <deque> // std::deque
#include <list> // std::list
#include "queue.h"
#include <signal.h>
#include <dirent.h>
#include <time.h>
#define price_per_widget 10
#define TOTAL_NUM_WIDGETS 1000
#define TOTAL_AMT_MONEY 10000
#define EMPTY "EMPTY"
#define FILE_NAME "snapshot_"
#define GLOBAL_STATES "globalState_"
#define PORT00 3490
#define BACKLOG 10
#define MAXDATASIZE 256 // max number of bytes we can get at once
using namespace std;
typedef struct mp1_process_t_
{
pid_t pid;
bool snapshot_initiator;
queue_t* event_queue;
queue_t* snapshot_queue;
long money;
long widgets;
unsigned int id;
unsigned int ltime;
unsigned int marker_received;
vector< unsigned int > * vtime ;
vector<struct receiver_t * > * myRecvWorkers;
int num_processes;
bool state_recorded;
bool isTakingSnapshot;
int snapshot_th;
char* filename;
pthread_mutex_t process_lock;
pthread_cond_t data_ready;
}mp1_process;
typedef struct channel_state_t
{
long money;
long widgets;
}channel_state;
typedef struct receiver_t
{
mp1_process* parent;
bool open_recording;
unsigned int parentID;
channel_state* cState;
pthread_t t_id;
unsigned int from_process;
char* listening_on_port;
char message_received[MAXDATASIZE];
}receiver;
vector<vector<string> > channels;
int send_message( int sender, unsigned int receiver, const char* msg);
void cast_marker(mp1_process* p)
{
char* mmsg;
char* vtimeStr;
for(int i=0; i<p->num_processes; i++ )
{
mmsg=NULL; vtimeStr=NULL;
if(i!=p->id)
{
p->ltime++;
(*p->vtime)[p->id]++;
for(int i=0; i<p->vtime->size(); i++ )
{
if(vtimeStr)
asprintf(&vtimeStr, "%s,%d", vtimeStr ,(*p->vtime)[i]);
else
asprintf(&vtimeStr, "%d" , (*p->vtime)[i]);
}
asprintf(&mmsg, "MARKER: seq-%d from-%u logical-%u vector-%s", p->snapshot_th+1, p->id, p->ltime, vtimeStr );
send_message(p->id, i, mmsg );
printf("Process#%d sent marker-%d to process#%d during %d-th snapshot \n", p->id, p->snapshot_th+1 ,i, p->snapshot_th+1 );
if(mmsg) free(mmsg);
if(vtimeStr) free(vtimeStr);
}
}
}
unsigned int update_logic_timeStamp(unsigned int curr, unsigned int received)
{
// printf("the origin logical time stamp is %d , and the received is %d\n", curr, received);
if(received>curr)
return received+1;
else
return curr+1;
}
void update_vector_timeStamp(vector<unsigned int >* curr, const vector<unsigned int >& received, int id )
{
(*curr)[id]++;
for(int i=0; i<curr->size(); i++)
{
if(i!=id)
{
(*curr)[i]=max((*curr)[i],received[i]);
}
}
}
void record_PState_to_file(const mp1_process* p)
{
char* state=NULL;
char* vState=NULL;
FILE* pFile;
for(int i=0; i<p->vtime->size(); i++ )
{
if(vState)
asprintf(&vState, "%s %d", vState ,(*p->vtime)[i]);
else
asprintf(&vState, " %d" , (*p->vtime)[i]);
}
asprintf(&state,"id %d : snapshot %d : logical %d : vector%s : money %ld : widgets %ld\n",
p->id, p->snapshot_th+1, p->ltime, vState, p->money, p->widgets );
pFile=fopen(p->filename, "a+");
fputs(state, pFile);
fclose(pFile);
if(state) free(state);
if(vState) free(vState);
return;
}
void record_CState_to_file(mp1_process* p, unsigned int from, unsigned int logical, char* vtime, bool empty )
{
char* state=NULL;
long m = (*p->myRecvWorkers)[from]->cState->money ;
long w = (*p->myRecvWorkers)[from]->cState->widgets ;
FILE* pFile=fopen(p->filename, "a+");
if(empty || (m==0 && w==0) )
{
asprintf(&state, "id %u : snapshot %d : logical %u : vector %s : message %u to %u : %s\n",
p->id, p->snapshot_th+1, logical, vtime, from , p->id , EMPTY );
}
else
{
asprintf(&state, "id %u : snapshot %d : logical %u : vector %s : message %u to %u : money %ld widgets %ld\n",
p->id, p->snapshot_th+1, logical, vtime, from, p->id, m, w);
}
fputs(state, pFile);
fclose(pFile);
if(state)
free(state);
}
void change_process_state(mp1_process* p, long money, long widgets)
{
p->widgets+=widgets;
p->money+=money;
}
void init_channels( vector<vector<string> > & channels )
{
// cout<< "channels has size "<<channels.size()<<" and size "<< channels[0].size()<<endl;
int s=0;
for(int i=0; i<channels.size(); i++)
for(int j=0; j<channels[0].size(); j++)
{
channels[i][j]=to_string(PORT00+s);
// cout<<"channels("<<i<<","<<j<<")="<< channels[i][j] <<endl;
s++;
}
}
void sigchld_handler(int s)
{
while(waitpid(-1, NULL, WNOHANG) > 0);
}
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
void get_vector_t(const char* vec, vector<unsigned int > & t )
{
char* str=NULL;
asprintf(&str, "%s", vec);
char * pch;
pch = strtok (str,",");
while (pch != NULL)
{
unsigned int x = atoi(pch);
t.push_back(x);
pch = strtok (NULL, ",");
}
}
void show_state(mp1_process* p)
{
char* vState=NULL;
for(int i=0; i<p->vtime->size(); i++ )
{
if(vState)
asprintf(&vState, "%s %d", vState ,(*p->vtime)[i]);
else
asprintf(&vState, " %d" , (*p->vtime)[i]);
}
printf("process#%d's current state: snapshot-%d logical-%d : vector%s money-%ld widgets-%ld\n",
p->id, p->snapshot_th , p->ltime, vState, p->money, p->widgets );
if(vState) free(vState);
return;
}
void taking_snapshot(mp1_process* p) //MARKER: seq-1 from-1 logical-1 vector-1,1,1,1
{
char* vtimeStr=NULL;
record_PState_to_file(p);
p->state_recorded=true;
//open all the incoming channels!
for(int i=0; i<p->num_processes; i++)
{
if((*p->myRecvWorkers)[i]->open_recording==false )
(*p->myRecvWorkers)[i]->open_recording=true;
}
printf("Process%d finishes recording its state and opening its incoming channels during %d'th snapshot \n",
p->id, p->snapshot_th+1);
//cast to all other processes!
cast_marker(p);
if(vtimeStr)
free(vtimeStr);
}
void process_message(mp1_process* p, const char* msg )
{
char* temp=NULL;
char* vec=NULL;
char* c;
unsigned int l;
unsigned int from;
unsigned int marker_seq;
vector< unsigned int > v;
long m,w;
asprintf(&temp, "%s", msg);
if(p->id==0)
//SEND_TO: p-0 money-100 widgets-10
//UPDATE: logical-1 vector-1,1,1,1 money-100 widgets-100
//MARKER: seq-1 from-1 logical-1 vector-1,1,1,1
if(strstr(temp, "SNAPSHOT"))
{
char* pos=NULL;
pos=strstr(temp, " ")+1;
int s_th=atoi(pos);
printf("%d'th snapshot request coming\n", s_th );
pos=NULL;
if(p->snapshot_th<s_th-1 || p->isTakingSnapshot )
{
//need to re-push snapshot onto the snapshot_queue !
printf("The %d'th snapshot has not finished! New snapshot should wait \n", p->snapshot_th+1 );
char* temp_=NULL;
asprintf(&temp_, "%s", temp);
queue_enqueue(p->snapshot_queue, temp_ );
return;
}
p->ltime++;
(*p->vtime)[p->id]++;
p->isTakingSnapshot=true;
printf("process# %d is initiating the %d-th snapshot.....\n", p->id, s_th );
taking_snapshot(p);
}
if(strstr(temp, "SEND_TO") )
{
char* del;
char* resMsg=NULL;
unsigned int to;
char* vtimeStr=NULL;
c=strtok(temp, " ");
while(c !=NULL)
{
if(strstr(c,"p"))
{
del=strstr(c,"-");
// printf("sendto process: %s\n", del+1 );
to=atoi(del+1);
}
else if(strstr(c, "money"))
{
del=strstr(c,"-");
// printf("money: %s\n", del+1 );
m=(long)(atoi(del+1));
}
else if(strstr(c, "widgets"))
{
del=strstr(c,"-");
// printf("widgets: %s\n", del+1 );
w=(long)(atoi(del+1));
}
else
{
// fprintf(stderr, "no match found!\n");
}
c=strtok(NULL, " ");
}
p->ltime++;
(*p->vtime)[p->id]++;
for(int i=0; i<p->vtime->size(); i++ )
{
if(vtimeStr)
asprintf(&vtimeStr, "%s,%d", vtimeStr ,(*p->vtime)[i]);
else
asprintf(&vtimeStr, "%d" , (*p->vtime)[i]);
}
asprintf(&resMsg, "UPDATE: from-%d logical-%u vector-%s money-%ld widgets-%ld",
p->id ,p->ltime, vtimeStr, m, w );
printf("process %d sends to process %d with the message: %s\n", p->id ,to ,resMsg);
send_message(p->id, to, resMsg);
change_process_state(p, (-1)*m, (-1)*w);
}
else if( strstr(temp, "UPDATE") ) // message formatted as "UPDATE: from-1 logical-1 vector-1,1,1,1 money-100 widgets-100"
{
char* del;
c=strtok(temp, " ");
char* channel_vtime=NULL;
while(c !=NULL)
{
if(strstr(c,"from"))
{
del=strstr(c,"-");
// printf("logical: %s\n", del+1 );
from=atoi(del+1);
}
else if(strstr(c,"logical"))
{
del=strstr(c,"-");
// printf("logical: %s\n", del+1 );
l=atoi(del+1);
}
else if(strstr(c, "vector"))
{
del=strstr(c,"-");
// printf("vector: %s\n", del+1 );
asprintf(&vec, "%s", del+1);
asprintf(&channel_vtime, "%s", del+1);
}
else if(strstr(c, "money"))
{
del=strstr(c,"-");
// printf("money: %s\n", del+1 );
m=(long)(atoi(del+1));
}
else if(strstr(c, "widgets"))
{
del=strstr(c,"-");
// printf("widgets: %s\n", del+1 );
w=(long)(atoi(del+1));
}
else
{
// fprintf(stderr, "no match found!\n");
}
c=strtok(NULL, " ");
}
get_vector_t(vec, v);
if((*p->myRecvWorkers)[from]->open_recording )
{
(*p->myRecvWorkers)[from]->cState->money+=m;
(*p->myRecvWorkers)[from]->cState->widgets+=w;
}
printf("Process#%d delivered %d's message: %s\n", p->id, from, msg );
p->ltime=update_logic_timeStamp(p->ltime, l );
update_vector_timeStamp(p->vtime, v, p->id);
change_process_state(p, m, w);
if(channel_vtime)
free(channel_vtime);
}
else if(strstr(temp, "MARKER")) //MARKER: seq-1 from-1 logical-1 vector-1,1,1,1
{
char* del;
char* marker_to_be_queued=NULL;
asprintf(&marker_to_be_queued, "%s", temp);
char* vtimeStr=NULL;
c=strtok(temp, " ");
while(c !=NULL)
{
if(strstr(c,"seq"))
{
del=strstr(c,"-");
// printf("sendto process: %s\n", del+1 );
marker_seq=atoi(del+1);
}
else if(strstr(c, "from"))
{
del=strstr(c,"-");
// printf("money: %s\n", del+1 );
from=atoi(del+1);
}
else if(strstr(c,"logical"))
{
del=strstr(c,"-");
// printf("logical: %s\n", del+1 );
l=atoi(del+1);
}
else if(strstr(c, "vector"))
{
del=strstr(c,"-");
// printf("vector: %s\n", del+1 );
asprintf(&vec, "%s", del+1);
}
c=strtok(NULL, " ");
}
get_vector_t(vec, v);
printf("Process#%d receives marker-%d from process#%d!\n", p->id, marker_seq, from);
if(marker_seq>p->snapshot_th+1)
{
printf("Process%d is not ready to deliver marker-%d yet!\n", p->id, marker_seq );
queue_enqueue(p->event_queue, marker_to_be_queued);
}
p->ltime=update_logic_timeStamp(p->ltime, l );
update_vector_timeStamp(p->vtime, v, p->id);
p->marker_received++;
if(p->state_recorded)
{
record_CState_to_file(p, from, l, vec, false);
}
else
{
p->isTakingSnapshot=true;
taking_snapshot(p);
record_CState_to_file(p, from, l, vec, true);
}
if(p->marker_received==p->num_processes-1)
{
p->marker_received=0;
p->state_recorded=false;
// close all incoming channels:
for(int i=0; i<p->num_processes; i++)
{
if((*p->myRecvWorkers)[i]->open_recording )
(*p->myRecvWorkers)[i]->open_recording=false;
(*p->myRecvWorkers)[i]->cState->money=0;
(*p->myRecvWorkers)[i]->cState->widgets=0;
}
p->isTakingSnapshot=false;
p->snapshot_th++;
printf("Process %d has received all the marker-%d's, finishing snapshot %d's cycle\n",
p->id, marker_seq, p->snapshot_th);
if(queue_size(p->snapshot_queue)>0)
{
queue_enqueue(p->event_queue, queue_dequeue(p->snapshot_queue));
}
}
}
if(temp)
free(temp);
}
static void* receiver_cb(void* arg)
{
receiver* worker=(receiver*)arg;
char* port_num=worker->listening_on_port;
int sockfd, new_fd, numbytes; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
struct sigaction sa;
int yes=1;
char s[INET6_ADDRSTRLEN];
int rv;
unsigned int parent_id=worker->parentID;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, port_num, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return NULL;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("server: socket");
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("server: bind");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "server: failed to bind\n");
return NULL;
}
freeaddrinfo(servinfo); // all done with this structure
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
struct sockaddr_in* IPV4addr = (struct sockaddr_in * )(p->ai_addr) ;
unsigned int des_port = IPV4addr->sin_port ;
// printf("process#%u is waiting for connections from process#%u on port %d \n", parent_id, worker->from_process, des_port );
while(1) { // main accept() loop
char* mesg_stored=NULL;
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1)
{
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
// printf("process#%u: channel C-%u%u established, and process#%u is ready to receive message from process#%u !\n",
// parent_id, worker->from_process, parent_id, parent_id, worker->from_process);
if ((numbytes = recv(new_fd, worker->message_received, MAXDATASIZE-1, 0)) == -1)
{
perror("recv");
exit(1);
}
worker->message_received[numbytes] = '\0';
asprintf(&mesg_stored, "%s", worker->message_received);
bzero(worker->message_received, MAXDATASIZE);
// if(parent_id==0)
// printf(" via C%d%d: process#%d received msg: %s , ready to enter critical section \n",
// worker->from_process , parent_id ,parent_id ,mesg_stored);
pthread_mutex_lock(&worker->parent->process_lock );
// if(parent_id==0)
// printf("process#%d with msg: %s is in critical section! Ready to enqueue the message \n", parent_id ,mesg_stored);
queue_enqueue(worker->parent->event_queue, (void*)mesg_stored );
pthread_cond_signal(&worker->parent->data_ready);
pthread_mutex_unlock(&worker->parent->process_lock );
mesg_stored=NULL;
close(new_fd); // parent doesn't need this
}
return NULL;
}
int send_message( int sender, unsigned int receiver, const char* buf)
{
char* msg=NULL;
char* port;
if(!buf)
{
fprintf(stderr, "message is invalid!\n" );
return 1;
}
asprintf(&msg, "%s", buf);
if(sender<0) //the sender is the main parent process
{
port=(char*)channels[receiver][receiver].c_str();
sender=getpid();
}
else //the sender is the following child processes
{
port=(char*)channels[sender][receiver].c_str();
}
int sockfd, numbytes;
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
char* error_msg=NULL;
asprintf(&error_msg, "cannot establish channel from process %d to %d due to ", sender, receiver);
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo("localhost", port, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1)
{
fprintf(stderr, "%ssocket failure \n", error_msg);
// perror("client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
close(sockfd);
// perror("client: connect");
fprintf(stderr, "%sconnect failure \n", error_msg);
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "process %d failed to connect to process %d \n", sender, receiver);
return 2;
}
// struct sockaddr_in* IPV4addr = (struct sockaddr_in * )(p->ai_addr) ;
// unsigned int des_port = IPV4addr->sin_port ;
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
// printf("process#%d connecting to process#%d at %s on port %d \n", sender , receiver, s, des_port );
freeaddrinfo(servinfo); // all done with this structure
if (send(sockfd, msg, MAXDATASIZE, 0) == -1)
perror("send");
close(sockfd);
return 0;
}
void init_state(mp1_process* p)
{
p->money=TOTAL_AMT_MONEY/p->num_processes;
p->widgets=TOTAL_NUM_WIDGETS/p->num_processes;
}
void clear_process(mp1_process* p )
{
if(p->filename)
free(p->filename);
for(int i=0; i<p->myRecvWorkers->size(); i++)
{
if((*(p->myRecvWorkers))[i]->cState)
free((*(p->myRecvWorkers))[i]->cState);
free((*(p->myRecvWorkers))[i]);
}
if(p->event_queue)
{
queue_destroy(p->event_queue);
free(p->event_queue);
}
delete p->myRecvWorkers;
delete p->vtime ;
pthread_mutex_destroy(&p->process_lock);
pthread_cond_destroy(&p->data_ready);
}
void test_connection_channels(mp1_process* p)
{
std::chrono::milliseconds dura( 2000 );
std::this_thread::sleep_for( dura );
for(int i=0; i<p->num_processes;i++)
{
if(i!=p->id)
{
char* msg=NULL;
asprintf(&msg, "Hello, process#%d, I'm process#%d, nice to connect with you ! \n", i,p->id);
send_message( p->id , i , msg);
}
}
return;
}
void sender(unsigned int id, int num, pid_t pid)
{
mp1_process* process_mem=(mp1_process*)malloc(sizeof(mp1_process));
process_mem->event_queue=(queue_t*)malloc(sizeof(queue_t));
process_mem->snapshot_queue=(queue_t*)malloc(sizeof(queue_t));
queue_init(process_mem->snapshot_queue);
queue_init(process_mem->event_queue);
process_mem->id=id;
process_mem->pid=pid;
process_mem->ltime=0;
process_mem->num_processes=num;
process_mem->filename=NULL;
process_mem->snapshot_th=0;
process_mem->marker_received=0;
process_mem->isTakingSnapshot=false;
process_mem->state_recorded=false;
process_mem->myRecvWorkers=new vector<struct receiver_t* > ;
process_mem->vtime=new vector<unsigned int > ;
asprintf(&process_mem->filename, "snapshot_%d.txt",id);
for(int i=0; i<num; i++)
{
process_mem->vtime->push_back(0);
}
pthread_mutex_init(&process_mem->process_lock, NULL);
pthread_cond_init(&process_mem->data_ready,NULL);
if(id==0)
process_mem->snapshot_initiator=true;
else
process_mem->snapshot_initiator=false;
init_state( process_mem);
pthread_t* thread_id=(pthread_t*)malloc(sizeof(pthread_t)*num);
int j=0;
for(int otherid=0; otherid<num; otherid++ )
{
string port=channels[otherid][id];
receiver* recv_worker=(receiver*)malloc(sizeof(receiver));
recv_worker->parent=process_mem;
recv_worker->open_recording=false;
recv_worker->parentID = process_mem->id;
recv_worker->from_process=(unsigned int)otherid;
recv_worker->listening_on_port=(char*)port.c_str();
recv_worker->cState=(channel_state*)malloc(sizeof(channel_state));
recv_worker->cState->money=0;
recv_worker->cState->widgets=0;
process_mem->myRecvWorkers->push_back(recv_worker);
pthread_create(&thread_id[j++],NULL, receiver_cb ,(void*)recv_worker);
}
srand (time(NULL));
while(1)
{
int offset=0;
char* msg=NULL;
pthread_mutex_lock(&process_mem->process_lock);
while(queue_size(process_mem->event_queue)==0)
{
pthread_cond_wait(&process_mem->data_ready, &process_mem->process_lock );
}
msg=(char*)queue_dequeue(process_mem->event_queue);
offset = 100+rand()%300 ;
std::chrono::milliseconds dura( offset );
std::this_thread::sleep_for( dura );
process_message(process_mem ,msg);
pthread_mutex_unlock(&process_mem->process_lock);
// show_state(process_mem);
if(msg)
free(msg);
}
//test connection!
// test_connection_channels(process_mem );
for(int i=0; i<num; i++)
{
pthread_join(thread_id[i],NULL);
}
free(thread_id);
clear_process(process_mem);
free(process_mem);
}
bool isNum(char* m)
{
for(int i = 0; i < (strlen(m) - 1); i++)
{
if(!isdigit(m[i]))
return false;
}
return true;
}
void verify_condition(unsigned int num)
{
char* statefile=NULL;
char* line=NULL;
long m=0;
long w=0;
size_t len=0;
ssize_t read;
asprintf(&statefile, "%s%d.txt", GLOBAL_STATES, num);
FILE* pf=fopen(statefile, "r");
if(!pf)
{
fprintf(stderr, "%s does not exist!\n", statefile);
return;
}
while ((read = getline(&line, &len, pf)) != -1)
{
char* temp=NULL;
char* pch=NULL;
char* pre=NULL;
asprintf(&temp, "%s", line);
pch = strtok (temp," ");
while (pch != NULL)
{
if(strstr(pch, "widgets"))
asprintf(&pre, "%s", "widgets");
else if(strstr(pch, "money"))
asprintf(&pre, "%s", "money");
else
{
if(pre && strcmp(pre, "money")==0)
{
m+=atoi(pch);
free(pre);
pre=NULL;
}
else if(pre && strcmp(pre, "widgets")==0)
{
w+=atoi(pch);
free(pre);
pre=NULL;
}
}
pch = strtok (NULL, " ");
}
if(temp)
free(temp);
if(pre)
free(pre);
}
printf("At global state#%d: money sums up to %ld, and widgets sum up to %ld \n", num, m, w );
if(m==TOTAL_AMT_MONEY && w==TOTAL_NUM_WIDGETS )
printf("snapshot %d forms a consistent cut! \n", num);
else
printf("snapshot %d forms an inconsistent cut! \n", num);
if(statefile)
free(statefile);
fclose(pf);
}
void search_snapshot(unsigned int num, unsigned int num_processes)
{
char* filename=NULL;
char* gStateFile=NULL;
FILE* sFile=NULL;
asprintf(&gStateFile, "%s%d.txt", GLOBAL_STATES, num);
sFile=fopen(gStateFile, "a+");
for(int i=0; i<num_processes; i++)
{
asprintf(&filename, "%s%d.txt", FILE_NAME, i);
FILE* pFile;
char* line=NULL;
size_t len=0;
ssize_t read;
pFile=fopen(filename, "r");
if(pFile==NULL)
{
fprintf(stderr, "Error occurs when reading %s ! \n", filename);
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &len, pFile)) != -1)
{
// printf("%s", line);
char* temp=NULL;
char* pch;
asprintf(&temp, "%s", line);
if(strstr(line, "snapshot") ==NULL )
{
continue;
}
pch = strtok (temp,":");
while (pch != NULL)
{
char* x;
char* y;
if(strstr(pch, "snapshot") )
{
x=pch+(strlen(pch)-1);
y=pch+10;
(*x)=0;
if(atoi(y)==num)
{
printf("%s\n",line);
fputs(line, sFile);
}
break;
}
pch = strtok (NULL, ":");
}
if(temp)
free(temp);
}
if(line)
free(line);
fclose(pFile);
}
fclose(sFile);
}
void parse_search_check(const char* cmd, int num_processes)
{
char* temp=NULL;
int num;
asprintf(&temp, "%s", cmd);
char * pch;
pch = strtok (temp," ");
while (pch != NULL)
{
if(isNum(pch))
{
num=atoi(pch);
break;
}