-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.cc
870 lines (639 loc) · 21.9 KB
/
main.cc
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
#include <unistd.h>
#include <QVBoxLayout>
#include <QApplication>
#include <QDebug>
#include <QDateTime>
#include <random>
#include "main.hh"
enum node_status nodeStatus;
struct node_state nodeState;
struct leader_state leaderState;
ChatDialog::ChatDialog()
{
textview = new QTextEdit(this);
textview->setReadOnly(true);
textline = new QLineEdit(this);
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(textview);
layout->addWidget(textline);
setLayout(layout);
// Create a UDP network socket
socket = new NetSocket();
if (!socket->bind())
exit(1);
// Randomize local origin
// qsrand((uint) QDateTime::currentMSecsSinceEpoch());
//QString::number(qrand()) +
local_origin = socket->localPort();
setWindowTitle(local_origin);
qDebug() << "LOCAL ORIGIN: " << local_origin;
// set init currentTerm
nodeState.currentTerm = 0;
// set the nodes id
nodeState.id = local_origin;
// set waiting for a status to 0 (false) since instance just launched
nodeStatus = WAITING;
// last log applied to state
nodeState.lastApplied = 0;
// index of highest log entry known to be committed
nodeState.commitIndex = 0;
nodeState.nextPending = 0;
// set vote empty string
nodeState.votedFor = "";
// // Initialize timer for heartbeat timeout
heartbeatTimer = new QTimer(this);
connect(heartbeatTimer, SIGNAL(timeout()), this, SLOT(handleHeartbeatTimeout()));
electionTimeout = new QTimer(this);
connect(electionTimeout, SIGNAL(timeout()), this, SLOT(handleElectionTimeout()));
leaderTimeout = new QTimer(this);
connect(leaderTimeout , SIGNAL(timeout()), this, SLOT(handleLeaderTimeout()));
// socket->pingList = socket->PeerList();
// Register a callback on the textline's returnPressed signal
// so that we can send the message entered by the user.
connect(textline, SIGNAL(returnPressed()),
this, SLOT(gotReturnPressed()));
// Callback fired when message is received
connect(socket, SIGNAL(readyRead()), this, SLOT(readPendingMessages()));
}
void ChatDialog::readPendingMessages()
{
while (socket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize((int)socket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
socket->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
qDebug() << "RECEIVING MESSAGE";
processIncomingData(datagram, socket, senderPort);
}
}
void ChatDialog::processRequestVote(QMap<QString, QVariant> voteRequest, quint16 senderPort)
{
if (nodeStatus == LEADER) {
qDebug() << "Rejecting vote request";
return;
}
// If the logs have last entries with different terms,
// then the log with the later term is more up-to-date.
// If the logs end with the same term, then whichever log
// is longer is more up-to-date.
quint32 candidateTerm = voteRequest.value("term").toUInt();
quint32 candidateLastLogIndex = voteRequest.value("lastLogIndex").toUInt();
quint32 candidateLastLogTerm = voteRequest.value("lastLogTerm").toUInt();
quint32 localLastLogIndex = nodeState.lastApplied; // the last log index
quint32 localLastLogTerm = getLastTerm(); // the last log index
qDebug() << "Voted for: " << nodeState.votedFor;
qDebug() << "Candidate term: " << candidateTerm;
qDebug() << "Current term: " << nodeState.currentTerm;
qDebug() << "candidateLastLogTerm: " << candidateLastLogTerm;
qDebug() << "localLastLogTerm: " << localLastLogTerm;
if (candidateTerm > nodeState.currentTerm) {
if ((candidateLastLogTerm >= localLastLogTerm) && \
(candidateLastLogIndex >= localLastLogIndex)) {
qDebug() << "Vote granted";
nodeState.votedFor = voteRequest.value("candidateId").toString();
nodeState.currentTerm = candidateTerm;
sendVote(1, senderPort);
}
}
else if ((candidateTerm == nodeState.currentTerm) && (nodeState.votedFor != ""))
{
qDebug() << "terms equal, already voted";
sendVote(0, senderPort);
}
else if (candidateTerm < nodeState.currentTerm)
{
qDebug() << "terms less than local";
sendVote(0, senderPort);
}
// else if ((candidateLastLogTerm < localLastLogTerm) || \
// (nodeState.votedFor != ""))
// {
// sendVote(0, senderPort);
// }
else
{
sendVote(0, senderPort);
}
}
AppendEntryRPC::AppendEntryRPC() {
//Empty constructor
}
QByteArray AppendEntryRPC::serializeObject() {
QMap<QString, QMap<QString, QVariant>> messageToSend;
QMap<QString, QMap<QString, QMap<quint32, QMap<QString, QVariant>>>> entriesToSend;
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::ReadWrite);
messageToSend[APPEND_ENTRIES].insert("term", this->term);
messageToSend[APPEND_ENTRIES].insert("leaderId", this->leaderId);
messageToSend[APPEND_ENTRIES].insert("prevLogIndex", this->prevLogIndex);
messageToSend[APPEND_ENTRIES].insert("prevLogTerm", this->prevLogTerm);
messageToSend[APPEND_ENTRIES].insert("leaderCommit", this->leaderCommit);
stream << messageToSend;
if (this->entries.size() > 0) {
entriesToSend[APPEND_ENTRIES].insert("entries", this->entries);
stream << entriesToSend;
}
return buffer;
}
void AppendEntryRPC::deserializeStream(QByteArray receivedData) {
QMap<QString, QMap<QString, QVariant>> messageReceived;
QDataStream stream_msg(&receivedData, QIODevice::ReadWrite);
stream_msg >> messageReceived;
QMap<QString, QMap<QString, QMap<quint32, QMap<QString, QVariant>>>> appendEntryMessage;
QDataStream entries_msg(&receivedData, QIODevice::ReadWrite);
entries_msg >> appendEntryMessage;
this->term = messageReceived[APPEND_ENTRIES].value("term").toUInt();
this->leaderId = messageReceived[APPEND_ENTRIES].value("leaderId").toString();
this->prevLogIndex = messageReceived[APPEND_ENTRIES].value("prevLogIndex").toUInt();
this->prevLogTerm = messageReceived[APPEND_ENTRIES].value("prevLogTerm").toUInt();
this->leaderCommit = messageReceived[APPEND_ENTRIES].value("leaderCommit").toUInt();
if (appendEntryMessage[APPEND_ENTRIES].value("entries").size() > 0) {
this->entries = appendEntryMessage[APPEND_ENTRIES].value("entries");
}
}
void ChatDialog::sendVote(quint8 vote, quint16 senderPort)
{
QMap<QString, QMap<QString, QVariant>> voteToSend;
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::ReadWrite);
voteToSend[VOTE_REPLY].insert("vote", vote);
stream << voteToSend;
sendMessage(buffer, senderPort);
}
void ChatDialog::processAppendEntries(AppendEntryRPC appendEntry, quint16 senderPort)
{
quint32 rcvTerm = appendEntry.term;
QString rcvId = appendEntry.leaderId;
quint32 rcvPrevLogIndex = appendEntry.prevLogIndex;
quint32 rcvPrevLogTerm = appendEntry.prevLogTerm;
quint32 rcvCommitIndex = appendEntry.leaderCommit;
QMap <quint32, QMap<QString, QVariant>> entries = appendEntry.entries;
// build response from append entries
QMap<QString, QMap<QString, QVariant>> ackToSend;
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::ReadWrite);
if (nodeStatus == FOLLOWER) {
heartbeatTimer->stop();
heartbeatTimer->start(generateRandomTimeRange(5000, 6000));
nodeState.currentTerm = rcvTerm;
nodeState.leaderPort = senderPort;
}
if ((nodeStatus == CANDIDATE) || (nodeStatus == LEADER))
{
// you recognize the leader and return to follower state because you're weak
if (nodeStatus == CANDIDATE) {
electionTimeout->stop();
}
else if (nodeStatus == LEADER) {
leaderTimeout->stop();
}
nodeStatus = FOLLOWER;
heartbeatTimer->start(generateRandomTimeRange(5000, 6000));
nodeState.currentTerm = rcvTerm;
nodeState.leaderPort = senderPort;
}
if (rcvTerm < nodeState.currentTerm)
{
// reply false -> leader update its currenterm to
// rcv term and set itself to follower
sendAckToLeader(0, senderPort);
return;
}
if (nodeState.logEntries.contains(rcvPrevLogIndex))
{
QMap<QString, QVariant> localEntry;
localEntry = nodeState.logEntries[rcvPrevLogIndex];
if (rcvPrevLogTerm != localEntry["term"])
{
// reply false
sendAckToLeader(0, senderPort);
for (quint32 i = rcvPrevLogIndex; i <= nodeState.lastApplied; i++) {
nodeState.logEntries.remove(i);
}
nodeState.lastApplied = rcvPrevLogIndex-1;
return;
}
else
{
if (!entries.isEmpty()){
for (int e = 0; e < entries.size(); e++){
for (auto index : entries.keys()) {
nodeState.logEntries[index] = entries[index];
}
}
sendAckToLeader(1, senderPort);
}
}
}
if (rcvCommitIndex > nodeState.commitIndex)
{
nodeState.commitIndex = std::max(nodeState.lastApplied, rcvCommitIndex);
}
}
void ChatDialog::sendAckToLeader(quint8 success, quint16 senderPort)
{
// build response from append entries
QMap<QString, QMap<QString, QVariant>> ackToSend;
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::ReadWrite);
ackToSend[ACK].insert("originid", nodeState.id);
ackToSend[ACK].insert("term", nodeState.currentTerm);
ackToSend[ACK].insert("success", success);
stream << ackToSend;
sendMessage(buffer, senderPort);
}
// Process the message read from pending messages from sock
void ChatDialog::processIncomingData(QByteArray datagramReceived, NetSocket *socket, quint16 senderPort)
{
if (nodeStatus == WAITING)
{
qDebug() << "In WAITING state, return";
return;
}
QMap<QString, QMap<QString, QVariant>> messageReceived;
QDataStream stream_msg(&datagramReceived, QIODevice::ReadWrite);
stream_msg >> messageReceived;
qDebug() << "Data received: " << messageReceived;
if (messageReceived.contains(REQUEST_VOTE))
{
qDebug() << "MESSAGE CONTAINS REQUEST_VOTE";
processRequestVote(messageReceived.value(REQUEST_VOTE), senderPort);
}
else if (messageReceived.contains(APPEND_ENTRIES))
{
qDebug() << "MESSAGE CONTAINS APPEND_ENTRIES";
AppendEntryRPC appendEntries;
appendEntries.deserializeStream(datagramReceived);
processAppendEntries(appendEntries, senderPort);
}
else if (messageReceived.contains(VOTE_REPLY))
{
qDebug() << "MESSAGE CONTAINS VOTE_REPLY";
addVoteCount((quint8)messageReceived[VOTE_REPLY]["vote"].toUInt());
}
else if (messageReceived.contains(ACK))
{
processACK(messageReceived.value(ACK), senderPort);
}
else if (messageReceived.contains(MSG_ACK))
{
addMsgVoteCount(
(quint8)messageReceived[MSG_ACK]["success"].toUInt(),
messageReceived[MSG_ACK].value("msgorigin").toString()
);
}
else if (messageReceived.contains(MSG))
{
qDebug() << "Recieved message: " << messageReceived.value(MSG);
if (nodeStatus == LEADER) {
QString msgOrigin = messageReceived[MSG].value("origin").toString();
QString msgRcvd = messageReceived[MSG].value("msg").toString();
QMap<QString, QVariant> msgToAppend;
msgToAppend.insert("origin", msgOrigin);
msgToAppend.insert("msg", msgRcvd);
if (nodeState.messageList.size() == 0) {
nodeState.messageList.append(msgToAppend);
}
else {
nodeState.messageList[nodeState.nextPending] = msgToAppend;
}
qDebug() << "Added to message list";
nodeState.nextPending++;
QMap<QString, QMap<QString, QVariant>> messageToSend;
messageToSend.insert(MSG, messageReceived.value(MSG));
qDebug() << "Adding to stream";
QList<quint16> peerList = socket->PeerList();
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::ReadWrite);
stream << messageToSend;
numberOfMsgVotes = 0;
qDebug() << "Replicating message: " << messageReceived.value(MSG);
for (int p = 0; p < peerList.size(); p++) {
if(peerList[p] != senderPort) {
sendMessage(buffer, peerList[p]);
}
}
}
else if ((nodeStatus == FOLLOWER) || (nodeStatus == CANDIDATE)) {
QString origin = messageReceived[MSG].value("origin").toString();
sendMsgACK(senderPort, origin);
}
}
else {
qDebug() << "Unsupported message RPC type";
}
}
void ChatDialog::processACK(QMap<QString, QVariant> ack, quint16 senderPort)
{
quint32 rcvAckTerm = ack.value("term").toUInt();
quint32 rcvAckSuccess = ack.value("success").toUInt();
// • If command received from client: append entry to local log, respond after entry applied to state machine (§5.3)
// • If last log index ≥ nextIndex for a follower: send AppendEntries RPC with log entries starting at nextIndex
// • If successful: update nextIndex and matchIndex for
// follower (§5.3)
// • If AppendEntries fails because of log inconsistency:
// decrement nextIndex and retry (§5.3)
// • If there exists an N such that N > commitIndex, a majority
// of matchIndex[i] ≥ N, and log[N].term == currentTerm: set commitIndex = N (§5.3, §5.4).
QString candidateId = ack.value("candidateId").toString();
quint32 candidateNextIndex = leaderState.nextIndex.value(candidateId).toUInt();
if ((rcvAckTerm > nodeState.currentTerm) && (rcvAckSuccess == 0))
{
// BECOME follower
nodeStatus = FOLLOWER;
nodeState.currentTerm = rcvAckTerm;
return;
}
if (rcvAckSuccess == 0)
{
AppendEntryRPC appendEntry;
leaderState.nextIndex[candidateId]= candidateNextIndex - 1;
appendEntry.term = nodeState.currentTerm;
appendEntry.leaderId = nodeState.id;
appendEntry.prevLogIndex = nodeState.lastApplied;
appendEntry.prevLogTerm = getLastTerm();
appendEntry.leaderCommit = nodeState.commitIndex;
for (quint32 i = leaderState.nextIndex[candidateId].toUInt(); i <= nodeState.lastApplied; i++)
{
appendEntry.entries[i].insert("term", nodeState.logEntries[i].value("term"));
appendEntry.entries[i].insert("command", nodeState.logEntries[i].value("command"));
}
sendMessage(appendEntry.serializeObject(), senderPort);
}
else
{
leaderState.nextIndex[candidateId] = nodeState.lastApplied + 1;
leaderState.matchIndex[candidateId] = nodeState.lastApplied;
}
}
void ChatDialog::sendMsgACK(quint16 senderPort, QString origin) {
QMap<QString, QMap<QString, QVariant>> msgACK;
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::ReadWrite);
msgACK[MSG_ACK].insert("originid", nodeState.id);
msgACK[MSG_ACK].insert("msgorigin", origin);
msgACK[MSG_ACK].insert("term", nodeState.currentTerm);
msgACK[MSG_ACK].insert("success", 1);
stream << msgACK;
sendMessage(buffer, senderPort);
}
void ChatDialog::addVoteCount(quint8 vote)
{
numberOfVotes += vote;
// we know there are 5 nodes
if (numberOfVotes >= 3)
{
// become leader and send heartbeat
electionTimeout->stop();
// set vote to 0
numberOfVotes = 0;
qDebug() << "\n\nBECAME FUCKING LEADER\n\n";
// set status to LEADER
nodeStatus = LEADER;
QList<quint16> peerList = socket->PeerList();
for (int x = 0; x < peerList.size(); x++) {
sendHeartbeat(peerList[x]);
}
leaderTimeout->start(generateRandomTimeRange(2000,3000));
// init nextIndex + 1 for each node
// also for matchindex ?
}
}
void ChatDialog::addMsgVoteCount(quint8 msgSuccess, QString origin) {
numberOfMsgVotes += msgSuccess;
if (numberOfMsgVotes >= 2) {
nodeState.logEntries[nodeState.lastApplied+1].insert("term", nodeState.currentTerm);
nodeState.logEntries[nodeState.lastApplied+1].insert("command", nodeState.messageList[nodeState.nextPending-1][origin]);
nodeState.logEntries[nodeState.lastApplied+1].insert("origin", origin);
nodeState.lastApplied++;
nodeState.commitIndex++;
nodeState.nextPending--;
QList<quint16> peerList = socket->PeerList();
for (int x = 0; x < peerList.size(); x++) {
sendHeartbeat(peerList[x]);
}
}
}
void ChatDialog::sendRequestVoteRPC()
{
electionTimeout->start(generateRandomTimeRange(8000, 12000));
QMap<QString, QMap<QString, QVariant>> requestVoteMap;
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::ReadWrite);
requestVoteMap[REQUEST_VOTE].insert("term", nodeState.currentTerm);
requestVoteMap[REQUEST_VOTE].insert("candidateId", nodeState.id);
requestVoteMap[REQUEST_VOTE].insert("lastLogIndex", nodeState.lastApplied);
requestVoteMap[REQUEST_VOTE].insert("lastLogTerm", getLastTerm());
stream << requestVoteMap;
QList<quint16> peerList = socket->PeerList();
for (int p = 0; p < peerList.size(); p++) {
sendMessage(buffer, peerList[p]);
}
}
void ChatDialog::sendHeartbeat(quint16 port)
{
if (nodeStatus != LEADER){
nodeStatus = LEADER;
}
AppendEntryRPC appendEntry;
appendEntry.term = nodeState.currentTerm;
appendEntry.leaderId = nodeState.id;
appendEntry.prevLogIndex = nodeState.lastApplied;
appendEntry.prevLogTerm = getLastTerm();
appendEntry.leaderCommit = nodeState.commitIndex;
qDebug() << "\n\n----------SENDING HEARTBEAT-----------\n\n";
sendMessage(appendEntry.serializeObject(), port);
}
quint32 ChatDialog::getLastTerm()
{
quint32 response = 0;
if (!nodeState.logEntries.isEmpty())
{
response = (quint32)nodeState.logEntries[nodeState.lastApplied].value("term").toInt();
}
return response;
}
void ChatDialog::handleLeaderTimeout()
{
qDebug() << "LEADER TIMEOUT OCCURED!!!";
QList<quint16> peerList = socket->PeerList();
for (int x = 0; x < peerList.size(); x++) {
sendHeartbeat(peerList[x]);
}
leaderTimeout->stop();
leaderTimeout->start(generateRandomTimeRange(1000, 2000));
}
void ChatDialog::handleHeartbeatTimeout()
{
qDebug() << "HEARTBEAT TIMEOUT OCCURED!!!";
// when trasmitioning to candidate state
nodeState.currentTerm++;
nodeStatus = CANDIDATE;
numberOfVotes = 1;
heartbeatTimer->stop();
nodeState.votedFor = nodeState.id;
sendRequestVoteRPC();
numberOfVotes++;
}
void ChatDialog::handleElectionTimeout()
{
qDebug() << "REQUESTVOTE TIMEOUT OCCURED!!!";
numberOfVotes = 0;
electionTimeout->stop();
nodeState.currentTerm++;
sendRequestVoteRPC();
}
void ChatDialog::gotReturnPressed()
{
QString text = textline->text();
// textview->append(local_origin + ": " + textline->text());
checkCommand(text);
// Clear the textline to get ready for the next input message.
textline->clear();
}
int ChatDialog::generateRandomTimeRange(int min, int max)
{
std::random_device rd; // obtain a random number from hardware
std::mt19937 eng(rd()); // seed the generator
std::uniform_int_distribution<> distr(min, max); // define the range
return distr(eng);
}
void ChatDialog::checkCommand(QString text) {
if (text.contains("START", Qt::CaseSensitive)) {
qDebug() << "COMMAND START";
// change state to follower and start timer
nodeStatus = FOLLOWER;
// waiting for heartbeat
heartbeatTimer->start(generateRandomTimeRange(4000, 8000));
// if timer runs out change state to CANDIDATE
// else respond to heatbeats
}
else if (text.contains(MSG, Qt::CaseSensitive)) {
qDebug() << "COMMAND MSG";
processMessageReceived(text, this->local_origin);
}
else if (text.contains("GET_CHAT", Qt::CaseSensitive)) {
// Print current chat history of the selected node
qDebug() << "COMMAND GET_CHAT";
// iterate through our chat log and print it to the dialog window
}
else if (text.contains("STOP", Qt::CaseSensitive)) {
qDebug() << "COMMAND STOP";
}
else if (text.contains("DROP", Qt::CaseSensitive)) {
qDebug() << "COMMAND DROP";
processDropNode(text);
}
else if (text.contains("RESTORE", Qt::CaseSensitive)) {
qDebug() << "COMMAND RESTORE";
restoreDroppedNode(text);
}
else if (text.contains("GET_NODES", Qt::CaseSensitive)) {
qDebug() << "COMMAND GET_NODES";
getNodeCommand();
}
else {
qDebug() << "Did not recognize valid command";
}
return;
}
void ChatDialog::processMessageReceived(QString messageReceived, QString origin)
{
messageReceived.replace("MSG ", "", Qt::CaseSensitive); // remove the command from the actual message
QMap<QString, QMap<QString, QVariant>> messageToSend;
messageToSend[MSG].insert("origin", origin);
messageToSend[MSG].insert("msg", messageReceived);
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::ReadWrite);
stream << messageToSend;
if (nodeState.leaderPort != 0){
sendMessage(buffer, nodeState.leaderPort);
}
else {
QList<quint16> peerList = socket->PeerList();
quint16 randomPeer = generateRandomTimeRange(peerList[0], peerList[peerList.size()-1]);
sendMessage(buffer, peerList[randomPeer]);
}
}
void ChatDialog::processDropNode(QString dropNodeMessage)
{
QStringList str;
str = dropNodeMessage.split(" ");
droppedNodes.append(str[1]);
qDebug() << "Dropped node_id: " << str[1];
}
void ChatDialog::restoreDroppedNode(QString restoreNodeMessage)
{
QStringList str;
str = restoreNodeMessage.split(" ");
int indexOfNodeToRestore = droppedNodes.indexOf(str[1]);
droppedNodes.removeAt(indexOfNodeToRestore);
qDebug() << "Restored node_id: " << str[1];
}
void ChatDialog::getNodeCommand()
{
qDebug() << "node ids: " << socket->PeerList();
qDebug() << "WAITING 0, FOLLOWER 1, CANDIDATE 2, LEADER 3";
qDebug() << "Current State: " << nodeStatus;
if (nodeStatus != LEADER) {
if (nodeState.leaderPort != 0) {
qDebug() << "Leader id: " << nodeState.leaderPort;
}
else
{
qDebug() << "There is no leader";
}
}
}
void ChatDialog::sendMessage(QByteArray buffer, quint16 senderPort)
{
qDebug() << "Sending to port: " << senderPort;
socket->writeDatagram(buffer, buffer.size(), QHostAddress::LocalHost, senderPort);
}
NetSocket::NetSocket()
{
// Pick a range of four UDP ports to try to allocate by default,
// computed based on my Unix user ID.
// This makes it trivial for up to four P2Papp instances per user
// to find each other on the same host,
// barring UDP port conflicts with other applications
// (which are quite possible).
// We use the range from 32768 to 49151 for this purpose.
myPortMin = 32768 + (getuid() % 4096)*4;
myPortMax = myPortMin + 4;
}
QList<quint16> NetSocket::PeerList()
{
QList<quint16> peerList;
for (int p = myPortMin; p <= myPortMax; p++) {
if (this->localPort() != p) {
peerList.append(p);
}
}
return peerList;
}
bool NetSocket::bind()
{
// Try to bind to each of the range myPortMin..myPortMax in turn.
for (int p = myPortMin; p <= myPortMax; p++) {
if (QUdpSocket::bind(p)) {
qDebug() << "bound to UDP port " << p;
return true;
}
}
qDebug() << "Oops, no ports in my default range " << myPortMin
<< "-" << myPortMax << " available";
return false;
}
int main(int argc, char **argv)
{
// Initialize Qt toolkit
QApplication app(argc,argv);
// Create an initial chat dialog window
ChatDialog dialog;
dialog.show();
// Enter the Qt main loop; everything else is event driven
return app.exec();
}