-
Notifications
You must be signed in to change notification settings - Fork 3
/
paxos.js
1351 lines (1194 loc) · 42 KB
/
paxos.js
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
/* jshint globalstrict: true */
/* jshint browser: true */
/* jshint devel: true */
/* jshint jquery: true */
/* global util */
'use strict';
var paxos = {};
(function () {
/* Begin paxos algorithm logic */
// Configure these variables to define the number of proposers, accepters
// and learners in the consensus.
paxos.NUM_CLIENTS = 1;
paxos.NUM_PROPOSERS = 2;
paxos.NUM_ACCEPTORS = 3;
paxos.NUM_LEARNERS = 1;
// Public Variable.
paxos.NUM_SERVERS = paxos.NUM_CLIENTS + paxos.NUM_PROPOSERS + paxos.NUM_ACCEPTORS + paxos.NUM_LEARNERS;
// Use these utils to identify server state.
const SERVER_STATE = {
CLIENT: 'client',
PROPOSER: 'proposer',
ACCEPTOR: 'acceptor',
LEARNER: 'learner',
UNKNOWN: 'unknown',
}
const MESSAGE_TYPE = {
CLIENT_RQ: 'client_request',
CLIENT_REPLY: 'client_reply',
PREPARE: 'prepare_msg',
PROMISE: 'promise_msg',
ACCEPT: 'accept_msg',
NACK: 'nack',
ACCEPTED: 'accepted_msg',
}
var messageTypeToText = function (type) {
switch (type) {
case MESSAGE_TYPE.CLIENT_RQ:
return "Client Request";
case MESSAGE_TYPE.CLIENT_REPLY:
return "Client Reply";
case MESSAGE_TYPE.PREPARE:
return "Prepare";
case MESSAGE_TYPE.PROMISE:
return "Promise";
case MESSAGE_TYPE.ACCEPT:
return "Accept";
case MESSAGE_TYPE.NACK:
return "Nack";
case MESSAGE_TYPE.ACCEPTED:
return "Accepted";
}
return "Unknown";
}
// Proposer specific phases.
const PROPOSER_PHASE = {
INACTIVE: 'inactive',
SEND_PREPARE: 'send_prepare',
WAIT_PROMISE: 'wait_promise',
WAIT_ACCEPTED: 'wait_accepted',
}
// Translate ID in range [1, NUM_SERVERS] to server state. Returns
// UNKNOWN if ID is out of bound.
var serverIdToState = function (id) {
if (id <= 0 || id > paxos.NUM_SERVERS) {
return SERVER_STATE.UNKNOWN;
}
if (id <= paxos.NUM_CLIENTS) {
return SERVER_STATE.CLIENT;
}
if (id <= paxos.NUM_CLIENTS + paxos.NUM_PROPOSERS) {
return SERVER_STATE.PROPOSER;
}
if (id <= paxos.NUM_CLIENTS + paxos.NUM_PROPOSERS + paxos.NUM_ACCEPTORS) {
return SERVER_STATE.ACCEPTOR;
}
return SERVER_STATE.LEARNER;
}
// Define color per server state. Returns 'black' for unknown state.
// (TODO: tune the colors to look smoother.)
var serverStateToColor = function (state) {
if (state === SERVER_STATE.CLIENT) {
return '#BBB5A4';
}
if (state === SERVER_STATE.PROPOSER) {
return '#AC8295';
}
if (state === SERVER_STATE.ACCEPTOR) {
return '#6c515a';
}
if (state === SERVER_STATE.LEARNER) {
return '#a393bf';
}
return 'black'; // UNKNOWN.
}
var serverIdToColor = function (id) {
return serverStateToColor(serverIdToState(id));
}
// Public API: server object.
paxos.server = function (id, peers) {
let serverAttrs = {
id: id,
state: serverIdToState(id), //some online searches say a server can take multiple states
peers: peers,
maxPropNum: 0, //this server promises to not allow proposals with proposalNum less than maxPropNum
// following variables show the currently accepted proposal num and value
acceptedProposalNum: -1, //initially -1. If this is -1 then nothing was ever accepted and thus the acceptedProposalVal is invalid
acceptedProposalVal: 'default', //can only use this value if acceptedProposalID !== 0
peers: peers,
term: 1,
log: [],
commitIndex: 0,
matchIndex: util.makeMap(peers, 0),
nextIndex: util.makeMap(peers, 1),
rpcDue: util.makeMap(peers, 0),
stopped: false,
};
// Proposer Specific Attributes.
if (serverAttrs.state === SERVER_STATE.PROPOSER) {
serverAttrs.phase = PROPOSER_PHASE.INACTIVE;
// For proposal value replacement.
serverAttrs.largestAcceptedTerm = -1;
// For WAIT_PROMISE phase.
serverAttrs.grantedPromises = 0;
// For WAIT_ACCEPTED phase.
serverAttrs.grantedAccepts = 0;
serverAttrs.grantedNacks = 0;
serverAttrs.proposeValue = null;
serverAttrs.timeoutClock = 0;
}
// Acceptor Specific Attributes.
if (serverAttrs.state === SERVER_STATE.ACCEPTOR) {
// Determine how to respond to promise messages.
serverAttrs.promisedTerm = -1;
// Take care of accept (phase 2) logic.
serverAttrs.hasAccepted = false;
serverAttrs.acceptedTerm = -1;
serverAttrs.acceptedValue = null;
serverAttrs.accValueLog = [];
}
// Learner Specific Attributes.
if (serverAttrs.state === SERVER_STATE.LEARNER) {
serverAttrs.voteLog = {};
serverAttrs.learnedValue = null;
serverAttrs.lrnValueLog = [];
}
return serverAttrs;
};
var MIN_RPC_LATENCY = 10000;
var MAX_RPC_LATENCY = 15000;
var sendMessageNormal = function (model, message) {
message.sendTime = model.time;
message.recvTime = model.time +
MIN_RPC_LATENCY +
Math.random() * (MAX_RPC_LATENCY - MIN_RPC_LATENCY);
model.messages.push(message);
}
var PROPOSER_TIMEOUT = 40000;
var MIN_LATENCY = 15000;
var liveLockDelay = 80000;
var sendMessageLocked = function (model, message) {
message.sendTime = model.time;
message.recvTime = model.time +
MIN_LATENCY +
Math.random() * 0.1 * MIN_LATENCY;
if (model.liveLock && message.type == MESSAGE_TYPE.PROMISE) {
message.recvTime += liveLockDelay;
}
model.messages.push(message);
};
var sendMessage = function (model, message) {
if (model.liveLock) {
sendMessageLocked(model, message);
} else {
sendMessageNormal(model, message);
}
};
var sendRequest = function (model, request) {
request.direction = 'request';
sendMessage(model, request);
};
var sendReply = function (model, request, reply) {
reply.from = request.to;
reply.to = request.from;
reply.direction = 'reply';
sendMessage(model, reply);
};
var logTerm = function (log, index) {
if (index < 1 || index > log.length) {
return 0;
} else {
return log[index - 1].term;
}
};
var rules = {};
paxos.rules = rules;
paxos.latestTerm = 0;
//send request from client to proposer
paxos.sendClientRequest = function (model, server, proposer) {
// Prompt proposer number.
let proposerNumber = window.prompt('Send to which proposer?', '1');
if (proposerNumber == null) return;
if (proposerNumber <= 0 || proposerNumber > paxos.NUM_PROPOSERS) {
window.alert("Invalid Proposer Number, should be between (0, " + paxos.NUM_PROPOSERS + "].");
return;
}
// Prompt proposing term.
let proposingTerm = window.prompt('Please give a term number:', paxos.latestTerm);
if (proposingTerm == null) return;
// Prompt proposing value.
let proposingValue = window.prompt('Please give a proposing value:', 'abc');
if (proposingValue == null) return;
// Ready to suggest next term to be latest term + 1.
if (parseInt(proposingTerm, 10) >= paxos.latestTerm) {
paxos.latestTerm = parseInt(proposingTerm, 10) + 1;
}
var group = util.groupServers(model);
var clientId = group[0][0].id;
var proposer = group[1][proposerNumber - 1];
sendRequest(model, {
from: clientId,
to: proposer.id,
type: MESSAGE_TYPE.CLIENT_RQ,
term: parseInt(proposingTerm),
value: proposingValue,
});
};
//send request from client to proposer
paxos.sendClientRequest2 = function (model, term, target, value) {
if (target <= 0 || target > paxos.NUM_PROPOSERS) {
window.alert("Invalid Proposer Number, should be between (0, " + paxos.NUM_PROPOSERS + "].");
return;
}
// Ready to suggest next term to be latest term + 1.
if (parseInt(term, 10) >= paxos.latestTerm) {
paxos.latestTerm = parseInt(term, 10) + 1;
}
var group = util.groupServers(model);
var clientId = group[0][0].id;
var proposer = group[1][target - 1];
sendRequest(model, {
from: clientId,
to: proposer.id,
type: MESSAGE_TYPE.CLIENT_RQ,
term: term,
value: value,
});
};
var handleMessage = function (model, server, message) {
if (server.stopped) {
return;
}
switch (serverIdToState(server.id)) {
case SERVER_STATE.PROPOSER:
handleMessageProposer(model, server, message);
break;
case SERVER_STATE.ACCEPTOR:
handleMessageAcceptor(model, server, message);
break;
case SERVER_STATE.LEARNER:
handleMessageLearner(model, server, message);
break;
default:
// Unknown.
break;
}
};
/* Start Paxos Proposer Implementation. */
var handleMessageProposer = function (model, server, message) {
// Initiate proposer to be active.
if (message.type == MESSAGE_TYPE.CLIENT_RQ) {
if (server.phase === PROPOSER_PHASE.INACTIVE) {
server.phase = PROPOSER_PHASE.SEND_PREPARE;
// Take proposing term and value from client request.
server.term = message.term;
server.proposeValue = message.value;
}
}
// Prepare sent, waiting on promise.
if (server.phase === PROPOSER_PHASE.WAIT_PROMISE) {
if (message.type === MESSAGE_TYPE.PROMISE) {
// Acceptor has previously accepted another value with a smaller
// term number. This proposer will try to propose for that value
// instead of its original value.
//
// The initial acceptor.promisedTerm is set to '-1' so this replacement
// is guaranteed to happen if there was a legit accepted value.
//
// For Acceptors, previouslyAcceptedTerm and previouslyAcceptedValue
// should be set/unset together.
if (message.previouslyAcceptedTerm > server.largestAcceptedTerm) {
server.largestAcceptedTerm = message.previouslyAcceptedTerm;
server.proposeValue = message.previouslyAcceptedValue;
}
server.grantedPromises += 1;
}
}
// Accept requests sent, waiting on replies.
if (server.phase === PROPOSER_PHASE.WAIT_ACCEPTED) {
if (message.type === MESSAGE_TYPE.ACCEPTED) {
// According to phase 2b on https://en.wikipedia.org/wiki/Paxos_(computer_science),
// ACCEPTED replies will only be sent if acceptor has truly accepted the request.
//
// To elaborate a bit further, if acceptor has previously promised another value with
// term greater than this proposer's term, it would simply ignore the accept request.
// Therefore, we can assume that upon receiving an ACCEPTED message, the proposer
// won't be participating in the algorithm further. We will increment an internal
// counter that is used only to reset this proposer.
server.grantedAccepts += 1;
}
if (message.type === MESSAGE_TYPE.NACK) {
server.grantedNacks += 1;
}
}
}
var resetProposer = function (server) {
server.phase = PROPOSER_PHASE.INACTIVE;
server.grantedPromises = 0;
server.grantedAccepts = 0;
server.grantedNacks = 0;
}
var shouldProposerRetry = function (model, server) {
return server.timeoutClock <= model.time || server.grantedNacks > paxos.NUM_ACCEPTORS / 2;
}
var handleProposerUpdate = function (model, server) {
// Prepare phase.
if (server.phase === PROPOSER_PHASE.SEND_PREPARE) {
server.peers.forEach(function (peer) {
if (serverIdToState(peer) !== SERVER_STATE.ACCEPTOR) {
return; // Only propose to acceptors.
}
sendRequest(model, {
from: server.id,
to: peer,
type: MESSAGE_TYPE.PREPARE,
term: server.term,
});
//for debugging livelock feature
//server.timeoutClock = PROPOSER_TIMEOUT + model.time;
});
server.phase = PROPOSER_PHASE.WAIT_PROMISE; // Enter next phase.
// Used to compare & choose the largest accepted value to
// propose instead in the next phase.
server.largestAcceptedTerm = -1;
return;
}
// Prepare -> accept phase transition check.
if (server.phase === PROPOSER_PHASE.WAIT_PROMISE) {
if (server.grantedPromises > paxos.NUM_ACCEPTORS / 2) {
// Server has quorum. First fire off the accept requests, then enter
// next phase to wait for accepted responses.
//
// The order of operation does not really matter here due to the
// fact that this method is executed each frame and race condition
// becomes impossible.
server.peers.forEach(function (peer) {
if (serverIdToState(peer) !== SERVER_STATE.ACCEPTOR) {
return;
}
sendRequest(model, {
from: server.id,
to: peer,
type: MESSAGE_TYPE.ACCEPT,
term: server.term,
value: server.proposeValue,
});
});
server.phase = PROPOSER_PHASE.WAIT_ACCEPTED;
server.timeoutClock = PROPOSER_TIMEOUT + model.time;
}
}
if (server.phase === PROPOSER_PHASE.WAIT_ACCEPTED) {//timed out
// Successful.
if (server.grantedAccepts > paxos.NUM_ACCEPTORS / 2) {
server.timeoutClock = model.time;
resetProposer(server);
return;
}
// Failure to complete WAIT_ACCEPTED phase. Retry.
if (shouldProposerRetry(model, server)) { // Returns to WAIT_PROMISE phase.
server.term += 2;
server.peers.forEach(function (peer) {
if (serverIdToState(peer) !== SERVER_STATE.ACCEPTOR) {
return; // Only propose to acceptors.
}
sendRequest(model, {
from: server.id,
to: peer,
type: MESSAGE_TYPE.PREPARE,
term: server.term,
});
});
// Reset counters.
server.grantedPromises = 0;
server.grantedAccepts = 0;
server.grantedNacks = 0;
//for debugging livelock feature
//server.timeoutClock = PROPOSER_TIMEOUT + model.time;
// Revert back to WAIT_PROMISE phase. Eliminate the timeout
// circle as proposers do not do that during WAIT_PROMISE.
server.phase = PROPOSER_PHASE.WAIT_PROMISE;
server.timeoutClock = model.time;
}
}
}
/* End proposer implementation. */
/* Start Paxos Acceptor Implementation */
var handlePrepareMessage = function (model, server, proposalMsg) {
// handes the PREPARE message that this (acceptor) server received from proposer
// term check
if (proposalMsg.term < server.promisedTerm) {
return;
}
// Promise to ignore other requests with term number smaller than this.
server.promisedTerm = proposalMsg.term;
let messageSpec = { type: MESSAGE_TYPE.PROMISE, term: server.promisedTerm };
// Fill in these if acceptor has accepted something before.
if (server.hasAccepted) {
messageSpec.previouslyAcceptedTerm = server.acceptedTerm;
messageSpec.previouslyAcceptedValue = server.acceptedValue;
}
// send reply (prepare reply = promise)
sendReply(model, proposalMsg, messageSpec);
}
var handleAcceptMessage = function (model, server, acceptMsg) {
// handes the ACCEPT message that this (acceptor) server received from proposer
// term check
if (acceptMsg.term < server.promisedTerm) {
// Send back NACK.
sendReply
(model, acceptMsg, {
type: MESSAGE_TYPE.NACK,
});
return;
}
// else we have accepted the value
server.hasAccepted = true;
// Register accepted term & value
// This line can be reached even if acceptor has accepted something in the past already.
server.acceptedTerm = acceptMsg.term;
server.acceptedValue = acceptMsg.value;
server.accValueLog.push(acceptMsg.value);
// send reply (accept reply = broadcast to all proposers and learners)
// look into the server's peers and ignore if they are acceptors
server.peers.forEach(function (peer) {
if (serverIdToState(peer) == SERVER_STATE.ACCEPTOR || serverIdToState(peer) == SERVER_STATE.CLIENT) {
return;
}
// Skip reply if peer proposer is not sender of accept request.
if (serverIdToState(peer) == SERVER_STATE.PROPOSER
&& peer !== acceptMsg.from) {
return;
}
// cant use sendReply because we have to send to learner also, thus sendMessage()
sendMessage(model, {
from: server.id,
to: peer,
direction: 'reply',
type: MESSAGE_TYPE.ACCEPTED,
term: server.acceptedTerm,
value: server.acceptedValue,
});
});
}
var handleMessageAcceptor = function (model, server, message) {
// proposal message from proposer
if (message.type == MESSAGE_TYPE.PREPARE) {
handlePrepareMessage(model, server, message);
}
if (message.type == MESSAGE_TYPE.ACCEPT) {
handleAcceptMessage(model, server, message);
}
}
/* End acceptor implementation. */
var handleMessageLearner = function (model, server, message) {
if (server.learnedValue !== null) {
return;
}
// Already decided one value in this round of Paxos.
if (message.type == MESSAGE_TYPE.ACCEPTED) {
var key = [message.term, message.value];
if (server.voteLog[key] == undefined) {
server.voteLog[key] = 1;
} else {
server.voteLog[key] += 1;
}
if (server.voteLog[key] > paxos.NUM_ACCEPTORS / 2) {
//majority of accepted message received.
server.learnedValue = message.value;
server.lrnValueLog.push(message.value);
server.term = message.term;
server.voteLog = {};
sendMessage(model, {
from: message.to,
to: util.groupServers(state.current)[0][0].id,
direction: 'reply',
type: MESSAGE_TYPE.CLIENT_REPLY,
value: server.learnedValue,
term: server.term,
});
}
}
}
//start of part (1/2) of automated livelock implementation
var livelockDelay = 80000;
var SecondMsgAt = util.Inf;//when to send second message
paxos.liveLockSenario = function (model) {
var group = util.groupServers(model);
//first message send
sendRequest(model, {
from: group[0][0].id,
to: group[1][0].id,
type: MESSAGE_TYPE.CLIENT_RQ,
term: 0,
value: 'abc',
});
SecondMsgAt = model.time + livelockDelay;
}
//end of part (1/2) of automated livelock implementation
//start of part (2/2) of automated livelock implementation
var livelockSenarioPartTwo = function (model) {
if (model.time >= SecondMsgAt) {
SecondMsgAt = util.Inf;
var group = util.groupServers(model);
//second message send
sendRequest(model, {
from: group[0][0].id,
to: group[1][1].id,
type: MESSAGE_TYPE.CLIENT_RQ,
term: 1,
value: 'def',
});
}
}
//end of part (2/2) of automated livelock implementation
// Public function.
paxos.update = function (model) {
livelockSenarioPartTwo(model);
model.servers.forEach(function (server) {
// Paxos.
switch (serverIdToState(server.id)) {
case SERVER_STATE.PROPOSER:
handleProposerUpdate(model, server);
break;
case SERVER_STATE.ACCEPTOR:
//handleAcceptorUpdate(model, server);
break;
case SERVER_STATE.LEARNER:
// handleLearnerUpdate(model, server);
break;
default:
// Unknown.
break;
}
});
var deliver = [];
var keep = [];
model.messages.forEach(function (message) {
if (message.recvTime <= model.time)
deliver.push(message);
else if (message.recvTime < util.Inf)
keep.push(message);
});
model.messages = keep;
deliver.forEach(function (message) {
model.servers.forEach(function (server) {
if (server.id == message.to) {
handleMessage(model, server, message);
}
});
});
};
// Public function.
paxos.stop = function (model, server) {
server.stopped = true;
};
// Public function.
paxos.resume = function (model, server) {
server.stopped = false;
};
// Public function.
paxos.resumeAll = function (model) {
model.servers.forEach(function (server) {
paxos.resume(model, server);
});
};
paxos.restart = function (model, server) {
paxos.stop(model, server);
paxos.resume(model, server);
};
paxos.drop = function (model, message) {
model.messages = model.messages.filter(function (m) {
return m !== message;
});
};
paxos.clientRequest = function (modal, server) {
if (server.state === SERVER_STATE.CLIENT) {
let term = parseInt(document.getElementById('client-term').value, 10);
if (isNaN(term)) {
window.alert("failed to send request: term number is invalid");
return;
}
let target = parseInt(document.getElementById('client-target').value, 10);
if (isNaN(target)) {
window.alert("failed to send request: target proposer number is invalid");
return;
}
let value = document.getElementById('client-value').value;
if (value == '') {
window.alert("failed to send request: value input required");
return;
}
paxos.sendClientRequest2(modal, term, target, value);
}
if (server.state == 'leader') {
server.log.push({
term: server.term,
value: 'v'
});
}
};
/* End paxos algorithm logic */
/* Begin paxos-specific visualization */
var ARC_WIDTH = 5;
var comma = ',';
var arcSpec = function (spec, fraction) {
var radius = spec.r + ARC_WIDTH / 2;
var end = util.circleCoord(fraction, spec.cx, spec.cy, radius);
var s = ['M', spec.cx, comma, spec.cy - radius];
if (fraction > 0.5) {
s.push('A', radius, comma, radius, '0 0,1', spec.cx, spec.cy + radius);
s.push('M', spec.cx, comma, spec.cy + radius);
}
s.push('A', radius, comma, radius, '0 0,1', end.x, end.y);
return s.join(' ');
};
var logsSpec = {
x: 800,
y: 25,
width: 250,
height: 200,
};
var ringSpec = {
cx: 500,
cy: 210,
r: 150,
};
var columnSpec = {
cx: 380,
cy: 160,
xGap: 160,
yGap: 100,
};
var serverSpec = function (id, model) {
/*var coord = util.verticalCoord(model.servers[id-1].state,util.serverIdtoNumInGroup(id,model),
columnSpec.xGap,columnSpec.yGap,columnSpec.cx,columnSpec.cy,
paxos.NUM_PROPOSERS,paxos.NUM_ACCEPTORS,paxos.NUM_LEARNERS);*/
var coord = util.paxosLayoutCoord((id - 2) / (paxos.NUM_SERVERS - paxos.NUM_CLIENTS), model.servers[id - 1].state,
ringSpec.cx, ringSpec.cy, ringSpec.r);
return {
cx: coord.x,
cy: coord.y,
r: 30,
};
};
var MESSAGE_RADIUS = 8;
var messageSpec = function (from, to, frac, model) {
var fromSpec = serverSpec(from, model);
var toSpec = serverSpec(to, model);
// adjust frac so you start and end at the edge of servers
var totalDist = Math.sqrt(Math.pow(toSpec.cx - fromSpec.cx, 2) +
Math.pow(toSpec.cy - fromSpec.cy, 2));
var travel = totalDist - fromSpec.r - toSpec.r;
frac = (fromSpec.r / totalDist) + frac * (travel / totalDist);
return {
cx: fromSpec.cx + (toSpec.cx - fromSpec.cx) * frac,
cy: fromSpec.cy + (toSpec.cy - fromSpec.cy) * frac,
r: MESSAGE_RADIUS,
};
};
var messageArrowSpec = function (from, to, frac, model) {
var fromSpec = serverSpec(from, model);
var toSpec = serverSpec(to, model);
// adjust frac so you start and end at the edge of servers
var totalDist = Math.sqrt(Math.pow(toSpec.cx - fromSpec.cx, 2) +
Math.pow(toSpec.cy - fromSpec.cy, 2));
var travel = totalDist - fromSpec.r - toSpec.r;
var fracS = ((fromSpec.r + MESSAGE_RADIUS) / totalDist) +
frac * (travel / totalDist);
var fracH = ((fromSpec.r + 2 * MESSAGE_RADIUS) / totalDist) +
frac * (travel / totalDist);
return [
'M', fromSpec.cx + (toSpec.cx - fromSpec.cx) * fracS, comma,
fromSpec.cy + (toSpec.cy - fromSpec.cy) * fracS,
'L', fromSpec.cx + (toSpec.cx - fromSpec.cx) * fracH, comma,
fromSpec.cy + (toSpec.cy - fromSpec.cy) * fracH,
].join(' ');
};
var serverActions = [
['stop', paxos.stop],
['resume', paxos.resume],
['restart', paxos.restart],
['time out', paxos.timeout],
['request', paxos.clientRequest],
];
var messageActions = [
['drop', paxos.drop],
];
// Public method but may be specific to paxos Only.
var fillClientModalBody = function (m, server, li) {
$('.modal-body', m)
.empty()
.append($('<dl class="dl-horizontal"></dl>')
.append(li('state', server.state))
.append('<dt>term</dt><input id="client-term" type="text" class="client-input"><br>') // Client term.
.append('<dt>proposer #</dt><input id="client-target" type="text" class="client-input"><br>') // Client target proposer.
.append('<dt>value</dt><input id="client-value" type="text" class="client-input"><br>') // Client target proposer.
)
document.getElementById('client-term').value = paxos.latestTerm; // default to next term.
document.getElementById('client-target').value = '1'; // default to first proposer.
document.getElementById('client-value').value = 'abc'; // default to a sample value.
}
var fillProposerModalBody = function (m, server, li) {
$('.modal-body', m)
.empty()
.append($('<dl class="dl-horizontal"></dl>')
.append(li('state', server.state))
.append(li('current term', server.term))
.append(li('proposing value', server.proposeValue))
);
}
var fillAcceptorModalBody = function (m, server, li) {
$('.modal-body', m)
.empty()
.append($('<dl class="dl-horizontal"></dl>')
.append(li('state', server.state))
.append(li('promised term', server.promisedTerm))
.append(li('accepted term', server.acceptedTerm))
.append(li('accpeted value', server.acceptedValue))
);
}
var fillLearnerModalBody = function (m, server, li) {
$('.modal-body', m)
.empty()
.append($('<dl class="dl-horizontal"></dl>')
.append(li('state', server.state))
.append(li('learned value', server.learnedValue))
);
}
var serverModal = function (model, server) {
var m = $('#modal-details');
$('.modal-title', m).text('Server ' + server.id);
$('.modal-dialog', m).removeClass('modal-sm').addClass('modal-lg');
var li = function (label, value) {
return '<dt>' + label + '</dt><dd>' + value + '</dd>';
};
var peerTable = $('<table></table>')
.addClass('table table-condensed')
.append($('<tr></tr>')
.append('<th>peer</th>')
.append('<th>next index</th>')
.append('<th>match index</th>')
.append('<th>RPC due</th>')
);
server.peers.forEach(function (peer) {
peerTable.append($('<tr></tr>')
.append('<td>S' + peer + '</td>')
.append('<td>' + server.nextIndex[peer] + '</td>')
.append('<td>' + server.matchIndex[peer] + '</td>')
.append('<td>' + util.relTime(server.rpcDue[peer], model.time) + '</td>')
);
});
if (server.state === SERVER_STATE.CLIENT) {
fillClientModalBody(m, server, li);
}
// Append Proposer specific states to server model menu.
if (server.state === SERVER_STATE.PROPOSER) {
fillProposerModalBody(m, server, li);
}
// Append Acceptor specific states.
if (server.state === SERVER_STATE.ACCEPTOR) {
fillAcceptorModalBody(m, server, li);
}
// Append Learner specific states.
if (server.state === SERVER_STATE.LEARNER) {
fillLearnerModalBody(m, server, li);
}
var footer = $('.modal-footer', m);
footer.empty();
serverActions.forEach(function (action) {
footer.append(util.button(action[0])
.click(function () {
state.fork();
action[1](model, server);
state.save();
render.update();
m.modal('hide');
}));
});
m.modal();
};
var fillClientRequestFields = function (message, fields, li) {
fields.append(li('propose term', message.term));
fields.append(li('propose value', message.value));
}
var fillPrepareMessageFields = function (message, fields, li) {
fields.append(li('term', message.term));
}
var fillPromiseMessageFields = function (message, fields, li) {
fields.append(li('term', message.term));
if (message.previouslyAcceptedTerm != null) {
fields.append(li('previous term', message.previouslyAcceptedTerm));
fields.append(li('previous value', message.previouslyAcceptedValue));
}
}
var fillAcceptMessageFields = function (message, fields, li) {
fields.append(li('propose term', message.term));
fields.append(li('propose value', message.value));
}
var fillAcceptedMessageFields = function (message, fields, li) {
fields.append(li('accpeted term', message.term));
fields.append(li('accpeted value', message.value));
}
var fillClientReplyFields = function (message, fields, li) {
fields.append(li('decided value', message.value));
fields.append(li('from term', message.term));
}
var messageModal = function (model, message) {
var m = $('#modal-details');
$('.modal-dialog', m).removeClass('modal-lg').addClass('modal-sm');
$('.modal-title', m).text(messageTypeToText(message.type));
var li = function (label, value) {
return '<dt>' + label + '</dt><dd>' + value + '</dd>';
};
var fields = $('<dl class="dl-horizontal"></dl>')
.append(li('from', serverIdToText(message.from)))
.append(li('to', serverIdToText(message.to)))
.append(li('sent', util.relTime(message.sendTime, model.time)))
.append(li('deliver', util.relTime(message.recvTime, model.time)));
switch (message.type) {
case MESSAGE_TYPE.CLIENT_RQ:
fillClientRequestFields(message, fields, li);
break;
case MESSAGE_TYPE.PREPARE:
fillPrepareMessageFields(message, fields, li);
break;
case MESSAGE_TYPE.PROMISE:
fillPromiseMessageFields(message, fields, li);
break;
case MESSAGE_TYPE.ACCEPT:
fillAcceptMessageFields(message, fields, li);
break;
case MESSAGE_TYPE.ACCEPTED:
fillAcceptedMessageFields(message, fields, li);
break;
case MESSAGE_TYPE.CLIENT_REPLY:
fillClientReplyFields(message, fields, li);
break;
}
$('.modal-body', m)
.empty()
.append(fields);
var footer = $('.modal-footer', m);
footer.empty();