-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplicated-log-2.cpp
More file actions
278 lines (228 loc) · 8.57 KB
/
replicated-log-2.cpp
File metadata and controls
278 lines (228 loc) · 8.57 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
#include "replicated-log-2.h"
#include <velocypack/Iterator.h>
#include <velocypack/velocypack-aliases.h>
void rlog2::LogEntry::intoBuilder(VPackBuilder& builder) const {
VPackObjectBuilder ob(&builder);
builder.add("index", VPackValue(index));
builder.add("term", VPackValue(term));
builder.add("payload", VPackSlice(payload.data()));
}
rlog2::LogEntry::LogEntry(VPackSlice slice) {
index = slice.get("index").getNumber<log_index_type>();
term = slice.get("term").getNumber<log_term_type>();
auto payloadSlice = slice.get("payload");
payload.append(payloadSlice.begin(), payloadSlice.byteSize());
}
rlog2::LogEntry::LogEntry(rlog2::log_index_type index,
rlog2::log_term_type term, VPackBufferUInt8 payload)
: index(index), term(term), payload(std::move(payload)) {
assert(index != 0);
}
rlog2::AppendEntriesRequest::AppendEntriesRequest(rlog2::log_term_type term,
rlog2::log_index_type prevLogIndex,
rlog2::log_term_type prevLogTerm,
rlog2::log_index_type commitIndex,
std::unique_ptr<LogIterator> entries)
: term(term),
prevLogIndex(prevLogIndex),
prevLogTerm(prevLogTerm),
commitIndex(commitIndex),
entries(std::move(entries)) {}
void rlog2::AppendEntriesRequest::intoBuilder(VPackBuilder& builder) const {
VPackObjectBuilder ob(&builder);
builder.add("term", VPackValue(term));
builder.add("prevLogIndex", VPackValue(prevLogIndex));
builder.add("prevLogTerm", VPackValue(prevLogTerm));
builder.add("commitIndex", VPackValue(commitIndex));
{
VPackArrayBuilder ab(&builder, "entries");
while (auto e = entries->next()) {
e->intoBuilder(builder);
}
}
}
rlog2::AppendEntriesRequest::AppendEntriesRequest(VPackSlice slice) {
term = slice.get("term").getNumber<log_index_type>();
prevLogIndex = slice.get("prevLogIndex").getNumber<log_index_type>();
prevLogTerm = slice.get("prevLogTerm").getNumber<log_index_type>();
commitIndex = slice.get("commitIndex").getNumber<log_index_type>();
using container = std::vector<LogEntry>;
auto entriesSlice = slice.get("entries");
container v;
v.reserve(entriesSlice.length());
for (auto const& e : VPackArrayIterator(slice.get("entries"))) {
v.emplace_back(e);
}
struct Iterator final : LogIterator {
auto next() -> std::optional<LogEntry> override {
if (iter == v.end()) {
return std::nullopt;
} else {
return *(iter++);
}
}
void reset() override { iter = v.begin(); }
explicit Iterator(container vp) : v(std::move(vp)), iter(v.begin()) {}
container v;
container::iterator iter;
};
entries = std::make_unique<Iterator>(std::move(v));
}
rlog2::AppendEntriesResult::AppendEntriesResult(VPackSlice slice) {
term = slice.get("term").getNumber<log_term_type>();
success = slice.get("success").isTrue();
}
void rlog2::AppendEntriesResult::intoBuilder(VPackBuilder& builder) const {
VPackObjectBuilder ob(&builder);
builder.add("term", VPackValue(term));
builder.add("success", VPackValue(success));
}
rlog2::AppendEntriesResult::AppendEntriesResult(rlog2::log_term_type term, bool success)
: term(term), success(success) {}
rlog2::ReplicatedLog::ReplicatedLog(rlog2::log_id_type logId_,
std::shared_ptr<RocksDBHandle> rocks_,
std::shared_ptr<sched::scheduler> scheduler_)
: _logId(logId_), rocks(std::move(rocks_)), scheduler(std::move(scheduler_)) {
rocksdb::ReadOptions opts;
auto iter = this->rocks->db->NewIterator(opts, this->rocks->logs.get());
std::string prefix;
insert_big_endian_uint64(prefix, this->_logId + 1);
iter->Seek(rocksdb::Slice(prefix));
if (auto status = iter->status(); !status.ok()) {
throw RocksDBException(status);
}
while (iter->Valid() && iter->key().starts_with(rocksdb::Slice(prefix))) {
_log.emplace_back(VPackSlice(reinterpret_cast<const uint8_t*>(iter->key().data())));
if (_log.size() == 1000) {
break;
}
iter->Prev();
}
if (!_log.empty()) {
firstMemoryIndex = _log.front().index;
currentIndex = _log.back().index;
currentTerm = _log.back().term;
storeIndex = _log.back().index;
}
}
auto rlog2::ReplicatedLog::insert(VPackBufferUInt8 payload)
-> std::pair<log_index_type, log_term_type> {
std::unique_lock guard(mutex);
if (state != State::LEADER) {
throw std::logic_error("not a leader");
}
_log.emplace_back(currentIndex + 1, currentTerm, std::move(payload));
currentIndex += 1;
triggerStore();
triggerReplication();
return {currentIndex, currentTerm};
}
auto rlog2::ReplicatedLog::waitFor(rlog2::log_index_type index)
-> futures::future<WaitResult> {
std::unique_lock guard(mutex);
if (state != State::LEADER) {
throw std::logic_error("not a leader");
}
if (index < firstMemoryIndex) {
throw std::runtime_error("index no longer in memory");
}
auto relativeIndex = index - firstMemoryIndex;
if (relativeIndex >= _log.size()) {
throw std::logic_error("unknown log index");
}
if (commitIndex >= index) {
return futures::make_fulfilled_promise<WaitResult>(std::in_place, _log.operator[](relativeIndex).term);
}
auto&& [f, p] = futures::make_promise<WaitResult>();
notify_queue.emplace(index, std::move(p));
return std::move(f);
}
futures::future<void> rlog2::ReplicatedLog::assumeLeadership(rlog2::log_term_type term) {
std::unique_lock guard(mutex);
if (state != State::FOLLOWER) {
throw std::logic_error("not a follower");
}
if (term < currentTerm) {
throw std::logic_error("invalid term");
}
state = State::TRANSITION;
// wait for all store operations to complete
return waitForAllTasks().then([this, self = shared_from_this(), term](auto&& e) {
std::unique_lock guard(mutex);
if (e.has_error()) {
// failed to do something
state = State::FOLLOWER;
abort();
} else {
state = State::LEADER;
currentTerm = term;
}
});
}
futures::future<void> rlog2::ReplicatedLog::waitForAllTasks() {
std::vector<futures::future<void>> tasks;
tasks.emplace_back(std::move(storeOperation));
return futures::fan_in(tasks.begin(), tasks.end()).then([](auto&& e) {
e.rethrow_error();
});
}
futures::future<void> rlog2::ReplicatedLog::resignLeadership() {
std::unique_lock guard(mutex);
if (state != State::LEADER) {
throw std::logic_error("not a leader");
}
// wait for store and replication to finish
state = State::TRANSITION;
// wait for all store operations to complete
return waitForAllTasks().then([this, self = shared_from_this()](auto&& e) {
std::unique_lock guard(mutex);
if (e.has_error()) {
// failed to do something
state = State::LEADER;
abort();
} else {
state = State::FOLLOWER;
}
});
}
auto rlog2::ReplicatedLog::appendEntries(rlog2::AppendEntriesRequest const& req)
-> futures::future<AppendEntriesResult> {
std::unique_lock guard(mutex);
if (state == State::FOLLOWER && req.term >= currentTerm) {
// update my term
currentTerm = req.term;
commitIndex = req.commitIndex;
// check log end
if (req.prevLogIndex <= currentIndex) {
if (req.prevLogIndex < firstMemoryIndex) {
throw std::runtime_error("entry not in memory");
}
auto relativeIndex = req.prevLogIndex - firstMemoryIndex;
auto& entry = _log.at(relativeIndex);
if (entry.term == req.prevLogTerm) {
// delete all entries following entry
_log.erase(_log.begin() + relativeIndex, _log.end());
// insert the new entries
while (auto e = req.entries->next()) {
_log.emplace_back(std::move(e).value());
}
storeIndex = req.prevLogIndex;
return runStoreOperation()
.and_then([term = currentTerm] {
std::cout << "appended entries" << std::endl;
return AppendEntriesResult{term, true};
})
.throw_nested<std::logic_error>("failed to append entries");
} else {
std::cout << "term of prevlog index does not match " << entry.term
<< " != " << req.prevLogTerm << std::endl;
}
} else {
std::cout << "prevlog index is after my log head" << _log.size() << std::endl;
}
} else {
std::cout << "my term is higher " << currentTerm << std::endl;
}
std::cout << "returning false to replication " << std::endl;
return futures::make_fulfilled_promise<AppendEntriesResult>(std::in_place, currentTerm, false);
}