-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgNormalNode.java
More file actions
1129 lines (959 loc) · 44.3 KB
/
ProgNormalNode.java
File metadata and controls
1129 lines (959 loc) · 44.3 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
// NORMAL SLOT NODE - PAP 20160529
import daj.Message;
import daj.Program;
import java.util.*;
public class ProgNormalNode extends Program {
public static final int STS_ACTIVE = 1;
public static final int STS_RUNNING = 2;
public static final int STS_WAIT_STATUS = 3;
public static final int STS_WAIT_INIT = 4;
public static final int STS_DISCONNECTED = 5;
public static final int STS_REQ_SLOTS = 6;
public static final int STS_NEW = 7;
public static final int STS_MERGE_STATUS = 8;
public static final int NO_PRIMARY_MBR = -1;
public static final int MIN_OWNED_SLOTS = 16;
public static final int FREE_SLOTS_LOW = 8;
public static final int SLOTS_BY_MSG = 1024;
public static final int MAX_NEW_PROCS = 1;
public static final int MEDIAN_CHANGE_INTERVAL = 5000;
public static final int LT_UNIT = 45;
public static final int LT_MIN = 1;
public static final int LT_MAX = 100;
public static final int FI_MAX= 10;
public static final int FI_MIN = 1;
public static final int FI_RANGE = 4;
public static final int FI_MIN_AVG = 5;
public static final int FI_MAX_AVG = 10;
// public static final int MIN_OWNED_SLOTS = 4;
// public static final int FREE_SLOTS_LOW = 2;
// public static final int SLOTS_BY_MSG = 3;
private final Random random;
private int arrivalMedian;
private int nextMedianChange;
private Slot[] slotsTable = new Slot[SlotsDonation.TOTAL_SLOTS];
// private Process[] processTable = new Process[SlotsDonation.TOTAL_SLOTS];
private boolean[] activeNodes = new boolean[SlotsDonation.MAX_NODES+1];
private boolean[] initializedNodes = new boolean[SlotsDonation.MAX_NODES+1];
private boolean[] donorsNodes = new boolean[SlotsDonation.MAX_NODES+1];
private boolean[] bmPendingNodes = new boolean[SlotsDonation.MAX_NODES+1];
private boolean[] bmWaitSts = new boolean[SlotsDonation.MAX_NODES+1];
private final int nodeId;
private int state = STS_DISCONNECTED;
private int primaryMember;
private int maxOwnedSlots = SlotsDonation.TOTAL_SLOTS;
private boolean sysBarrier = false;
private boolean pendingConnect = false;
private boolean gotAtLeastOne = false;
private int counterForksSucceded = 0;
private int counterForksFailed = 0;
private int counterExits = 0;
private int counterConnects = 0;
private int counterDisconnects = 0;
private int counterRequestedSlots = 0;
private int counterGotSlots = 0;
private int counterDonatedSlots = 0;
private int counterGotZeroSlots = 0;
private int[] counterGotFirstSlotAt = new int[SlotsDonation.MAX_NODES-1];
private int counterAtMessage = 0;
private int timeLeftToFork;
public ProgNormalNode(int id) {
this.random = new Random();
this.nodeId = id;
for(int i = 0; i < SlotsDonation.TOTAL_SLOTS; i++) {
slotsTable[i] = new Slot(0, Slot.STATUS_FREE, 0);
}
this.cleanNodesLists();
}
@Override
public void main() {
int number;
//number = this.random.nextInt(SlotsDonation.MAX_NODES);
number = this.nodeId * 10;
println("Sleeping: "+number);
sleep(number);
this.nextMedianChange = MEDIAN_CHANGE_INTERVAL;
this.arrivalMedian = this.getNextArrivalMedian();
this.timeLeftToFork = getTime()+this.getNextDeltaFork();
this.doConnect();
// Start with algorithm
this.slotsLoop();
}
public void getInfoLine() {
//(NodeId, Forks OK, Forks Failed, Exits, TotalRequested, TotalReceived, GotZero)
System.out.println(""+this.nodeId+','+this.counterForksSucceded+','+
this.counterForksFailed+','+this.counterExits+','+this.counterRequestedSlots+
','+this.counterGotSlots+','+this.counterGotZeroSlots);
}
private void handleSpreadDisconnect(SpreadMessageLeave msg) {
this.println("Handling Spread Leave");
/* Clear those INITIALIZED members until SYS_PUT_STATUS arrives */
/* because the primary member will send a new SYS_PUT_STATUS */
if(this.state == STS_WAIT_STATUS) {
for(int i = 1; i <= SlotsDonation.MAX_NODES; i++) {
this.initializedNodes[i] = false;
}
return;
}
int disc_mbr = msg.getSenderId();
this.activeNodes = this.cloneBitmapTable(msg.getRegisteredNodes());
if( disc_mbr == this.nodeId){ /* The own LEAVE message */
this.println("Received my own Leave message");
this.initGlobalVars();
this.state = STS_DISCONNECTED;
return;
}
/* if local_nodeid is not initialized and is the only surviving node , restart all*/
if(!this.isInitialized() && this.getActiveNodes() == 1) {
this.initGlobalVars();
this.doDisconnect();
this.doConnect();
return;
}
/* I am not initialized yet */
if( !this.isInitialized() && (this.state != STS_WAIT_INIT)) {
return;
}
/* mark node as not initialized */
this.initializedNodes[disc_mbr] = false;
/* verify if the local member is waiting a donation from the disconnected node */
this.donorsNodes[disc_mbr] = false;
/* Are there any pending ZERO reply for that dead node ? */
this.bmPendingNodes[disc_mbr] = false;
/* if the dead node was the primary_mbr, search another primary_mbr */
if( this.primaryMember == disc_mbr) {
/* Is the process waiting STS_MERGE_STATUS message from the dead primary_mbr? */
if(this.state == STS_MERGE_STATUS)
this.state = STS_RUNNING;
this.primaryMember = this.getPrimaryMember();
if( this.primaryMember == NO_PRIMARY_MBR) {
this.println("primary_mbr == NO_PRIMARY_MBR");
this.state = STS_NEW;
this.initGlobalVars();
this.doDisconnect();
this.doConnect();
return;
}
}
/* recalculate global variables */
this.maxOwnedSlots = (SlotsDonation.TOTAL_SLOTS -
(MIN_OWNED_SLOTS * (this.getInitializedNodes() - 1)));
this.println("max_owned_slots="+this.maxOwnedSlots);
/* reallocate slots of the disconnecter member to the primary member */
for(int i = 0; i < SlotsDonation.TOTAL_SLOTS; i++) {
if( this.slotsTable[i].getOwner() == disc_mbr ) {
/* an uncompleted donation */
if( this.slotsTable[i].getStatus() == Slot.STATUS_DONATING) {
/* local node was the donor */
this.slotsTable[i].setOwner(this.nodeId);
this.slotsTable[i].setStatus(Slot.STATUS_FREE);
} else {
if( this.primaryMember == this.nodeId &&
this.state == STS_REQ_SLOTS &&
this.getOwnedSlots() == 0) {
this.state = STS_RUNNING;
this.sysBarrier = true;
}
this.slotsTable[i].setOwner(this.primaryMember);
}
}
}
/*
* the disconnected member may be the previous primary_mbr
* if it leaves the group without finishing new nodes synchronization
* the new primary_mbr must do that operations.
*/
if( this.nodeId == this.primaryMember) {
//this.sendStatusInfo(); TODO: incomplete (we are not testing with disconnects)
}
}
private boolean amIsender(SpreadMessage msg) {
return msg.getSenderId() == this.nodeId;
}
/*===========================================================================*
* sp_join *
* A NEW member has joint the VM group but it is not initialized
*===========================================================================*/
private void handleSpreadJoin(SpreadMessageJoin msg) {
this.println("Handling Spread Join");
/* update registered nodes table */
this.activeNodes = this.cloneBitmapTable(msg.getActiveNodes());
if (this.getActiveNodes() < 0) {
return;
}
if( this.amIsender(msg)){ /* The own JOIN message */
this.println("Received my own Join message");
if (this.getActiveNodes() == 1) { /* It is a LONELY member*/
this.println("I'm the first active node");
/* it is ready to start running */
this.state = STS_RUNNING;
/* it is the Primary Member */
this.primaryMember = this.nodeId;
this.initializedNodes[this.nodeId] = true;
/* allocate all slots to the member */
for (int i = 0; i < SlotsDonation.TOTAL_SLOTS; i++) {
slotsTable[i].setOwner(this.nodeId);
slotsTable[i].setStatus(Slot.STATUS_FREE);
}
this.sysBarrier = true;
} else {
/* Waiting Global status info */
this.state = STS_WAIT_STATUS;
this.println("New Status: "+this.getStateAsString());
}
} else { /* Other node JOINs the group */
println("Other member joines the group: node#"+msg.getSenderId()+". My State="+this.getStateAsString());
/* I am not initialized yet */
if( (!this.isInitialized())) {
println("I'm not Inizialized nor waiting init. My State:" +this.getStateAsString());
return;
}
/* if the new member was previously considered as a member of other */
/* partition but really had crashed, allocate its slots to primary_mbr */
/* TODO!!! */
/* This node has sent an SYS_REQ_SLOTS messages, but before the other nodes */
/* (and itself) could receive slots donation, a VIEW CHANGE (JOIN) has occurred */
/* This means that the SYS_REQ_SLOTS message is not STABLE and it was discarded */
/* Therefore, if the local node hasn't got any owned slot, it must request again */
println("bm_donors="+Arrays.toString(this.donorsNodes)+
" bm_pending="+Arrays.toString(this.bmPendingNodes));
this.cleanBinaryList(this.donorsNodes);
this.cleanBinaryList(this.bmPendingNodes);
/* Sets the bm_waitsts bitmap to signal which new member need to get STATUS from PRIMARY */
println("member="+this.nodeId+" state="+STS_RUNNING);
if (this.state == STS_RUNNING ) {
if(this.primaryMember == this.nodeId) {
if (this.getWaitStsNodes() == 0) {
this.sendStatusInfo(msg.getSenderId());
}
}
this.bmWaitSts[msg.getSenderId()] = true;
}
}
}
/*======================================================================*
* sp_put_status *
* A new member has joined the group. *
* The Primary has broadcasted Global Status information *
*======================================================================*/
private void handleSlotsPutStatus(SlotsMessagePutStatus msg) {
this.println("Handling Slots Put Status from Node#"+msg.getSenderId()+" to Node#"+msg.getDestination());
int initMbr = msg.getDestination();
if(initMbr != this.nodeId) {
this.bmWaitSts[initMbr] = false;
println("init_mbr="+initMbr+" bm_waitsts="+Arrays.toString(this.bmWaitSts));
if(this.state == STS_RUNNING) {
if(this.primaryMember == this.nodeId) {
if (this.getWaitStsNodes() != 0) {
int next_wait = getNextWait(0);
if (next_wait != NO_PRIMARY_MBR) {
this.sendStatusInfo(next_wait);
}
}
}
} else if (this.getOwnedSlots() == 0 && this.countActive(this.donorsNodes) == 0) {
if (this.getWaitStsNodes() == 0) {
this.state = STS_REQ_SLOTS;
if(this.getInitializedNodes() > 1 )
this.mbrRqstSlots(MIN_OWNED_SLOTS);
}
} else {
return;
}
/* Is the new initialized member already considered as Initialized ? */
if(!this.isInitialized(initMbr)) { /* No, set the bitmap and count */
this.initializedNodes[initMbr] = true;
} else {
/* Here comes initialized members without owned slots after a NETWORK MERGE */
println("WARNING member "+initMbr+" just was initilized");
return;
}
println("init_mbr="+initMbr+" bm_init="+Arrays.toString(this.initializedNodes));
/* compute the slot high water threshold */
this.maxOwnedSlots = (SlotsDonation.TOTAL_SLOTS -
(MIN_OWNED_SLOTS * (this.getInitializedNodes() - 1)));
println("bm_init="+Arrays.toString(this.initializedNodes)+
" max_owned_slots="+this.maxOwnedSlots);
/* IMPLICIT SYS_REQ_SLOTS when JOIN->PUT_STATUS */
// PAP: CONSTRUIR UN MENSAJE con parametro initMbr como source
// y MIN_OWNED_SLOTS como getNeedSlots
// para poder invocar a la funcion.
SlotsMessageRequest newMsg = new SlotsMessageRequest(MIN_OWNED_SLOTS,
this.getFreeSlots(), this.getOwnedSlots(), initMbr);
this.handleSlotsRequest(newMsg);
return;
}
/*
* INIT_MBR is LOCAL NODE
*The init_mbr has receipt a SYS_PUT_STATUS message, therefore does not need anymore
*/
/* bm_init considerer the bitmap sent by primary_mbr ORed by */
/* the bitmap of those nodes initialized before SYS_PUT_STATUS message arrives */
boolean[] received = cloneBitmapTable(msg.getInitializedNodes());
this.println("Received init bitmap: "+Arrays.toString(received));
for(int i = 1; i <= SlotsDonation.MAX_NODES; i++) {
if(received[i] == true) {
this.initializedNodes[i] = true;
}
}
this.initializedNodes[this.nodeId] = true;
this.println("Updated Initialized nodes table with: "+Arrays.toString(this.initializedNodes));
/* Copy the received slot table to local table */
// ESTO ESTA BIEN??
this.slotsTable = this.cloneSlotTable(msg.getSlotsTable());
/* The member is initialized but it hasn't got slots to start running */
this.state = STS_REQ_SLOTS;
this.donorsNodes = cloneBitmapTable(this.initializedNodes);
this.donorsNodes[this.nodeId] = false;
this.println("Requesting slots");
/* IMPLICIT SYS_REQ_SLOTS when JOIN->PUT_STATUS */
}
/*---------------------------------------------------------------------
* sp_req_slots
* SYS_REQ_SLOTS: A Systask on other node has requested free slots
*---------------------------------------------------------------------*/
private void handleSlotsRequest(SlotsMessageRequest msg) {
int don_nodes, surplus;
double donated_slots;
int requester = msg.getSenderId();
println("Handling slot request from Node#"+requester);
/* the member is not initialized yet, then it can't respond to this request */
if( !(this.isInitialized())) {
println("Cannot donate, I am not initialized");
return;
}
/* Ignore owns requests */
if(requester == this.nodeId) {
println("Won't donate to myself. Ignoring...");
return;
}
/* Verify if the requester is initialized */
if( !(isInitialized(requester))) {
println("ERROR: member "+requester+ " was not initilized. Initialized nodes: "+Arrays.toString(this.initializedNodes));
return;
// println("HOTFIX: marking node#"+requester+" as initialized");
// this.initializedNodes[requester] = true;
}
/*
* ALL other initialized members respond to a request slot message
* but only members with enough slots will donate
*/
if( this.countActive(this.donorsNodes) != 0) {
/* If local node it is also a requester, then:
* consider the other requester as a PENDING donor which donates donated_slots = 0
* only if it has not replied yet.
* do not reply because the requester has already receipt my request
* if local node is the next member of the other requester, it must ALLWAYS reply
*/
if( (this.donorsNodes[requester] == true)
&& (this.getNextInit(requester) != this.nodeId)) {
println("concurrent request with: "+requester);
this.donorsNodes[requester] = false;
return;
}
donated_slots = 0;
}else{
don_nodes = this.getInitializedNodes() - 1;
assert( don_nodes > 0);
surplus = (this.getFreeSlots() - FREE_SLOTS_LOW);
println("free_slots:"+ this.getFreeSlots()+" free_slots_low:"+FREE_SLOTS_LOW
+" needed_slots:"+msg.getNeedSlots()+" don_nodes:"+don_nodes
+" surplus:"+surplus);
if( surplus <= 0) {
donated_slots = 0;
} else if( surplus > Math.ceil(msg.getNeedSlots()/(float)don_nodes)) { /* donate the slots requested */
donated_slots = Math.ceil(msg.getNeedSlots()/(float)don_nodes);
} else {
donated_slots = surplus;
}
// if( surplus > Math.ceil(msg.getNeedSlots()/(float)don_nodes)) { /* donate the slots requested */
// donated_slots = Math.ceil(msg.getNeedSlots()/(float)don_nodes);
// } else if( surplus > Math.ceil((FREE_SLOTS_LOW/(float)don_nodes))) {
// /* donate slots at least up to complete the minimal number of free slots */
// donated_slots = Math.ceil((FREE_SLOTS_LOW/(float)don_nodes));
// } else if( surplus > 0 ) { /* donate at least one */
// donated_slots = 1;
// } else {
// donated_slots = 0;
// }
}
/* if the local node does not have slots to donate and have no pending donation response to requester*/
/* it tries to reply later after receiving a donation message to the requester from other node */
/* WARNING: if any node has slots to donate, the requester will hang waiting for donations which */
/* never will come. To break this issue, the requester's next member always replies */
if (donated_slots == 0 && this.bmPendingNodes[requester] == false) {
/* next member always reply */
if(this.getNextInit(requester) != this.nodeId) {
this.bmPendingNodes[requester] = true;
this.println("Delaying reply to "+requester);
return;
}
this.println("I'm next member. Replying with zero slots to Node#"+ requester);
}
/* Maximum number of slots that can be donated by message round - Limited by the message structure */
if(donated_slots > SLOTS_BY_MSG) {
donated_slots = SLOTS_BY_MSG;
}
/* build the list of donated slots */
int[] donatedSlotsList = new int[(int)donated_slots];
for(int r = 0; r < donated_slots; r++) {
donatedSlotsList[r] = 0;
}
int j = 0;
if( donated_slots > 0) {
/* Search free owned slots */
for(int i = 0; (i < SlotsDonation.TOTAL_SLOTS) && (donated_slots > 0) ;i++) {
if( (slotsTable[i].isFree()) && (slotsTable[i].getOwner() == this.nodeId)) {
donated_slots--;
slotsTable[i].setOwner(requester);
slotsTable[i].setStatus(Slot.STATUS_DONATING);
donatedSlotsList[j] = i;
j++;
}
}
}
this.println("Donated_slots:"+donatedSlotsList.length+" requester:"+requester +" List: "+Arrays.toString(donatedSlotsList));
SlotsMessageDonate donMsg = new SlotsMessageDonate(
msg.getSenderId(), donatedSlotsList.clone(), this.nodeId);
this.counterDonatedSlots = donatedSlotsList.length + this.counterDonatedSlots;
broadcast(donMsg);
}
/*----------------------------------------------------------------------------------------------------
* sp_don_slots
* SYS_DON_SLOTS: A Donation Message has received
* If it is the destination systask, it adds the new free slots to its own
* or if they are for other node register the new ownership
*----------------------------------------------------------------------------------------------------*/
private void handleSlotsDonation(SlotsMessageDonate msg) {
this.println("Handling Slots Donate from Node#"+msg.getSenderId());
this.println("Donation of "+msg.getDonatedIdList().length+" slots from "
+msg.getSenderId()
+" to "+msg.getRequester());
/* Is the destination an initialized member ? */
if(!this.isInitialized(msg.getRequester())) {
println("WARNING Destination member node#"+msg.getRequester()
+" is not initialized");
return;
}
/* Is the donor an initialized member ? */
if(!this.isInitialized(msg.getSenderId())) {
println("WARNING Source member node#"+msg.getSenderId()+
" is not initialized");
return;
}
int[] donatedList = msg.getDonatedIdList().clone();
/* this is for me */
if( this.state == STS_REQ_SLOTS && donatedList.length > 0
&& msg.getRequester() == this.nodeId) {
this.state = STS_RUNNING;
if( this.getOwnedSlots() == 0){ /* a new member without slots */
this.println("Wake up fork/exit");
this.sysBarrier = true; /* Wakeup SYSTASK */
}
}
/* Change the owner of the donated slots */
for( int j = 0; j < donatedList.length; j++) {
int slotId = donatedList[j];
this.slotsTable[slotId].setOwner(msg.getRequester());
this.slotsTable[slotId].setStatus(Slot.STATUS_FREE);
if(msg.getRequester() == this.nodeId){
this.counterGotSlots++;
if(!this.gotAtLeastOne) {
this.gotAtLeastOne = true;
this.counterGotFirstSlotAt[this.counterAtMessage]++;
}
}
}
if(!(this.isInitialized())) {
println("I am not initialized nor waiting initialization. Return.");
return;
}
if(msg.getRequester() == this.nodeId){
this.counterAtMessage++;
}
/* If the slots are for other node, returns */
if(msg.getRequester() != this.nodeId){
if(this.bmPendingNodes[msg.getRequester()] == true) {
this.println("Delayed reply to Node#"+msg.getRequester());
int[] donatedSlotsList = new int[0];
SlotsMessageDonate donMsg = new SlotsMessageDonate(
msg.getRequester(), donatedSlotsList.clone(), this.nodeId);
broadcast(donMsg);
this.bmPendingNodes[msg.getRequester()] = false;
}
return;
}
// if( spin_ptr->mA_dst != local_nodeid) {
// rcode = OK;
// /* Are there any pending reply with ZERO slots for this destination ?*/
// if( TEST_BIT(bm_pending, spin_ptr->mA_dst)) {
// donated_slots = 0;
// requester = spin_ptr->mA_dst;
// TASKDEBUG("procs=%d donated_slots=%d requester=%d\n",
// (vm_ptr->vm_nr_tasks + vm_ptr->vm_nr_procs),donated_slots, requester);
// spout_ptr->m_source = local_nodeid;
// spout_ptr->m_type = SYS_DON_SLOTS;
// spout_ptr->mA_dst = requester;
// spout_ptr->mA_nr = donated_slots;
// for ( j = 0 ; j < SLOTS_BY_MSG; j++) spout_ptr->mA_ia[j] = 0;
// rcode = SP_multicast (sysmbox, SAFE_MESS, (char *) vm_ptr->vm_name,
// SYS_DON_SLOTS, sizeof(message), (char *) spout_ptr);
// CLR_BIT(bm_pending, spin_ptr->mA_dst);
// }
// return(rcode);
// }
this.donorsNodes[msg.getSenderId()] = false;
this.println("free_slots:"+this.getFreeSlots()+" free_slots_low:"
+FREE_SLOTS_LOW);
this.println("owned_slots:"+this.getOwnedSlots()+" max_owned_slots:"
+this.maxOwnedSlots+" bm_donors:"+ Arrays.toString(donorsNodes));
if( this.state == STS_REQ_SLOTS && this.countActive(this.donorsNodes) == 0
&& this.getOwnedSlots() == 0) {
mbrRqstSlots(MIN_OWNED_SLOTS);
}
if (this.countActive(this.donorsNodes) == 0 && this.gotAtLeastOne == false) {
this.counterGotZeroSlots++;
this.println("Got Zero Slots:"+counterGotZeroSlots);
}
}
private void handleSlotsMergeStatus(SlotsMessageMergeStatus msg) {
this.println("Handling Slots Merge Status (TODO)");
}
private void sendStatusInfo(int destId) {
/* Build Global Status Information (VM + bm_init + Shared slot table */
/* Send the Global status info to new members */
SlotsMessagePutStatus msg = new SlotsMessagePutStatus(
this.cloneSlotTable(this.slotsTable), cloneBitmapTable(this.initializedNodes), this.nodeId, destId);
this.println("Broadcasting Global status from Node#"+this.nodeId+"to Node#"+destId);
this.broadcast(msg);
}
/*===========================================================================*
* mbr_rqst_slots
* It builds and broadcasts a message requesting slots
*===========================================================================*/
private void mbrRqstSlots(int nr_slots) {
this.println("Sending request of slots: " + nr_slots);
/* set donors*/
this.donorsNodes = cloneBitmapTable(this.initializedNodes);
this.donorsNodes[this.nodeId] = false;
if(this.countActive(this.donorsNodes) == 0) {
return;
}
SlotsMessageRequest msg = new SlotsMessageRequest(nr_slots,
this.getFreeSlots(), this.getOwnedSlots(), this.nodeId);
this.counterRequestedSlots = nr_slots + this.counterRequestedSlots;
this.gotAtLeastOne = false;
this.counterAtMessage = 0;
this.broadcast(msg);
}
/****************
* AUXILIARY
****************/
/**
* Broadcasting a message is sending it to the spread node
* @param msg
*/
public void broadcast(Message msg) {
out(0).send(msg);
}
private void slotsLoop() {
Message msg;
int mbr;
while(true) {
// this.println("Waiting for message...");
msg = this.in(0).receive(1);
if (msg != null) {
if(msg instanceof SpreadMessage) {
if(msg instanceof SpreadMessageJoin) {
this.handleSpreadJoin((SpreadMessageJoin)msg);
} else if (msg instanceof SpreadMessageLeave) {
this.handleSpreadDisconnect((SpreadMessageLeave)msg);
} else {
this.println("THIS SHOULD NOT HAPPEN!!! SpreadMessage non JOIN or LEAVE!");
}
} else if (this.isConnected()) {
if(msg instanceof SlotsMessageRequest) {
this.handleSlotsRequest((SlotsMessageRequest)msg);
} else if (msg instanceof SlotsMessageDonate) {
this.handleSlotsDonation((SlotsMessageDonate)msg);
} else if (msg instanceof SlotsMessagePutStatus) {
mbr = ((SlotsMessagePutStatus)msg).getSenderId();
if( !this.isInitialized()) {
this.primaryMember = mbr;
} else {
if(this.primaryMember != mbr) {
this.println("SYS_PUT_STATUS: current primary_mbr:"+
this.primaryMember+" differs from new primary_mbr:"+
mbr);
}
if(!this.isInitialized(mbr)) {
this.println("SYS_PUT_STATUS: primary_mbr:"+mbr+" is not in bm_init:"+Arrays.toString(this.initializedNodes));
}
}
this.handleSlotsPutStatus((SlotsMessagePutStatus)msg);
} else if (msg instanceof SlotsMessageMergeStatus) {
this.handleSlotsMergeStatus((SlotsMessageMergeStatus)msg);
} else {
this.println("UNHANDLED SLOT MESSAGE!!!");
}
} else {
this.println("Ignoring Slots Message. Node is not connected!");
}
}
//check fork or exit
this.processForkExit();
// test((GlobalAssertion)this.slotsAssertion);
}
}
@Override
public String getText() {
return "Node #" + nodeId + "\nStatus: "+ this.getStateAsString()
+"\nI own: "+ this.getOwnedSlots() + " ("+this.getFreeSlots()+
" free) slots\nmaxOwnedSlots: "+this.maxOwnedSlots+"\n"
+ "FSL: "+FREE_SLOTS_LOW+ "\nRegistered Nodes: "
+ Arrays.toString(this.activeNodes)+"\nInitialized Nodes: "
+ Arrays.toString(this.initializedNodes)+"\nDonor Nodes: "
+ Arrays.toString(this.donorsNodes)+"\nForks Succeded: "+this.counterForksSucceded
+"\nForks Failed: "+this.counterForksFailed
+"\nExits: "+this.counterExits+"\nConnects: "+this.counterConnects
+"\nDisconnects: "+this.counterDisconnects
+"\nRequested Slots: "+this.counterRequestedSlots
+"\nDonated To Me Slots: "+this.counterGotSlots
+"\nDonated By Me Slots: "+this.counterDonatedSlots
+"\nArrival Median: "+this.arrivalMedian
+"\nNext Fork: "+this.timeLeftToFork
+"\nCurrent Time: "+getTime();
}
public void println(String str) {
System.out.println("Node[" + nodeId + "]("+getTime()+"): "+str);
}
public void decProcessesLifetimes() {
int counter = 0;
for(int i = 0; i < SlotsDonation.TOTAL_SLOTS; i++) {
if(slotsTable[i].isUsed() && slotsTable[i].getOwner() == this.nodeId) {
if(slotsTable[i].processTimeLeft == 0) {
println("Killing process: "+i);
this.doExit(i);
counter++;
} else {
slotsTable[i].processTimeLeft--;
}
}
}
// if (counter > 0)
// this.println("Number of destroyed processes: " + counter);
// this.println("Process Table: "+Arrays.toString(this.processTable));
}
/** find first owned free slot and use it **/
private void markSlotUsed() {
for(int i = 0; i<SlotsDonation.TOTAL_SLOTS; i++) {
if(slotsTable[i].isFree() && slotsTable[i].getOwner() == this.nodeId) {
slotsTable[i].setStatus(Slot.STATUS_USED);
slotsTable[i].setProcessLifetime(this.getRandomProcessLifeTime());
println("Created a process["+i+"] of lifetime "+slotsTable[i].processTimeLeft);
return;
}
}
}
private int getPrimaryMember() {
for(int i = 1; i < SlotsDonation.NODES; i++ ) {
if (this.isInitialized(i)) {
println("bm_init:"+Arrays.toString(this.initializedNodes)
+" primary_mbr:"+i);
return i;
}
}
return NO_PRIMARY_MBR;
}
int getNextWait(int node) {
int i, wait_mbr;
// TASKDEBUG("node=%d\n", node);
wait_mbr = NO_PRIMARY_MBR;
// assert( node < drvs_ptr->d_nr_nodes);
if( this.getInitializedNodes() == 1) return(wait_mbr);
for(i = 1, wait_mbr = node; i < SlotsDonation.NODES; i++ ) {
wait_mbr = (wait_mbr + 1) % SlotsDonation.NODES;
if (this.bmWaitSts[wait_mbr]) {
println("next:"+wait_mbr);
return(wait_mbr);
}
}
return NO_PRIMARY_MBR;
}
int getNextInit(int node) {
int i, next_mbr;
// TASKDEBUG("node=%d\n", node);
next_mbr = NO_PRIMARY_MBR;
// assert( node < drvs_ptr->d_nr_nodes);
if( this.getInitializedNodes() == 1) return(next_mbr);
for(i = 1, next_mbr = node; i < SlotsDonation.NODES; i++ ) {
next_mbr = (next_mbr + 1) % SlotsDonation.NODES;
if (this.isInitialized(next_mbr)) {
println("next:"+next_mbr);
return(next_mbr);
}
}
return NO_PRIMARY_MBR;
}
private boolean isInitialized(int nodeId) {
return this.initializedNodes[nodeId];
}
public boolean isInitialized() {
return this.isInitialized(this.nodeId);
}
private String getStateAsString() {
switch(this.state) {
case STS_DISCONNECTED:
return "Disconnected";
case STS_ACTIVE:
return "Active";
case STS_RUNNING:
return "Running";
case STS_WAIT_STATUS:
return "Wait Status";
case STS_WAIT_INIT:
return "Wait Init";
case STS_REQ_SLOTS:
return "Requested Slots";
case STS_NEW:
return "New ??";
case STS_MERGE_STATUS:
return "Merge ??";
default:
return "Unknown Status: "+this.state;
}
}
private int countActive(boolean[] list) {
int counter = 0;
for(int i = 0; i < list.length; i++) {
if(list[i]) {
counter++;
}
}
return counter;
}
public int getFreeSlots() {
int counter = 0;
for(int i = 0; i<SlotsDonation.TOTAL_SLOTS; i++) {
if(slotsTable[i].isFree() && slotsTable[i].getOwner() == this.nodeId) {
counter++;
}
}
return counter;
}
public int getUsedSlots() {
int counter = 0;
for(int i = 0; i<SlotsDonation.TOTAL_SLOTS; i++) {
if(slotsTable[i].isUsed() && slotsTable[i].getOwner() == this.nodeId) {
counter++;
}
}
return counter;
}
public int getOwnedSlots() {
int counter = 0;
for(int i = 0; i<SlotsDonation.TOTAL_SLOTS; i++) {
if(slotsTable[i].getOwner() == this.nodeId) {
counter++;
}
}
return counter;
}
private void processForkExit() {
if(this.nextMedianChange == 0) {
this.arrivalMedian = this.getNextArrivalMedian();
this.nextMedianChange = MEDIAN_CHANGE_INTERVAL;
println("Changed fork arrival median to: "+ this.arrivalMedian);
} else {
this.nextMedianChange--;
}
if (this.timeLeftToFork <= getTime()) { // time for a new fork
this.timeLeftToFork = getTime()+this.getNextDeltaFork();
//println("Next fork in: "+this.timeLeftToFork);
if(this.isConnected() && this.isInitialized() && this.sysBarrier) {
this.tryFork();
}
}
if(this.isConnected() && this.isInitialized()) {
this.decProcessesLifetimes();
}
}
private boolean isConnected() {
return (this.activeNodes[this.nodeId]);
}
private void doConnect() {
println("Connecting...");
this.pendingConnect = true;
this.counterConnects++;
out(0).send(new SpreadMessageJoin(this.nodeId));
}
private void doDisconnect() {
println("Disconnecting...");
this.initGlobalVars();
this.state = STS_DISCONNECTED;
this.counterDisconnects++;
out(0).send(new SpreadMessageLeave(this.nodeId));
}
private int getActiveNodes() {
int counter = 0;
for(int i = 0; i <= SlotsDonation.MAX_NODES; i++) {
if(this.activeNodes[i] == true) {
counter++;
}
}
return counter;
}
private int getInitializedNodes() {
int counter = 0;
for(int i = 1; i <= SlotsDonation.MAX_NODES; i++) {
if(this.initializedNodes[i]) {
counter++;
}
}
return counter;
}
private int getWaitStsNodes() {
int counter = 0;
for(int i = 1; i <= SlotsDonation.MAX_NODES; i++) {
if(this.bmWaitSts[i]) {
counter++;
}
}
return counter;
}
private void initGlobalVars() {
this.state = STS_NEW;
this.primaryMember = NO_PRIMARY_MBR;
this.cleanNodesLists();
this.cleanSlotsLists();
this.cleanCounterGotFirstAt();
this.sysBarrier = false;
this.pendingConnect = false;
this.maxOwnedSlots = 0;
this.cleanBinaryList(this.bmWaitSts);
}
private void cleanBinaryList(boolean[] list) {
for(int i = 1; i < list.length; i++) {
list[i] = false;
}
}
private void cleanNodesLists() {
for(int i = 1; i <= SlotsDonation.MAX_NODES; i++) {
this.initializedNodes[i] = false;
this.activeNodes[i] = false;
this.donorsNodes[i] = false;
this.bmPendingNodes[i] = false;
}
}
private void cleanCounterGotFirstAt() {
for(int i = 0; i < SlotsDonation.MAX_NODES-1; i++) {
this.counterGotFirstSlotAt[i] = 0;
}
}