-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
peer.rs
6248 lines (5738 loc) · 241 KB
/
peer.rs
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
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
// #[PerformanceCriticalPath]
use std::{
cell::RefCell,
cmp,
collections::VecDeque,
mem,
sync::{
atomic::{AtomicUsize, Ordering},
Arc, Mutex,
},
time::{Duration, Instant},
u64, usize,
};
use bitflags::bitflags;
use bytes::Bytes;
use collections::{HashMap, HashSet};
use crossbeam::{atomic::AtomicCell, channel::TrySendError};
use engine_traits::{
Engines, KvEngine, PerfContext, RaftEngine, Snapshot, WriteBatch, WriteOptions, CF_DEFAULT,
CF_LOCK, CF_WRITE,
};
use error_code::ErrorCodeExt;
use fail::fail_point;
use getset::{Getters, MutGetters};
use keys::{enc_end_key, enc_start_key};
use kvproto::{
errorpb,
kvrpcpb::{DiskFullOpt, ExtraOp as TxnExtraOp},
metapb::{self, PeerRole},
pdpb::PeerStats,
raft_cmdpb::{
self, AdminCmdType, AdminResponse, CmdType, CommitMergeRequest, PutRequest, RaftCmdRequest,
RaftCmdResponse, Request, TransferLeaderRequest, TransferLeaderResponse,
},
raft_serverpb::{
ExtraMessage, ExtraMessageType, MergeState, PeerState, RaftApplyState, RaftMessage,
},
replication_modepb::{
DrAutoSyncState, RegionReplicationState, RegionReplicationStatus, ReplicationMode,
},
};
use parking_lot::RwLockUpgradableReadGuard;
use pd_client::INVALID_ID;
use protobuf::Message;
use raft::{
self,
eraftpb::{self, Entry, EntryType, MessageType},
GetEntriesContext, LightReady, ProgressState, RawNode, Ready, SnapshotStatus, StateRole,
INVALID_INDEX, NO_LIMIT,
};
use rand::seq::SliceRandom;
use smallvec::SmallVec;
use tikv_alloc::trace::TraceEvent;
use tikv_util::{
box_err,
codec::number::decode_u64,
debug, error, info,
sys::disk::DiskUsage,
time::{duration_to_sec, monotonic_raw_now, Instant as TiInstant, InstantExt},
warn,
worker::Scheduler,
Either,
};
use time::{Duration as TimeDuration, Timespec};
use tracker::GLOBAL_TRACKERS;
use txn_types::{TimeStamp, WriteBatchFlags};
use uuid::Uuid;
use super::{
cmd_resp,
local_metrics::RaftMetrics,
metrics::*,
peer_storage::{write_peer_state, CheckApplyingSnapStatus, HandleReadyResult, PeerStorage},
read_queue::{ReadIndexQueue, ReadIndexRequest},
transport::Transport,
util::{
self, check_req_region_epoch, is_initial_msg, AdminCmdEpochState, ChangePeerI,
ConfChangeKind, Lease, LeaseState, NORMAL_REQ_CHECK_CONF_VER, NORMAL_REQ_CHECK_VER,
},
worker::BucketStatsInfo,
DestroyPeerJob, LocalReadContext,
};
use crate::{
coprocessor::{
split_observer::NO_VALID_SPLIT_KEY, CoprocessorHost, RegionChangeEvent, RegionChangeReason,
RoleChange,
},
errors::RAFTSTORE_IS_BUSY,
router::RaftStoreRouter,
store::{
async_io::{read::ReadTask, write::WriteMsg, write_router::WriteRouter},
fsm::{
apply::{self, CatchUpLogs},
store::PollContext,
Apply, ApplyMetrics, ApplyTask, Proposal,
},
hibernate_state::GroupState,
memory::{needs_evict_entry_cache, MEMTRACE_RAFT_ENTRIES},
msg::{CasualMessage, ErrorCallback, RaftCommand},
peer_storage::HandleSnapshotResult,
txn_ext::LocksStatus,
unsafe_recovery::{ForceLeaderState, SnapshotRecoveryState, UnsafeRecoveryState},
util::{admin_cmd_epoch_lookup, RegionReadProgress},
worker::{
CleanupTask, CompactTask, HeartbeatTask, RaftlogGcTask, ReadDelegate, ReadExecutor,
ReadProgress, RegionTask, SplitCheckTask,
},
Callback, Config, GlobalReplicationState, PdTask, ReadCallback, ReadIndexContext,
ReadResponse, TxnExt, WriteCallback, RAFT_INIT_LOG_INDEX,
},
Error, Result,
};
const SHRINK_CACHE_CAPACITY: usize = 64;
// 1s
const MIN_BCAST_WAKE_UP_INTERVAL: u64 = 1_000;
const REGION_READ_PROGRESS_CAP: usize = 128;
#[doc(hidden)]
pub const MAX_COMMITTED_SIZE_PER_READY: u64 = 16 * 1024 * 1024;
/// The returned states of the peer after checking whether it is stale
#[derive(Debug, PartialEq)]
pub enum StaleState {
Valid,
ToValidate,
LeaderMissing,
}
#[derive(Debug)]
pub struct ProposalQueue<C> {
region_id: u64,
peer_id: u64,
queue: VecDeque<Proposal<C>>,
}
impl<C: WriteCallback> ProposalQueue<C> {
pub fn new(region_id: u64, peer_id: u64) -> ProposalQueue<C> {
ProposalQueue {
region_id,
peer_id,
queue: VecDeque::new(),
}
}
/// Find the trackers of given index.
/// Caller should check if term is matched before using trackers.
pub fn find_trackers(&self, index: u64) -> Option<(u64, C::TimeTrackerListRef<'_>)> {
self.queue
.binary_search_by_key(&index, |p: &Proposal<_>| p.index)
.ok()
.map(|i| (self.queue[i].term, self.queue[i].cb.write_trackers()))
}
#[inline]
pub fn queue_mut(&mut self) -> &mut VecDeque<Proposal<C>> {
&mut self.queue
}
pub fn find_propose_time(&self, term: u64, index: u64) -> Option<Timespec> {
self.queue
.binary_search_by_key(&(term, index), |p: &Proposal<_>| (p.term, p.index))
.ok()
.and_then(|i| self.queue[i].propose_time)
}
// Find proposal in front or at the given term and index
pub fn pop(&mut self, term: u64, index: u64) -> Option<Proposal<C>> {
self.queue.pop_front().and_then(|p| {
// Comparing the term first then the index, because the term is
// increasing among all log entries and the index is increasing
// inside a given term
if (p.term, p.index) > (term, index) {
self.queue.push_front(p);
return None;
}
Some(p)
})
}
/// Find proposal at the given term and index and notify stale proposals
/// in front that term and index
pub fn find_proposal(
&mut self,
term: u64,
index: u64,
current_term: u64,
) -> Option<Proposal<C>> {
while let Some(p) = self.pop(term, index) {
if p.term == term {
if p.index == index {
return if p.cb.is_none() { None } else { Some(p) };
} else {
panic!(
"[region {}] {} unexpected callback at term {}, found index {}, expected {}",
self.region_id, self.peer_id, term, p.index, index
);
}
} else {
apply::notify_stale_req(current_term, p.cb);
}
}
None
}
#[inline]
pub fn oldest(&self) -> Option<&Proposal<C>> {
self.queue.front()
}
pub fn push(&mut self, p: Proposal<C>) {
if let Some(f) = self.queue.back() {
// The term must be increasing among all log entries and the index
// must be increasing inside a given term
assert!((p.term, p.index) > (f.term, f.index));
}
self.queue.push_back(p);
}
pub fn is_empty(&self) -> bool {
self.queue.is_empty()
}
pub fn gc(&mut self) {
if self.queue.capacity() > SHRINK_CACHE_CAPACITY && self.queue.len() < SHRINK_CACHE_CAPACITY
{
self.queue.shrink_to_fit();
}
}
pub fn back(&self) -> Option<&Proposal<C>> {
self.queue.back()
}
}
bitflags! {
// TODO: maybe declare it as protobuf struct is better.
/// A bitmap contains some useful flags when dealing with `eraftpb::Entry`.
pub struct ProposalContext: u8 {
const SYNC_LOG = 0b0000_0001;
const SPLIT = 0b0000_0010;
const PREPARE_MERGE = 0b0000_0100;
const COMMIT_MERGE = 0b0000_1000;
}
}
impl ProposalContext {
/// Converts itself to a vector.
pub fn to_vec(self) -> Vec<u8> {
if self.is_empty() {
return vec![];
}
let ctx = self.bits();
vec![ctx]
}
/// Initializes a `ProposalContext` from a byte slice.
pub fn from_bytes(ctx: &[u8]) -> ProposalContext {
if ctx.is_empty() {
ProposalContext::empty()
} else if ctx.len() == 1 {
ProposalContext::from_bits_truncate(ctx[0])
} else {
panic!("invalid ProposalContext {:?}", ctx);
}
}
}
/// `ConsistencyState` is used for consistency check.
pub struct ConsistencyState {
pub last_check_time: Instant,
// (computed_result_or_to_be_verified, index, hash)
pub index: u64,
pub context: Vec<u8>,
pub hash: Vec<u8>,
}
/// Statistics about raft peer.
#[derive(Default, Clone)]
pub struct PeerStat {
pub written_bytes: u64,
pub written_keys: u64,
}
#[derive(Default, Debug, Clone, Copy)]
pub struct CheckTickResult {
leader: bool,
up_to_date: bool,
reason: &'static str,
}
pub struct ProposedAdminCmd<S: Snapshot> {
cmd_type: AdminCmdType,
epoch_state: AdminCmdEpochState,
index: u64,
cbs: Vec<Callback<S>>,
}
impl<S: Snapshot> ProposedAdminCmd<S> {
fn new(
cmd_type: AdminCmdType,
epoch_state: AdminCmdEpochState,
index: u64,
) -> ProposedAdminCmd<S> {
ProposedAdminCmd {
cmd_type,
epoch_state,
index,
cbs: Vec::new(),
}
}
}
struct CmdEpochChecker<S: Snapshot> {
// Although it's a deque, because of the characteristics of the settings from
// `admin_cmd_epoch_lookup`, the max size of admin cmd is 2, i.e. split/merge and change
// peer.
proposed_admin_cmd: VecDeque<ProposedAdminCmd<S>>,
term: u64,
}
impl<S: Snapshot> Default for CmdEpochChecker<S> {
fn default() -> CmdEpochChecker<S> {
CmdEpochChecker {
proposed_admin_cmd: VecDeque::new(),
term: 0,
}
}
}
impl<S: Snapshot> CmdEpochChecker<S> {
fn maybe_update_term(&mut self, term: u64) {
assert!(term >= self.term);
if term > self.term {
self.term = term;
for cmd in self.proposed_admin_cmd.drain(..) {
for cb in cmd.cbs {
apply::notify_stale_req(term, cb);
}
}
}
}
/// Check if the proposal can be proposed on the basis of its epoch and
/// previous proposed admin cmds.
///
/// Returns None if passing the epoch check, otherwise returns a index which
/// is the last admin cmd index conflicted with this proposal.
fn propose_check_epoch(&mut self, req: &RaftCmdRequest, term: u64) -> Option<u64> {
self.maybe_update_term(term);
let (check_ver, check_conf_ver) = if !req.has_admin_request() {
(NORMAL_REQ_CHECK_VER, NORMAL_REQ_CHECK_CONF_VER)
} else {
let cmd_type = req.get_admin_request().get_cmd_type();
let epoch_state = admin_cmd_epoch_lookup(cmd_type);
(epoch_state.check_ver, epoch_state.check_conf_ver)
};
self.last_conflict_index(check_ver, check_conf_ver)
}
fn post_propose(&mut self, cmd_type: AdminCmdType, index: u64, term: u64) {
self.maybe_update_term(term);
let epoch_state = admin_cmd_epoch_lookup(cmd_type);
assert!(
self.last_conflict_index(epoch_state.check_ver, epoch_state.check_conf_ver)
.is_none()
);
if epoch_state.change_conf_ver || epoch_state.change_ver {
if let Some(cmd) = self.proposed_admin_cmd.back() {
assert!(cmd.index < index);
}
self.proposed_admin_cmd
.push_back(ProposedAdminCmd::new(cmd_type, epoch_state, index));
}
}
fn last_conflict_index(&self, check_ver: bool, check_conf_ver: bool) -> Option<u64> {
self.proposed_admin_cmd
.iter()
.rev()
.find(|cmd| {
(check_ver && cmd.epoch_state.change_ver)
|| (check_conf_ver && cmd.epoch_state.change_conf_ver)
})
.map(|cmd| cmd.index)
}
/// Returns the last proposed admin cmd index.
///
/// Note that the cmd of this type must change epoch otherwise it can not be
/// recorded to `proposed_admin_cmd`.
fn last_cmd_index(&mut self, cmd_type: AdminCmdType) -> Option<u64> {
self.proposed_admin_cmd
.iter()
.rev()
.find(|cmd| cmd.cmd_type == cmd_type)
.map(|cmd| cmd.index)
}
fn advance_apply(&mut self, index: u64, term: u64, region: &metapb::Region) {
self.maybe_update_term(term);
while !self.proposed_admin_cmd.is_empty() {
let cmd = self.proposed_admin_cmd.front_mut().unwrap();
if cmd.index <= index {
for cb in cmd.cbs.drain(..) {
let mut resp = cmd_resp::new_error(Error::EpochNotMatch(
format!(
"current epoch of region {} is {:?}",
region.get_id(),
region.get_region_epoch(),
),
vec![region.to_owned()],
));
cmd_resp::bind_term(&mut resp, term);
cb.report_error(resp);
}
} else {
break;
}
self.proposed_admin_cmd.pop_front();
}
}
fn attach_to_conflict_cmd(&mut self, index: u64, cb: Callback<S>) {
if let Some(cmd) = self
.proposed_admin_cmd
.iter_mut()
.rev()
.find(|cmd| cmd.index == index)
{
cmd.cbs.push(cb);
} else {
panic!(
"index {} can not found in proposed_admin_cmd, callback {:?}",
index, cb
);
}
}
}
impl<S: Snapshot> Drop for CmdEpochChecker<S> {
fn drop(&mut self) {
if tikv_util::thread_group::is_shutdown(!cfg!(test)) {
for mut state in self.proposed_admin_cmd.drain(..) {
state.cbs.clear();
}
} else {
for state in self.proposed_admin_cmd.drain(..) {
for cb in state.cbs {
apply::notify_stale_req(self.term, cb);
}
}
}
}
}
#[derive(PartialEq, Debug)]
pub struct ApplySnapshotContext {
/// The number of ready which has a snapshot.
pub ready_number: u64,
/// Whether this snapshot is scheduled.
pub scheduled: bool,
/// The message should be sent after snapshot is applied.
pub msgs: Vec<eraftpb::Message>,
pub persist_res: Option<PersistSnapshotResult>,
}
#[derive(PartialEq, Debug)]
pub struct PersistSnapshotResult {
/// prev_region is the region before snapshot applied.
pub prev_region: metapb::Region,
pub region: metapb::Region,
pub destroy_regions: Vec<metapb::Region>,
pub for_witness: bool,
}
#[derive(Debug)]
pub struct UnpersistedReady {
/// Number of ready.
pub number: u64,
/// Max number of following ready whose data to be persisted is empty.
pub max_empty_number: u64,
pub raft_msgs: Vec<Vec<eraftpb::Message>>,
}
pub struct ReadyResult {
pub state_role: Option<StateRole>,
pub has_new_entries: bool,
pub has_write_ready: bool,
}
// Propose a read index request to the raft group, return the request id and
// whether this request had dropped silently
// #[RaftstoreCommon], copied from Peer::propose_read_index
pub fn propose_read_index<T: raft::Storage>(
raft_group: &mut RawNode<T>,
request: Option<&raft_cmdpb::ReadIndexRequest>,
) -> (Uuid, bool) {
let last_pending_read_count = raft_group.raft.pending_read_count();
let last_ready_read_count = raft_group.raft.ready_read_count();
let id = Uuid::new_v4();
raft_group.read_index(ReadIndexContext::fields_to_bytes(id, request, None));
let pending_read_count = raft_group.raft.pending_read_count();
let ready_read_count = raft_group.raft.ready_read_count();
(
id,
pending_read_count == last_pending_read_count && ready_read_count == last_ready_read_count,
)
}
pub fn should_renew_lease(
is_leader: bool,
is_splitting: bool,
is_merging: bool,
has_force_leader: bool,
) -> bool {
// A splitting leader should not renew its lease.
// Because we split regions asynchronous, the leader may read stale results
// if splitting runs slow on the leader.
// A merging leader should not renew its lease.
// Because we merge regions asynchronous, the leader may read stale results
// if commit merge runs slow on sibling peers.
// when it enters force leader mode, should not renew lease.
is_leader && !is_splitting && !is_merging && !has_force_leader
}
// check if the request can be amended to the last pending read?
// return true if it can.
pub fn can_amend_read<C>(
last_pending_read: Option<&ReadIndexRequest<C>>,
req: &RaftCmdRequest,
lease_state: LeaseState,
max_lease: TimeDuration,
now: Timespec,
) -> bool {
match lease_state {
// Here, combining the new read request with the previous one even if the lease expired
// is ok because in this case, the previous read index must be sent out with a valid
// lease instead of a suspect lease. So there must no pending transfer-leader
// proposals before or after the previous read index, and the lease can be renewed
// when get heartbeat responses.
LeaseState::Valid | LeaseState::Expired => {
if let Some(read) = last_pending_read {
let is_read_index_request = req
.get_requests()
.get(0)
.map(|req| req.has_read_index())
.unwrap_or_default();
// A read index request or a read with addition request always needs the
// response of checking memory lock for async
// commit, so we cannot apply the optimization here
if !is_read_index_request
&& read.addition_request.is_none()
&& read.propose_time + max_lease > now
{
return true;
}
}
}
// If the current lease is suspect, new read requests can't be appended into
// `pending_reads` because if the leader is transferred, the latest read could
// be dirty.
_ => {}
}
false
}
/// The SplitCheckTrigger maintains the internal status to determine
/// if a split check task should be triggered.
#[derive(Default, Debug)]
pub struct SplitCheckTrigger {
/// An inaccurate difference in region size since last reset.
/// It is used to decide whether split check is needed.
size_diff_hint: u64,
/// An inaccurate difference in region size after compaction.
/// It is used to trigger check split to update approximate size and keys
/// after space reclamation of deleted entries.
pub compaction_declined_bytes: u64,
/// Approximate size of the region.
pub approximate_size: Option<u64>,
may_split_size: Option<bool>,
/// Approximate keys of the region.
pub approximate_keys: Option<u64>,
may_split_keys: Option<bool>,
/// Whether this region has scheduled a split check task. If we just
/// splitted the region or ingested one file which may be overlapped
/// with the existed data, reset the flag so that the region can be
/// splitted again.
may_skip_split_check: bool,
}
impl SplitCheckTrigger {
pub fn should_skip(&self, threshold: u64) -> bool {
self.may_skip_split_check
&& self.compaction_declined_bytes < threshold
&& self.size_diff_hint < threshold
}
pub fn post_triggered(&mut self) {
self.size_diff_hint = 0;
self.compaction_declined_bytes = 0;
// The task is scheduled, the next tick may skip it only when the size and keys
// are small.
// If either size or keys are big enough to do a split,
// keep split check tick until split is done
if !matches!(self.may_split_size, Some(true)) && !matches!(self.may_split_keys, Some(true))
{
self.may_skip_split_check = true;
}
}
pub fn post_split(&mut self) {
self.size_diff_hint = 0;
self.may_split_keys = None;
self.may_split_size = None;
// It's not correct anymore, so set it to false to schedule a split check task.
self.may_skip_split_check = false;
}
pub fn add_size_diff(&mut self, size_diff: i64) {
let diff = self.size_diff_hint as i64 + size_diff;
self.size_diff_hint = cmp::max(diff, 0) as u64;
}
pub fn reset_skip_check(&mut self) {
self.may_skip_split_check = false;
}
pub fn on_clear_region_size(&mut self) {
self.approximate_size = None;
self.approximate_keys = None;
self.may_split_size = None;
self.may_split_keys = None;
self.may_skip_split_check = false;
}
pub fn on_approximate_region_size(&mut self, size: Option<u64>, splitable: Option<bool>) {
// If size is none, it means no estimated size
if size.is_some() {
self.approximate_size = size;
}
if splitable.is_some() {
self.may_split_size = splitable;
}
// If the region is truly splitable,
// may_skip_split_check should be false
if matches!(splitable, Some(true)) {
self.may_skip_split_check = false;
}
}
pub fn on_approximate_region_keys(&mut self, keys: Option<u64>, splitable: Option<bool>) {
// if keys is none, it means no estimated keys
if keys.is_some() {
self.approximate_keys = keys;
}
if splitable.is_some() {
self.may_split_keys = splitable;
}
// If the region is truly splitable,
// may_skip_split_check should be false
if matches!(splitable, Some(true)) {
self.may_skip_split_check = false;
}
}
pub fn on_ingest_sst_result(&mut self, size: u64, keys: u64) {
self.approximate_size = Some(self.approximate_size.unwrap_or_default() + size);
self.approximate_keys = Some(self.approximate_keys.unwrap_or_default() + keys);
// The ingested file may be overlapped with the data in engine, so we need to
// check it again to get the accurate value.
self.may_skip_split_check = false;
}
}
#[derive(Getters, MutGetters)]
pub struct Peer<EK, ER>
where
EK: KvEngine,
ER: RaftEngine,
{
/// The ID of the Region which this Peer belongs to.
region_id: u64,
// TODO: remove it once panic!() support slog fields.
/// Peer_tag, "[region <region_id>] <peer_id>"
pub tag: String,
/// The Peer meta information.
pub peer: metapb::Peer,
/// The Raft state machine of this Peer.
pub raft_group: RawNode<PeerStorage<EK, ER>>,
/// The online configurable Raft configurations
raft_max_inflight_msgs: usize,
/// The cache of meta information for Region's other Peers.
peer_cache: RefCell<HashMap<u64, metapb::Peer>>,
/// Record the last instant of each peer's heartbeat response.
pub peer_heartbeats: HashMap<u64, Instant>,
/// Record the waiting data status of each follower or learner peer.
pub wait_data_peers: Vec<u64>,
/// This peer is created by a raft message from `create_by_peer`.
create_by_peer: Option<metapb::Peer>,
proposals: ProposalQueue<Callback<EK::Snapshot>>,
leader_missing_time: Option<Instant>,
#[getset(get = "pub", get_mut = "pub")]
leader_lease: Lease,
pending_reads: ReadIndexQueue<Callback<EK::Snapshot>>,
/// Threshold of long uncommitted proposals.
///
/// Note that this is a dynamically changing value. Check the
/// `has_long_uncommitted_proposals` method for details.
long_uncommitted_threshold: Duration,
/// If it fails to send messages to leader.
pub leader_unreachable: bool,
/// Indicates whether the peer should be woken up.
pub should_wake_up: bool,
/// Whether this peer is destroyed asynchronously.
/// If it's true,
/// - when merging, its data in storeMeta will be removed early by the
/// target peer.
/// - all read requests must be rejected.
pub pending_remove: bool,
/// Currently it's used to indicate whether the witness -> non-witess
/// convertion operation is complete. The meaning of completion is that
/// this peer must contain the applied data, then PD can consider that
/// the conversion operation is complete, and can continue to schedule
/// other operators to prevent the existence of multiple witnesses in
/// the same time period.
pub wait_data: bool,
/// When the witness becomes non-witness, it need to actively request a
/// snapshot from the leader, but the request may fail, so we need to save
/// the request index for retrying.
pub request_index: u64,
/// It's used to identify the situation where the region worker is
/// generating and sending snapshots when the newly elected leader by Raft
/// applies the switch witness cmd which commited before the election. This
/// flag will prevent immediate data clearing and will be cleared after
/// the successful transfer of leadership.
pub delay_clean_data: bool,
/// When the witness becomes non-witness, it need to actively request a
/// snapshot from the leader, In order to avoid log lag, we need to reject
/// the leader's `MsgAppend` request unless the `term` of the `last index`
/// is less than the peer's current `term`.
pub should_reject_msgappend: bool,
/// Force leader state is only used in online recovery when the majority of
/// peers are missing. In this state, it forces one peer to become leader
/// out of accordance with Raft election rule, and forbids any
/// read/write proposals. With that, we can further propose remove
/// failed-nodes conf-change, to make the Raft group forms majority and
/// works normally later on.
///
/// For details, see the comment of `ForceLeaderState`.
pub force_leader: Option<ForceLeaderState>,
/// Record the instants of peers being added into the configuration.
/// Remove them after they are not pending any more.
pub peers_start_pending_time: Vec<(u64, Instant)>,
/// A inaccurate cache about which peer is marked as down.
down_peer_ids: Vec<u64>,
/// the split check trigger
pub split_check_trigger: SplitCheckTrigger,
/// The count of deleted keys since last reset.
delete_keys_hint: u64,
/// The state for consistency check.
pub consistency_state: ConsistencyState,
/// The counter records pending snapshot requests.
pub pending_request_snapshot_count: Arc<AtomicUsize>,
/// The index of last scheduled committed raft log.
pub last_applying_idx: u64,
/// The index of last compacted raft log. It is used for the next compact
/// log task.
pub last_compacted_idx: u64,
/// Record the time of the last raft log compact, the witness should query
/// the leader periodically whether `voter_replicated_index` is updated
/// if CompactLog admin command isn't triggered for a while.
pub last_compacted_time: Instant,
/// When the peer is witness, and there is any voter lagging behind, the
/// log truncation of the witness shouldn't be triggered even if it's
/// force mode, and this item will be set to `true`, after all pending
/// compact cmds have been handled, it will be set to `false`.
pub has_pending_compact_cmd: bool,
/// The index of the latest urgent proposal index.
last_urgent_proposal_idx: u64,
/// The index of the latest committed split command.
last_committed_split_idx: u64,
/// The index of last sent snapshot
last_sent_snapshot_idx: u64,
/// Approximate size of logs that is applied but not compacted yet.
pub raft_log_size_hint: u64,
/// The write fence index.
/// If there are pessimistic locks, PrepareMerge can be proposed after
/// applying to this index. When a pending PrepareMerge exists, no more
/// write commands should be proposed. This avoids proposing pessimistic
/// locks that are already deleted before PrepareMerge.
pub prepare_merge_fence: u64,
pub pending_prepare_merge: Option<RaftCmdRequest>,
/// The index of the latest committed prepare merge command.
last_committed_prepare_merge_idx: u64,
/// The merge related state. It indicates this Peer is in merging.
pub pending_merge_state: Option<MergeState>,
/// The rollback merge proposal can be proposed only when the number
/// of peers is greater than the majority of all peers.
/// There are more details in the annotation above
/// `test_node_merge_write_data_to_source_region_after_merging`
/// The peers who want to rollback merge.
pub want_rollback_merge_peers: HashSet<u64>,
/// Source region is catching up logs for merge.
pub catch_up_logs: Option<CatchUpLogs>,
/// Write Statistics for PD to schedule hot spot.
pub peer_stat: PeerStat,
/// Time of the last attempt to wake up inactive leader.
pub bcast_wake_up_time: Option<TiInstant>,
/// Current replication mode version.
pub replication_mode_version: u64,
/// The required replication state at current version.
pub dr_auto_sync_state: DrAutoSyncState,
/// A flag that caches sync state. It's set to true when required
/// replication state is reached for current region.
pub replication_sync: bool,
/// The known newest conf version and its corresponding peer list
/// Send to these peers to check whether itself is stale.
pub check_stale_conf_ver: u64,
pub check_stale_peers: Vec<metapb::Peer>,
/// Whether this peer is created by replication and is the first
/// one of this region on local store.
pub local_first_replicate: bool,
pub txn_extra_op: Arc<AtomicCell<TxnExtraOp>>,
/// Transaction extensions related to this peer.
pub txn_ext: Arc<TxnExt>,
/// Check whether this proposal can be proposed based on its epoch.
cmd_epoch_checker: CmdEpochChecker<EK::Snapshot>,
// disk full peer set.
pub disk_full_peers: DiskFullPeers,
// show whether an already disk full TiKV appears in the potential majority set.
pub dangerous_majority_set: bool,
// region merge logic need to be broadcast to all followers when disk full happens.
pub has_region_merge_proposal: bool,
pub region_merge_proposal_index: u64,
pub read_progress: Arc<RegionReadProgress>,
pub memtrace_raft_entries: usize,
/// Used for sending write msg.
write_router: WriteRouter<EK, ER>,
/// Used for async write io.
unpersisted_readies: VecDeque<UnpersistedReady>,
/// The message count in `unpersisted_readies` for memory caculation.
unpersisted_message_count: usize,
/// Used for sync write io.
unpersisted_ready: Option<Ready>,
/// The last known persisted number.
persisted_number: u64,
/// The context of applying snapshot.
apply_snap_ctx: Option<ApplySnapshotContext>,
/// region buckets info in this region.
region_buckets_info: BucketStatsInfo,
/// lead_transferee if this peer(leader) is in a leadership transferring.
pub lead_transferee: u64,
pub unsafe_recovery_state: Option<UnsafeRecoveryState>,
pub snapshot_recovery_state: Option<SnapshotRecoveryState>,
last_record_safe_point: u64,
}
impl<EK, ER> Peer<EK, ER>
where
EK: KvEngine,
ER: RaftEngine,
{
pub fn new(
store_id: u64,
cfg: &Config,
region_scheduler: Scheduler<RegionTask<EK::Snapshot>>,
raftlog_fetch_scheduler: Scheduler<ReadTask<EK>>,
engines: Engines<EK, ER>,
region: &metapb::Region,
peer: metapb::Peer,
wait_data: bool,
create_by_peer: Option<metapb::Peer>,
) -> Result<Peer<EK, ER>> {
let peer_id = peer.get_id();
if peer_id == raft::INVALID_ID {
return Err(box_err!("invalid peer id"));
}
let tag = format!("[region {}] {}", region.get_id(), peer.get_id());
let ps = PeerStorage::new(
engines,
region,
region_scheduler,
raftlog_fetch_scheduler,
peer.get_id(),
tag.clone(),
)?;
let applied_index = ps.applied_index();
let raft_cfg = raft::Config {
id: peer.get_id(),
election_tick: cfg.raft_election_timeout_ticks,
heartbeat_tick: cfg.raft_heartbeat_ticks,
min_election_tick: cfg.raft_min_election_timeout_ticks,
max_election_tick: cfg.raft_max_election_timeout_ticks,
max_size_per_msg: cfg.raft_max_size_per_msg.0,
max_inflight_msgs: cfg.raft_max_inflight_msgs,
applied: applied_index,
check_quorum: !cfg.unsafe_disable_check_quorum,
skip_bcast_commit: true,
pre_vote: cfg.prevote,
max_committed_size_per_ready: MAX_COMMITTED_SIZE_PER_READY,
priority: if peer.is_witness { -1 } else { 0 },
..Default::default()
};
let logger = slog_global::get_global().new(slog::o!("region_id" => region.get_id()));
let raft_group = RawNode::new(&raft_cfg, ps, &logger)?;
let last_index = raft_group.store().last_index();
// In order to avoid excessive log accumulation due to the loss of pending
// compaction cmds after the witness is restarted, it will actively pull
// voter_request_index once at start.
let has_pending_compact_cmd = peer.is_witness;
let mut peer = Peer {
peer,
region_id: region.get_id(),
raft_group,
raft_max_inflight_msgs: cfg.raft_max_inflight_msgs,
proposals: ProposalQueue::new(region.get_id(), peer_id),
pending_reads: ReadIndexQueue::new(tag.clone()),
long_uncommitted_threshold: cfg.long_uncommitted_base_threshold.0,
peer_cache: RefCell::new(HashMap::default()),
peer_heartbeats: HashMap::default(),
wait_data_peers: Vec::default(),
create_by_peer,
peers_start_pending_time: vec![],
down_peer_ids: vec![],
split_check_trigger: SplitCheckTrigger::default(),
delete_keys_hint: 0,
leader_unreachable: false,
pending_remove: false,
wait_data,
request_index: last_index,
delay_clean_data: false,
should_reject_msgappend: false,
should_wake_up: false,
force_leader: None,
pending_merge_state: None,
want_rollback_merge_peers: HashSet::default(),
pending_request_snapshot_count: Arc::new(AtomicUsize::new(0)),
prepare_merge_fence: 0,
pending_prepare_merge: None,
last_committed_prepare_merge_idx: 0,
leader_missing_time: Some(Instant::now()),
tag: tag.clone(),
last_applying_idx: applied_index,
last_compacted_idx: 0,
last_compacted_time: Instant::now(),
has_pending_compact_cmd,
last_urgent_proposal_idx: u64::MAX,
last_committed_split_idx: 0,
last_sent_snapshot_idx: 0,
consistency_state: ConsistencyState {
last_check_time: Instant::now(),
index: INVALID_INDEX,
context: vec![],
hash: vec![],
},
raft_log_size_hint: 0,
leader_lease: Lease::new(
cfg.raft_store_max_leader_lease(),
cfg.renew_leader_lease_advance_duration(),