-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLogReplication.cpp
130 lines (101 loc) · 2.49 KB
/
LogReplication.cpp
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
#include "LogReplication.hpp"
#include "AppendEntry.hpp"
#include "SyncRequest.hpp"
#include "Peer.hpp"
using namespace locke;
LogReplication::LogReplication(RaftServer& server) : server(server) {}
void LogReplication::execute()
{
Peer* peer;
update_commit_index();
if (peer = expiring_peer()) {
send_heartbeat(peer);
return;
}
if (!(peer = outdated_peer())) {
return;
}
send_append_entry(peer);
}
void LogReplication::update_commit_index()
{
for (uint32_t idx = server.last_index; idx > 1; idx--) {
uint8_t count = 1;
for (uint8_t i = 0; i < NUM_PEERS; i++) {
if (server.peers[i]->match_index >= idx) {
count++;
}
}
if (count >= MAJORITY) {
server.commit_index = idx;
break;
}
}
}
Peer* LogReplication::expiring_peer()
{
for (int i = 0; i < NUM_PEERS; i++) {
Peer* peer = server.peers[i];
if (peer->enabled() && peer->will_timeout_soon()) {
return peer;
}
}
return nullptr;
}
Peer* LogReplication::outdated_peer()
{
for (int i = 0; i < NUM_PEERS; i++) {
Peer* peer = server.peers[i];
if (peer->enabled() && peer->next_index <= server.last_index) {
return peer;
}
}
return nullptr;
}
void LogReplication::send_heartbeat(Peer* peer)
{
StaticJsonBuffer<JSON_LARGE> large_buff;
JsonObject& json = large_buff.createObject();
AppendEntry heartbeat(json, server);
SyncRequest::Result result;
if (!SyncRequest::perform(peer->ip, heartbeat.json, &result)) {
peer->retry_later();
return;
}
if (!result.success && result.term > server.current_term) {
server.set_status(Follower);
return;
}
peer->touch();
}
void LogReplication::send_append_entry(Peer* peer)
{
StaticJsonBuffer<JSON_LARGE> large_buff;
JsonObject& json = large_buff.createObject();
Log::Entry next, prev;
Log::fetch(&next, peer->next_index);
Log::fetch(&prev, peer->next_index - 1);
AppendEntry append_entry(json, server, next, prev);
SyncRequest::Result result;
if (!SyncRequest::perform(peer->ip, append_entry.json, &result)) {
peer->retry_later();
return;
}
process_result(peer, &result);
}
void LogReplication::process_result(Peer* peer, SyncRequest::Result* result)
{
if (result->term > server.current_term) {
server.current_term = result-> term;
server.set_status(Follower);
return;
}
if (!result->success) {
peer->next_index--;
peer->touch();
return;
}
peer->match_index = peer->next_index;
peer->next_index++;
peer->touch();
}