-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcs_raft_server.cpp
1566 lines (1385 loc) · 62.2 KB
/
cs_raft_server.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
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
/**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. The ASF licenses
* this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cornerstone/cornerstone.h"
using namespace cornerstone;
const int CRaftServer::default_snapshot_sync_block_size = 4 * 1024;
// for tracing and debugging
static const char* __msg_type_str[] = {
"unknown",
"request_vote_request",
"request_vote_response",
"append_entries_request",
"append_entries_response",
"client_request",
"add_server_request",
"add_server_response",
"remove_server_request",
"remove_server_response",
"sync_log_request",
"sync_log_response",
"join_cluster_request",
"join_cluster_response",
"leave_cluster_request",
"leave_cluster_response",
"install_snapshot_request",
"install_snapshot_response"
};
CPtr<CResponseMsg> CRaftServer::ProcessRequest(CRequestMessage& req) {
recur_lock(lock_);
l_.Debug(
lstrfmt("Receive a %s message from %d with LastLogIndex=%llu, LastLogTerm=%llu, EntriesLength=%d, CommitIndex=%llu and Term=%llu")
.fmt(
__msg_type_str[req.GetType()],
req.GetSrc(),
req.get_last_log_idx(),
req.get_last_log_term(),
req.log_entries().size(),
req.get_commit_idx(),
req.GetTerm()));
if (req.GetType() == EMsgType::append_entries_request ||
req.GetType() == EMsgType::request_vote_request ||
req.GetType() == EMsgType::install_snapshot_request) {
// we allow the server to be continue after term updated to save a round message
update_term(req.GetTerm());
// Reset stepping down value to prevent this server goes down when leader crashes after sending a LeaveClusterRequest
if (steps_to_down_ > 0) {
steps_to_down_ = 2;
}
}
CPtr<CResponseMsg> resp;
if (req.GetType() == EMsgType::append_entries_request) {
resp = handle_append_entries(req);
}
else if (req.GetType() == EMsgType::request_vote_request) {
resp = handle_vote_req(req);
}
else if (req.GetType() == EMsgType::client_request) {
resp = handle_cli_req(req);
}
else {
// extended requests
resp = handle_extended_msg(req);
}
if (resp) {
l_.Debug(
lstrfmt("Response back a %s message to %d with Accepted=%d, Term=%llu, NextIndex=%llu")
.fmt(
__msg_type_str[resp->GetType()],
resp->GetDest(),
resp->GetAccepted() ? 1 : 0,
resp->GetTerm(),
resp->GetNextIndex()));
}
return resp;
}
CPtr<CResponseMsg> CRaftServer::handle_append_entries(CRequestMessage& req) {
if (req.GetTerm() == state_->GetTerm()) {
if (role_ == EServerRole::candidate) {
become_follower();
}
else if (role_ == EServerRole::leader) {
l_.Debug(
lstrfmt("Receive AppendEntriesRequest from another leader(%d) with same term, there must be a bug, server exits")
.fmt(req.GetSrc()));
ctx_->m_StateManager.SystemExit(-1);
::exit(-1);
}
else {
restart_election_timer();
}
}
// After a snapshot the req.get_last_log_idx() may less than log_store_->next_slot() but equals to log_store_->next_slot() -1
// In this case, log is Okay if req.get_last_log_idx() == lastSnapshot.get_last_log_idx() && req.get_last_log_term() == lastSnapshot.get_last_log_term()
// In not accepted case, we will return log_store_->next_slot() for the leader to quick jump to the index that might aligned
CPtr<CResponseMsg> resp(cs_new<CResponseMsg>(state_->GetTerm(), EMsgType::append_entries_response, id_, req.GetSrc(), log_store_->NextSlot()));
bool log_okay = req.get_last_log_idx() == 0 ||
(req.get_last_log_idx() < log_store_->NextSlot() && req.get_last_log_term() == term_for_log(req.get_last_log_idx()));
if (req.GetTerm() < state_->GetTerm() || !log_okay) {
return resp;
}
// follower & log is okay
if (req.log_entries().size() > 0) {
// write logs to store, start from overlapped logs
ulong idx = req.get_last_log_idx() + 1;
size_t log_idx = 0;
while (idx < log_store_->NextSlot() && log_idx < req.log_entries().size()) {
if (log_store_->TermAt(idx) == req.log_entries().at(log_idx)->GetTerm()) {
idx++;
log_idx++;
}
else {
break;
}
}
// dealing with overwrites
while (idx < log_store_->NextSlot() && log_idx < req.log_entries().size()) {
CPtr<CLogEntry> old_entry(log_store_->EntryAt(idx));
if (old_entry->GetType() == ELogValueType::e_Application) {
state_machine_.Rollback(idx, old_entry->GetBuffer());
}
else if (old_entry->GetType() == ELogValueType::e_Configuration) {
l_.Info(sstrfmt("revert from a prev config change to config at %llu").fmt(config_->GetLogIndex()));
config_changing_ = false;
}
log_store_->WriteAt(idx++, req.log_entries().at(log_idx++));
}
// append new log entries
while (log_idx < req.log_entries().size()) {
CPtr<CLogEntry> entry = req.log_entries().at(log_idx ++);
ulong idx_for_entry = log_store_->Append(entry);
if (entry->GetType() == ELogValueType::e_Configuration) {
l_.Info(sstrfmt("receive a config change from leader at %llu").fmt(idx_for_entry));
config_changing_ = true;
}
else {
state_machine_.PreCommit(idx_for_entry, entry->GetBuffer());
}
}
}
leader_ = req.GetSrc();
commit(req.get_commit_idx());
resp->Accept(req.get_last_log_idx() + req.log_entries().size() + 1);
return resp;
}
CPtr<CResponseMsg> CRaftServer::handle_vote_req(CRequestMessage& req) {
CPtr<CResponseMsg> resp(cs_new<CResponseMsg>(state_->GetTerm(), EMsgType::request_vote_response, id_, req.GetSrc()));
bool log_okay = req.get_last_log_term() > log_store_->LastEntry()->GetTerm() ||
(req.get_last_log_term() == log_store_->LastEntry()->GetTerm() &&
log_store_->NextSlot() - 1 <= req.get_last_log_idx());
bool grant = req.GetTerm() == state_->GetTerm() && log_okay && (state_->GetVotedFor() == req.GetSrc() || state_->GetVotedFor() == -1);
if (grant) {
resp->Accept(log_store_->NextSlot());
state_->SetVotedFor(req.GetSrc());
ctx_->m_StateManager.SaveState(*state_);
}
return resp;
}
CPtr<CResponseMsg> CRaftServer::handle_cli_req(CRequestMessage& req) {
CPtr<CResponseMsg> resp (cs_new<CResponseMsg>(state_->GetTerm(), EMsgType::append_entries_response, id_, leader_));
if (role_ != EServerRole::leader) {
return resp;
}
std::vector<CPtr<CLogEntry>>& entries = req.log_entries();
for (size_t i = 0; i < entries.size(); ++i) {
log_store_->Append(entries.at(i));
state_machine_.PreCommit(log_store_->NextSlot() - 1, entries.at(i)->GetBuffer());
}
// urgent commit, so that the commit will not depend on hb
request_append_entries();
resp->Accept(log_store_->NextSlot());
return resp;
}
void CRaftServer::handle_election_timeout() {
recur_lock(lock_);
if (steps_to_down_ > 0) {
if (--steps_to_down_ == 0) {
l_.Info("no hearing further news from leader, remove this server from cluster and step down");
for (std::list<CPtr<CServerConfig>>::iterator it = config_->GetServers().begin();
it != config_->GetServers().end();
++it) {
if ((*it)->GetId() == id_) {
config_->GetServers().erase(it);
ctx_->m_StateManager.SaveConfig(*config_);
break;
}
}
ctx_->m_StateManager.SystemExit(-1);
::exit(0);
return;
}
l_.Info(sstrfmt("stepping down (cycles left: %d), skip this election timeout event").fmt(steps_to_down_));
restart_election_timer();
return;
}
if (catching_up_) {
// this is a new server for the cluster, will not send out vote req until conf that includes this srv is committed
l_.Info("election timeout while joining the cluster, ignore it.");
restart_election_timer();
return;
}
if (role_ == EServerRole::leader) {
l_.Error("A leader should never encounter election timeout, illegal application state, stop the application");
ctx_->m_StateManager.SystemExit(-1);
::exit(-1);
return;
}
l_.Debug("Election timeout, change to Candidate");
state_->IncTerm();
state_->SetVotedFor(-1);
role_ = EServerRole::candidate;
votes_granted_ = 0;
votes_responded_ = 0;
election_completed_ = false;
ctx_->m_StateManager.SaveState(*state_);
request_vote();
// restart the election timer if this is not yet a leader
if (role_ != EServerRole::leader) {
restart_election_timer();
}
}
void CRaftServer::request_vote() {
l_.Info(sstrfmt("requestVote started with term %llu").fmt(state_->GetTerm()));
state_->SetVotedFor(id_);
ctx_->m_StateManager.SaveState(*state_);
votes_granted_ += 1;
votes_responded_ += 1;
// is this the only server?
if (votes_granted_ > (int32)(peers_.size() + 1) / 2) {
election_completed_ = true;
become_leader();
return;
}
for (peer_itor it = peers_.begin(); it != peers_.end(); ++it) {
CPtr<CRequestMessage> req(cs_new<CRequestMessage>(state_->GetTerm(), EMsgType::request_vote_request, id_, it->second->get_id(), term_for_log(log_store_->NextSlot() - 1), log_store_->NextSlot() - 1, state_->GetCommitIndex()));
l_.Debug(sstrfmt("send %s to server %d with term %llu").fmt(__msg_type_str[req->GetType()], it->second->get_id(), state_->GetTerm()));
it->second->send_req(req, resp_handler_);
}
}
void CRaftServer::request_append_entries() {
if (peers_.size() == 0) {
commit(log_store_->NextSlot() - 1);
return;
}
for (peer_itor it = peers_.begin(); it != peers_.end(); ++it) {
request_append_entries(*it->second);
}
}
bool CRaftServer::request_append_entries(CRaftPeer& p) {
if (p.make_busy()) {
CPtr<CRequestMessage> msg = create_append_entries_req(p);
p.send_req(msg, resp_handler_);
return true;
}
l_.Debug(sstrfmt("Server %d is busy, skip the request").fmt(p.get_id()));
return false;
}
void CRaftServer::handle_peer_resp(CPtr<CResponseMsg>& resp, CPtr<CRpcException>& err) {
recur_lock(lock_);
if (err) {
l_.Info(sstrfmt("peer response error: %s").fmt(err->what()));
return;
}
l_.Debug(
lstrfmt("Receive a %s message from peer %d with Result=%d, Term=%llu, NextIndex=%llu")
.fmt(__msg_type_str[resp->GetType()], resp->GetSrc(), resp->GetAccepted() ? 1 : 0, resp->GetTerm(), resp->GetNextIndex()));
// if term is updated, no more action is required
if (update_term(resp->GetTerm())) {
return;
}
// ignore the response that with lower term for safety
switch (resp->GetType())
{
case EMsgType::request_vote_response:
handle_voting_resp(*resp);
break;
case EMsgType::append_entries_response:
handle_append_entries_resp(*resp);
break;
case EMsgType::install_snapshot_response:
handle_install_snapshot_resp(*resp);
break;
default:
l_.Error(sstrfmt("Received an unexpected message %s for response, system exits.").fmt(__msg_type_str[resp->GetType()]));
ctx_->m_StateManager.SystemExit(-1);
::exit(-1);
break;
}
}
void CRaftServer::handle_append_entries_resp(CResponseMsg& resp) {
peer_itor it = peers_.find(resp.GetSrc());
if (it == peers_.end()) {
l_.Info(sstrfmt("the response is from an unkonw peer %d").fmt(resp.GetSrc()));
return;
}
// if there are pending logs to be synced or commit index need to be advanced, continue to send appendEntries to this peer
bool need_to_catchup = true;
CPtr<CRaftPeer> p = it->second;
if (resp.GetAccepted()) {
{
std::lock_guard<std::mutex>(p->get_lock());
p->set_next_log_idx(resp.GetNextIndex());
p->set_matched_idx(resp.GetNextIndex() - 1);
}
// try to commit with this response
// TODO: keep this to save a "new" operation for each response
std::unique_ptr<ulong> matched_indexes(new ulong[peers_.size() + 1]);
matched_indexes.get()[0] = log_store_->NextSlot() - 1;
int i = 1;
for (it = peers_.begin(); it != peers_.end(); ++it, ++i) {
matched_indexes.get()[i] = it->second->get_matched_idx();
}
std::sort(matched_indexes.get(), matched_indexes.get() + (peers_.size() + 1), std::greater<ulong>());
commit(matched_indexes.get()[(peers_.size() + 1) / 2]);
need_to_catchup = p->clear_pending_commit() || resp.GetNextIndex() < log_store_->NextSlot();
}
else {
std::lock_guard<std::mutex> guard(p->get_lock());
if (resp.GetNextIndex() > 0 && p->get_next_log_idx() > resp.GetNextIndex()) {
// fast move for the peer to catch up
p->set_next_log_idx(resp.GetNextIndex());
}
else {
p->set_next_log_idx(p->get_next_log_idx() - 1);
}
}
// This may not be a leader anymore, such as the response was sent out long time ago
// and the role was updated by UpdateTerm call
// Try to match up the logs for this peer
if (role_ == EServerRole::leader && need_to_catchup) {
request_append_entries(*p);
}
}
void CRaftServer::handle_install_snapshot_resp(CResponseMsg& resp) {
peer_itor it = peers_.find(resp.GetSrc());
if (it == peers_.end()) {
l_.Info(sstrfmt("the response is from an unkonw peer %d").fmt(resp.GetSrc()));
return;
}
// if there are pending logs to be synced or commit index need to be advanced, continue to send appendEntries to this peer
bool need_to_catchup = true;
CPtr<CRaftPeer> p = it->second;
if (resp.GetAccepted()) {
std::lock_guard<std::mutex> guard(p->get_lock());
CPtr<CSnapshotSyncContext> sync_ctx = p->get_snapshot_sync_ctx();
if (sync_ctx == nilptr) {
l_.Info("no snapshot sync context for this peer, drop the response");
need_to_catchup = false;
}
else {
if (resp.GetNextIndex() >= sync_ctx->GetSnapshot()->Size()) {
l_.Debug("snapshot sync is done");
CPtr<CSnapshot> nil_snp;
p->set_next_log_idx(sync_ctx->GetSnapshot()->GetLastLogIndex() + 1);
p->set_matched_idx(sync_ctx->GetSnapshot()->GetLastLogIndex());
p->set_snapshot_in_sync(nil_snp);
need_to_catchup = p->clear_pending_commit() || resp.GetNextIndex() < log_store_->NextSlot();
}
else {
l_.Debug(sstrfmt("continue to sync snapshot at offset %llu").fmt(resp.GetNextIndex()));
sync_ctx->SetOffset(resp.GetNextIndex());
}
}
}
else {
l_.Info("peer declines to install the snapshot, will retry");
}
// This may not be a leader anymore, such as the response was sent out long time ago
// and the role was updated by UpdateTerm call
// Try to match up the logs for this peer
if (role_ == EServerRole::leader && need_to_catchup) {
request_append_entries(*p);
}
}
void CRaftServer::handle_voting_resp(CResponseMsg& resp) {
votes_responded_ += 1;
if (election_completed_) {
l_.Info("Election completed, will ignore the voting result from this server");
return;
}
if (resp.GetAccepted()) {
votes_granted_ += 1;
}
if (votes_responded_ >= (int32)(peers_.size() + 1)) {
election_completed_ = true;
}
if (votes_granted_ > (int32)((peers_.size() + 1) / 2)) {
l_.Info(sstrfmt("Server is elected as leader for term %llu").fmt(state_->GetTerm()));
election_completed_ = true;
become_leader();
}
}
void CRaftServer::handle_hb_timeout(CRaftPeer& p) {
recur_lock(lock_);
l_.Debug(sstrfmt("Heartbeat timeout for %d").fmt(p.get_id()));
if (role_ == EServerRole::leader) {
request_append_entries(p);
{
std::lock_guard<std::mutex> guard(p.get_lock());
if (p.is_hb_enabled()) {
// Schedule another heartbeat if heartbeat is still enabled
ctx_->m_Scheduler.Schedule(p.get_hb_task(), p.get_current_hb_interval());
}
else {
l_.Debug(sstrfmt("heartbeat is disabled for peer %d").fmt(p.get_id()));
}
}
}
else {
l_.Info(sstrfmt("Receive a heartbeat event for %d while no longer as a leader").fmt(p.get_id()));
}
}
void CRaftServer::restart_election_timer() {
// don't start the election timer while this server is still catching up the logs
if (catching_up_) {
return;
}
if (election_task_) {
scheduler_.Cancel(election_task_);
}
else {
election_task_ = cs_new<CTimerTask<void>>(election_exec_);
}
scheduler_.Schedule(election_task_, rand_timeout_());
}
void CRaftServer::stop_election_timer() {
if (!election_task_) {
l_.Warning("Election Timer is never started but is requested to stop, protential a bug");
return;
}
scheduler_.Cancel(election_task_);
}
void CRaftServer::become_leader() {
stop_election_timer();
role_ = EServerRole::leader;
leader_ = id_;
srv_to_join_.reset();
CPtr<CSnapshot> nil_snp;
for (peer_itor it = peers_.begin(); it != peers_.end(); ++it) {
it->second->set_next_log_idx(log_store_->NextSlot());
it->second->set_snapshot_in_sync(nil_snp);
it->second->set_free();
enable_hb_for_peer(*(it->second));
}
if (config_->GetLogIndex() == 0) {
config_->SetLogIndex(log_store_->NextSlot());
CPtr<CBuffer> conf_buf = config_->Serialize();
CPtr<CLogEntry> entry(cs_new<CLogEntry>(state_->GetTerm(), conf_buf, ELogValueType::e_Configuration));
log_store_->Append(entry);
l_.Info("save initial config to log store");
config_changing_ = true;
}
request_append_entries();
}
void CRaftServer::enable_hb_for_peer(CRaftPeer& p) {
p.enable_hb(true);
p.resume_hb_speed();
scheduler_.Schedule(p.get_hb_task(), p.get_current_hb_interval());
}
void CRaftServer::become_follower() {
// stop hb for all peers
for (peer_itor it = peers_.begin(); it != peers_.end(); ++it) {
it->second->enable_hb(false);
}
srv_to_join_.reset();
role_ = EServerRole::follower;
restart_election_timer();
}
bool CRaftServer::update_term(ulong term) {
if (term > state_->GetTerm()) {
state_->SetTerm(term);
state_->SetVotedFor(-1);
election_completed_ = false;
votes_granted_ = 0;
votes_responded_ = 0;
ctx_->m_StateManager.SaveState(*state_);
become_follower();
return true;
}
return false;
}
void CRaftServer::commit(ulong target_idx) {
if (target_idx > quick_commit_idx_) {
quick_commit_idx_ = target_idx;
// if this is a leader notify peers to commit as well
// for peers that are free, send the request, otherwise, set pending commit flag for that peer
if (role_ == EServerRole::leader) {
for (peer_itor it = peers_.begin(); it != peers_.end(); ++it) {
if (!request_append_entries(*(it->second))) {
it->second->set_pending_commit();
}
}
}
}
if (log_store_->NextSlot() - 1 > state_->GetCommitIndex() && quick_commit_idx_ > state_->GetCommitIndex()) {
commit_cv_.notify_one();
}
}
void CRaftServer::snapshot_and_compact(ulong committed_idx) {
bool snapshot_in_action = false;
try {
bool f = false;
if (ctx_->m_Params->m_iSnapshotSistance > 0
&& (committed_idx - log_store_->StartIndex()) > (ulong)ctx_->m_Params->m_iSnapshotSistance
&& snp_in_progress_.compare_exchange_strong(f, true)) {
snapshot_in_action = true;
CPtr<CSnapshot> snp(state_machine_.LastSnapshot());
if (snp && (committed_idx - snp->GetLastLogIndex()) < (ulong)ctx_->m_Params->m_iSnapshotSistance) {
l_.Info(sstrfmt("a very recent snapshot is available at index %llu, will skip this one").fmt(snp->GetLastLogIndex()));
snp_in_progress_.store(false);
snapshot_in_action = false;
}
else {
l_.Info(sstrfmt("creating a snapshot for index %llu").fmt(committed_idx));
// get the latest configuration info
CPtr<CClusterConfig> conf(config_);
while (conf->GetLogIndex() > committed_idx && conf->GetPrevLogIndex() >= log_store_->StartIndex()) {
CPtr<CLogEntry> conf_log(log_store_->EntryAt(conf->GetPrevLogIndex()));
conf = CClusterConfig::Deserialize(conf_log->GetBuffer());
}
if (conf->GetLogIndex() > committed_idx &&
conf->GetPrevLogIndex() > 0 &&
conf->GetPrevLogIndex() < log_store_->StartIndex()) {
CPtr<CSnapshot> s(state_machine_.LastSnapshot());
if (!s) {
l_.Error("No snapshot could be found while no configuration cannot be found in current committed logs, this is a system error, exiting");
ctx_->m_StateManager.SystemExit(-1);
::exit(-1);
return;
}
conf = s->GetLastConfig();
}
else if (conf->GetLogIndex() > committed_idx && conf->GetPrevLogIndex() == 0) {
l_.Error("BUG!!! stop the system, there must be a configuration at index one");
ctx_->m_StateManager.SystemExit(-1);
::exit(-1);
return;
}
ulong idx_to_compact = committed_idx - 1;
ulong log_term_to_compact = log_store_->TermAt(idx_to_compact);
CPtr<CSnapshot> new_snapshot(cs_new<CSnapshot>(idx_to_compact, log_term_to_compact, conf));
CAsyncResult<bool>::handler_type handler = (CAsyncResult<bool>::handler_type) std::bind(&CRaftServer::on_snapshot_completed, this, new_snapshot, std::placeholders::_1, std::placeholders::_2);
state_machine_.CreateSnapshot(
*new_snapshot,
handler);
snapshot_in_action = false;
}
}
}
catch (...) {
l_.Error(sstrfmt("failed to compact logs at index %llu due to errors").fmt(committed_idx));
if (snapshot_in_action) {
bool val = true;
snp_in_progress_.compare_exchange_strong(val, false);
}
}
}
void CRaftServer::on_snapshot_completed(CPtr<CSnapshot>& s, bool result, CPtr<std::exception>& err) {
do {
if (err != nilptr) {
l_.Error(lstrfmt("failed to create a snapshot due to %s").fmt(err->what()));
break;
}
if (!result) {
l_.Info("the state machine rejects to create the snapshot");
break;
}
{
recur_lock(lock_);
l_.Debug("snapshot created, compact the log store");
log_store_->Compact(s->GetLastLogIndex());
}
} while (false);
snp_in_progress_.store(false);
}
CPtr<CRequestMessage> CRaftServer::create_append_entries_req(CRaftPeer& p) {
ulong cur_nxt_idx(0L);
ulong commit_idx(0L);
ulong last_log_idx(0L);
ulong term(0L);
ulong starting_idx(1L);
{
recur_lock(lock_);
starting_idx = log_store_->StartIndex();
cur_nxt_idx = log_store_->NextSlot();
commit_idx = quick_commit_idx_;
term = state_->GetTerm();
}
{
std::lock_guard<std::mutex> guard(p.get_lock());
if (p.get_next_log_idx() == 0L) {
p.set_next_log_idx(cur_nxt_idx);
}
last_log_idx = p.get_next_log_idx() - 1;
}
if (last_log_idx >= cur_nxt_idx) {
l_.Error(sstrfmt("Peer's lastLogIndex is too large %llu v.s. %llu, server exits").fmt(last_log_idx, cur_nxt_idx));
ctx_->m_StateManager.SystemExit(-1);
::exit(-1);
return CPtr<CRequestMessage>();
}
// for syncing the snapshots, for starting_idx - 1, we can check with last snapshot
if (last_log_idx > 0 && last_log_idx < starting_idx - 1) {
return create_sync_snapshot_req(p, last_log_idx, term, commit_idx);
}
ulong last_log_term = term_for_log(last_log_idx);
ulong end_idx = std::min(cur_nxt_idx, last_log_idx + 1 + ctx_->m_Params->m_iMaxAppendSize);
CPtr<std::vector<CPtr<CLogEntry>>> log_entries((last_log_idx + 1) >= cur_nxt_idx ? CPtr<std::vector<CPtr<CLogEntry>>>() : log_store_->LogEntries(last_log_idx + 1, end_idx));
l_.Debug(
lstrfmt("An AppendEntries Request for %d with LastLogIndex=%llu, LastLogTerm=%llu, EntriesLength=%d, CommitIndex=%llu and Term=%llu")
.fmt(
p.get_id(),
last_log_idx,
last_log_term,
log_entries ? log_entries->size() : 0,
commit_idx,
term));
CPtr<CRequestMessage> req(cs_new<CRequestMessage>(term, EMsgType::append_entries_request, id_, p.get_id(), last_log_term, last_log_idx, commit_idx));
std::vector<CPtr<CLogEntry>>& v = req->log_entries();
if (log_entries) {
v.insert(v.end(), log_entries->begin(), log_entries->end());
}
return req;
}
void CRaftServer::reconfigure(const CPtr<CClusterConfig>& new_config) {
l_.Debug(
lstrfmt("system is reconfigured to have %d servers, last config index: %llu, this config index: %llu")
.fmt(new_config->GetServers().size(), new_config->GetPrevLogIndex(), new_config->GetLogIndex()));
// we only allow one server to be added or removed at a time
std::vector<int32> srvs_removed;
std::vector<CPtr<CServerConfig>> srvs_added;
std::list<CPtr<CServerConfig>>& new_srvs(new_config->GetServers());
for (std::list<CPtr<CServerConfig>>::const_iterator it = new_srvs.begin(); it != new_srvs.end(); ++it) {
peer_itor pit = peers_.find((*it)->GetId());
if (pit == peers_.end() && id_ != (*it)->GetId()) {
srvs_added.push_back(*it);
}
}
for (peer_itor it = peers_.begin(); it != peers_.end(); ++it) {
if (!new_config->GetServer(it->first)) {
srvs_removed.push_back(it->first);
}
}
if (!new_config->GetServer(id_)) {
srvs_removed.push_back(id_);
}
for (std::vector<CPtr<CServerConfig>>::const_iterator it = srvs_added.begin(); it != srvs_added.end(); ++it) {
CPtr<CServerConfig> srv_added(*it);
CTimerTask<CRaftPeer&>::executor exec = (CTimerTask<CRaftPeer&>::executor)std::bind(&CRaftServer::handle_hb_timeout, this, std::placeholders::_1);
CPtr<CRaftPeer> p = cs_new<CRaftPeer, CServerConfig&, SRaftContext&, CTimerTask<CRaftPeer&>::executor&>(*srv_added, *ctx_, exec);
p->set_next_log_idx(log_store_->NextSlot());
peers_.insert(std::make_pair(srv_added->GetId(), p));
l_.Info(sstrfmt("server %d is added to cluster").fmt(srv_added->GetId()));
if (role_ == EServerRole::leader) {
l_.Info(sstrfmt("enable heartbeating for server %d").fmt(srv_added->GetId()));
enable_hb_for_peer(*p);
if (srv_to_join_ && srv_to_join_->get_id() == p->get_id()) {
p->set_next_log_idx(srv_to_join_->get_next_log_idx());
srv_to_join_.reset();
}
}
}
for (std::vector<int32>::const_iterator it = srvs_removed.begin(); it != srvs_removed.end(); ++it) {
int32 srv_removed = *it;
if (srv_removed == id_ && !catching_up_) {
// this server is removed from cluster
ctx_->m_StateManager.SaveConfig(*new_config);
l_.Info("server has been removed, step down");
ctx_->m_StateManager.SystemExit(0);
return;
}
peer_itor pit = peers_.find(srv_removed);
if (pit != peers_.end()) {
pit->second->enable_hb(false);
peers_.erase(pit);
l_.Info(sstrfmt("server %d is removed from cluster").fmt(srv_removed));
}
else {
l_.Info(sstrfmt("peer %d cannot be found, no action for removing").fmt(srv_removed));
}
}
config_ = new_config;
}
CPtr<CResponseMsg> CRaftServer::handle_extended_msg(CRequestMessage& req) {
switch (req.GetType())
{
case EMsgType::add_server_request:
return handle_add_srv_req(req);
case EMsgType::remove_server_request:
return handle_rm_srv_req(req);
case EMsgType::sync_log_request:
return handle_log_sync_req(req);
case EMsgType::join_cluster_request:
return handle_join_cluster_req(req);
case EMsgType::leave_cluster_request:
return handle_leave_cluster_req(req);
case EMsgType::install_snapshot_request:
return handle_install_snapshot_req(req);
default:
l_.Error(sstrfmt("receive an unknown request %s, for safety, step down.").fmt(__msg_type_str[req.GetType()]));
ctx_->m_StateManager.SystemExit(-1);
::exit(-1);
break;
}
return CPtr<CResponseMsg>();
}
CPtr<CResponseMsg> CRaftServer::handle_install_snapshot_req(CRequestMessage& req) {
if (req.GetTerm() == state_->GetTerm() && !catching_up_) {
if (role_ == EServerRole::candidate) {
become_follower();
}
else if (role_ == EServerRole::leader) {
l_.Error(lstrfmt("Receive InstallSnapshotRequest from another leader(%d) with same term, there must be a bug, server exits").fmt(req.GetSrc()));
ctx_->m_StateManager.SystemExit(-1);
::exit(-1);
return CPtr<CResponseMsg>();
}
else {
restart_election_timer();
}
}
CPtr<CResponseMsg> resp(cs_new<CResponseMsg>(state_->GetTerm(), EMsgType::install_snapshot_response, id_, req.GetSrc()));
if (!catching_up_ && req.GetTerm() < state_->GetTerm()) {
l_.Info("received an install snapshot request which has lower term than this server, decline the request");
return resp;
}
std::vector<CPtr<CLogEntry>>& entries(req.log_entries());
if (entries.size() != 1 || entries[0]->GetType() != ELogValueType::e_SnapshotSyncRequest) {
l_.Warning("Receive an invalid InstallSnapshotRequest due to bad log entries or bad log entry value");
return resp;
}
CPtr<CSnapshotSyncRequest> sync_req(CSnapshotSyncRequest::Deserialize(entries[0]->GetBuffer()));
if (sync_req->GetSnapshot().GetLastLogIndex() <= state_->GetCommitIndex()) {
l_.Warning(sstrfmt("received a snapshot (%llu) that is older than current log store").fmt(sync_req->GetSnapshot().GetLastLogIndex()));
return resp;
}
if (handle_snapshot_sync_req(*sync_req)) {
resp->Accept(sync_req->GetOffset() + sync_req->GetData().size());
}
return resp;
}
bool CRaftServer::handle_snapshot_sync_req(CSnapshotSyncRequest& req) {
try {
state_machine_.SaveSnapshotData(req.GetSnapshot(), req.GetOffset(), req.GetData());
if (req.IsDone()) {
// Only follower will run this piece of code, but let's check it again
if (role_ != EServerRole::follower) {
l_.Error("bad server role for applying a snapshot, exit for debugging");
ctx_->m_StateManager.SystemExit(-1);
::exit(-1);
}
l_.Debug("sucessfully receive a snapshot from leader");
if (log_store_->Compact(req.GetSnapshot().GetLastLogIndex())) {
// The state machine will not be able to commit anything before the snapshot is applied, so make this synchronously
// with election timer stopped as usually applying a snapshot may take a very long time
stop_election_timer();
l_.Info("successfully compact the log store, will now ask the statemachine to apply the snapshot");
if (!state_machine_.ApplySnapshot(req.GetSnapshot())) {
l_.Info("failed to apply the snapshot after log compacted, to ensure the safety, will shutdown the system");
ctx_->m_StateManager.SystemExit(-1);
::exit(-1);
return false;
}
reconfigure(req.GetSnapshot().GetLastConfig());
ctx_->m_StateManager.SaveConfig(*config_);
state_->SetCommitIndex(req.GetSnapshot().GetLastLogIndex());
quick_commit_idx_ = req.GetSnapshot().GetLastLogIndex();
ctx_->m_StateManager.SaveState(*state_);
restart_election_timer();
l_.Info("snapshot is successfully applied");
}
else {
l_.Error("failed to compact the log store after a snapshot is received, will ask the leader to retry");
return false;
}
}
}
catch (...) {
l_.Error("failed to handle snapshot installation due to system errors");
ctx_->m_StateManager.SystemExit(-1);
::exit(-1);
return false;
}
return true;
}
void CRaftServer::handle_ext_resp(CPtr<CResponseMsg>& resp, CPtr<CRpcException>& err) {
recur_lock(lock_);
if (err) {
handle_ext_resp_err(*err);
return;
}
l_.Debug(
lstrfmt("Receive an extended %s message from peer %d with Result=%d, Term=%llu, NextIndex=%llu")
.fmt(
__msg_type_str[resp->GetType()],
resp->GetSrc(),
resp->GetAccepted() ? 1 : 0,
resp->GetTerm(),
resp->GetNextIndex()));
switch (resp->GetType())
{
case EMsgType::sync_log_response:
if (srv_to_join_) {
// we are reusing heartbeat interval value to indicate when to stop retry
srv_to_join_->resume_hb_speed();
srv_to_join_->set_next_log_idx(resp->GetNextIndex());
srv_to_join_->set_matched_idx(resp->GetNextIndex() - 1);
sync_log_to_new_srv(resp->GetNextIndex());
}
break;
case EMsgType::join_cluster_response:
if (srv_to_join_) {
if (resp->GetAccepted()) {
l_.Debug("new server confirms it will join, start syncing logs to it");
sync_log_to_new_srv(1);
}
else {
l_.Debug("new server cannot accept the invitation, give up");
}
}
else {
l_.Debug("no server to join, drop the message");
}
break;
case EMsgType::leave_cluster_response:
if (!resp->GetAccepted()) {
l_.Debug("peer doesn't accept to stepping down, stop proceeding");
return;
}
l_.Debug("peer accepted to stepping down, removing this server from cluster");
rm_srv_from_cluster(resp->GetSrc());
break;
case EMsgType::install_snapshot_response:
{
if (!srv_to_join_) {
l_.Info("no server to join, the response must be very old.");
return;
}
if (!resp->GetAccepted()) {
l_.Info("peer doesn't accept the snapshot installation request");
return;
}
CPtr<CSnapshotSyncContext> sync_ctx = srv_to_join_->get_snapshot_sync_ctx();
if (sync_ctx == nilptr) {
l_.Error("Bug! SnapshotSyncContext must not be null");
ctx_->m_StateManager.SystemExit(-1);
::exit(-1);
return;
}
if (resp->GetNextIndex() >= sync_ctx->GetSnapshot()->Size()) {
// snapshot is done
CPtr<CSnapshot> nil_snap;
l_.Debug("snapshot has been copied and applied to new server, continue to sync logs after snapshot");
srv_to_join_->set_snapshot_in_sync(nil_snap);
srv_to_join_->set_next_log_idx(sync_ctx->GetSnapshot()->GetLastLogIndex() + 1);
srv_to_join_->set_matched_idx(sync_ctx->GetSnapshot()->GetLastLogIndex());
}
else {
sync_ctx->SetOffset(resp->GetNextIndex());
l_.Debug(sstrfmt("continue to send snapshot to new server at offset %llu").fmt(resp->GetNextIndex()));
}
sync_log_to_new_srv(srv_to_join_->get_next_log_idx());
}
break;
default:
l_.Error(lstrfmt("received an unexpected response message type %s, for safety, stepping down").fmt(__msg_type_str[resp->GetType()]));
ctx_->m_StateManager.SystemExit(-1);
::exit(-1);
break;
}
}
void CRaftServer::handle_ext_resp_err(CRpcException& err) {
l_.Debug(lstrfmt("receive an rpc error response from peer server, %s").fmt(err.what()));