-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
peer_storage.rs
2281 lines (2058 loc) · 82.3 KB
/
peer_storage.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::{Ref, RefCell},
error,
ops::{Deref, DerefMut},
sync::{
atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
mpsc::{self, Receiver, TryRecvError},
Arc,
},
u64,
};
use engine_traits::{Engines, KvEngine, Mutable, Peekable, RaftEngine, RaftLogBatch, CF_RAFT};
use fail::fail_point;
use into_other::into_other;
use keys::{self, enc_end_key, enc_start_key};
use kvproto::{
metapb::{self, Region},
raft_serverpb::{
MergeState, PeerState, RaftApplyState, RaftLocalState, RaftSnapshotData, RegionLocalState,
},
};
use protobuf::Message;
use raft::{
self,
eraftpb::{self, ConfState, Entry, HardState, Snapshot},
Error as RaftError, GetEntriesContext, RaftState, Ready, Storage, StorageError,
};
use rand::Rng;
use tikv_util::{
box_err, box_try, debug, defer, error, info,
store::find_peer_by_id,
time::{Instant, UnixSecs},
warn,
worker::Scheduler,
};
use super::{metrics::*, worker::RegionTask, SnapEntry, SnapKey, SnapManager};
use crate::{
store::{
async_io::{read::ReadTask, write::WriteTask},
entry_storage::EntryStorage,
fsm::GenSnapTask,
peer::PersistSnapshotResult,
util,
},
Error, Result,
};
// The maximum tick interval between precheck requests. The tick interval helps
// prevent sending the precheck requests too aggressively.
const SNAP_GEN_PRECHECK_MAX_TICK_INTERVAL: usize = 5;
// When we create a region peer, we should initialize its log term/index > 0,
// so that we can force the follower peer to sync the snapshot first.
pub const RAFT_INIT_LOG_TERM: u64 = 5;
pub const RAFT_INIT_LOG_INDEX: u64 = 5;
const MAX_SNAP_TRY_CNT: usize = 5;
/// The initial region epoch version.
pub const INIT_EPOCH_VER: u64 = 1;
/// The initial region epoch conf_version.
pub const INIT_EPOCH_CONF_VER: u64 = 1;
pub const JOB_STATUS_PENDING: usize = 0;
pub const JOB_STATUS_RUNNING: usize = 1;
pub const JOB_STATUS_CANCELLING: usize = 2;
pub const JOB_STATUS_CANCELLED: usize = 3;
pub const JOB_STATUS_FINISHED: usize = 4;
pub const JOB_STATUS_FAILED: usize = 5;
/// Possible status returned by `check_applying_snap`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CheckApplyingSnapStatus {
/// A snapshot is just applied.
Success,
/// A snapshot is being applied.
Applying,
/// No snapshot is being applied at all or the snapshot is canceled
Idle,
}
#[derive(Debug)]
pub enum SnapState {
Relax,
Generating {
canceled: Arc<AtomicBool>,
index: Arc<AtomicU64>,
receiver: Receiver<Snapshot>,
},
Applying(Arc<AtomicUsize>),
ApplyAborted,
}
impl PartialEq for SnapState {
fn eq(&self, other: &SnapState) -> bool {
match (self, other) {
(&SnapState::Relax, &SnapState::Relax)
| (&SnapState::ApplyAborted, &SnapState::ApplyAborted)
| (&SnapState::Generating { .. }, &SnapState::Generating { .. }) => true,
(SnapState::Applying(b1), SnapState::Applying(b2)) => {
b1.load(Ordering::Relaxed) == b2.load(Ordering::Relaxed)
}
_ => false,
}
}
}
pub fn storage_error<E>(error: E) -> raft::Error
where
E: Into<Box<dyn error::Error + Send + Sync>>,
{
raft::Error::Store(StorageError::Other(error.into()))
}
impl From<Error> for RaftError {
fn from(err: Error) -> RaftError {
storage_error(err)
}
}
#[derive(PartialEq, Debug)]
pub struct HandleSnapshotResult {
pub msgs: Vec<eraftpb::Message>,
pub snap_region: metapb::Region,
/// The regions whose range are overlapped with this region
pub destroy_regions: Vec<Region>,
/// The first index before applying the snapshot.
pub last_first_index: u64,
pub for_witness: bool,
}
#[derive(PartialEq, Debug)]
pub enum HandleReadyResult {
SendIoTask,
Snapshot(Box<HandleSnapshotResult>), // use boxing to reduce total size of the enum
NoIoTask,
}
pub fn recover_from_applying_state<EK: KvEngine, ER: RaftEngine>(
engines: &Engines<EK, ER>,
raft_wb: &mut ER::LogBatch,
region_id: u64,
) -> Result<()> {
let snapshot_raft_state_key = keys::snapshot_raft_state_key(region_id);
let snapshot_raft_state: RaftLocalState =
match box_try!(engines.kv.get_msg_cf(CF_RAFT, &snapshot_raft_state_key)) {
Some(state) => state,
None => {
return Err(box_err!(
"[region {}] failed to get raftstate from kv engine, \
when recover from applying state",
region_id
));
}
};
let raft_state = box_try!(engines.raft.get_raft_state(region_id)).unwrap_or_default();
// since raft_local_state is written to raft engine, and
// raft write_batch is written after kv write_batch. raft_local_state may wrong
// if restart happen between the two write. so we copy raft_local_state to
// kv engine (snapshot_raft_state), and set
// snapshot_raft_state.hard_state.commit = snapshot_index. after restart, we
// need check commit.
if snapshot_raft_state.get_hard_state().get_commit() > raft_state.get_hard_state().get_commit()
{
// There is a gap between existing raft logs and snapshot. Clean them up.
engines
.raft
.clean(region_id, 0 /* first_index */, &raft_state, raft_wb)?;
raft_wb.put_raft_state(region_id, &snapshot_raft_state)?;
}
Ok(())
}
fn init_raft_state<EK: KvEngine, ER: RaftEngine>(
engines: &Engines<EK, ER>,
region: &Region,
) -> Result<RaftLocalState> {
if let Some(state) = engines.raft.get_raft_state(region.get_id())? {
return Ok(state);
}
let mut raft_state = RaftLocalState::default();
if util::is_region_initialized(region) {
// new split region
raft_state.last_index = RAFT_INIT_LOG_INDEX;
raft_state.mut_hard_state().set_term(RAFT_INIT_LOG_TERM);
raft_state.mut_hard_state().set_commit(RAFT_INIT_LOG_INDEX);
let mut lb = engines.raft.log_batch(0);
lb.put_raft_state(region.get_id(), &raft_state)?;
engines.raft.consume(&mut lb, true)?;
}
Ok(raft_state)
}
fn init_apply_state<EK: KvEngine, ER: RaftEngine>(
engines: &Engines<EK, ER>,
region: &Region,
) -> Result<RaftApplyState> {
Ok(
match engines
.kv
.get_msg_cf(CF_RAFT, &keys::apply_state_key(region.get_id()))?
{
Some(s) => s,
None => {
let mut apply_state = RaftApplyState::default();
if util::is_region_initialized(region) {
apply_state.set_applied_index(RAFT_INIT_LOG_INDEX);
let state = apply_state.mut_truncated_state();
state.set_index(RAFT_INIT_LOG_INDEX);
state.set_term(RAFT_INIT_LOG_TERM);
}
apply_state
}
},
)
}
pub struct PeerStorage<EK, ER>
where
EK: KvEngine,
{
pub engines: Engines<EK, ER>,
peer_id: u64,
peer: Option<metapb::Peer>, // when uninitialized the peer info is unknown.
region: metapb::Region,
snap_state: RefCell<SnapState>,
gen_snap_task: RefCell<Option<GenSnapTask>>,
region_scheduler: Scheduler<RegionTask>,
snap_tried_cnt: RefCell<usize>,
entry_storage: EntryStorage<EK, ER>,
pub tag: String,
}
impl<EK: KvEngine, ER: RaftEngine> Deref for PeerStorage<EK, ER> {
type Target = EntryStorage<EK, ER>;
#[inline]
fn deref(&self) -> &Self::Target {
&self.entry_storage
}
}
impl<EK: KvEngine, ER: RaftEngine> DerefMut for PeerStorage<EK, ER> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.entry_storage
}
}
impl<EK, ER> Storage for PeerStorage<EK, ER>
where
EK: KvEngine,
ER: RaftEngine,
{
fn initial_state(&self) -> raft::Result<RaftState> {
self.initial_state()
}
fn entries(
&self,
low: u64,
high: u64,
max_size: impl Into<Option<u64>>,
context: GetEntriesContext,
) -> raft::Result<Vec<Entry>> {
let max_size = max_size.into();
self.entry_storage
.entries(low, high, max_size.unwrap_or(u64::MAX), context)
}
fn term(&self, idx: u64) -> raft::Result<u64> {
self.entry_storage.term(idx)
}
fn first_index(&self) -> raft::Result<u64> {
Ok(self.entry_storage.first_index())
}
fn last_index(&self) -> raft::Result<u64> {
Ok(self.entry_storage.last_index())
}
fn snapshot(&self, request_index: u64, to: u64) -> raft::Result<Snapshot> {
self.snapshot(request_index, to)
}
}
impl<EK, ER> PeerStorage<EK, ER>
where
EK: KvEngine,
ER: RaftEngine,
{
pub fn new(
engines: Engines<EK, ER>,
region: &metapb::Region,
region_scheduler: Scheduler<RegionTask>,
raftlog_fetch_scheduler: Scheduler<ReadTask<EK>>,
peer_id: u64,
tag: String,
) -> Result<PeerStorage<EK, ER>> {
debug!(
"creating storage on specified path";
"region_id" => region.get_id(),
"peer_id" => peer_id,
"path" => ?engines.kv.path(),
);
let raft_state = init_raft_state(&engines, region)?;
let apply_state = init_apply_state(&engines, region)?;
let entry_storage = EntryStorage::new(
peer_id,
engines.raft.clone(),
raft_state,
apply_state,
region,
raftlog_fetch_scheduler,
)?;
Ok(PeerStorage {
engines,
peer_id,
peer: find_peer_by_id(region, peer_id).cloned(),
region: region.clone(),
snap_state: RefCell::new(SnapState::Relax),
gen_snap_task: RefCell::new(None),
region_scheduler,
snap_tried_cnt: RefCell::new(0),
tag,
entry_storage,
})
}
pub fn is_initialized(&self) -> bool {
util::is_region_initialized(self.region())
}
pub fn initial_state(&self) -> raft::Result<RaftState> {
let hard_state = self.raft_state().get_hard_state().clone();
if hard_state == HardState::default() {
assert!(
!self.is_initialized(),
"peer for region {:?} is initialized but local state {:?} has empty hard \
state",
self.region,
self.raft_state()
);
return Ok(RaftState::new(hard_state, ConfState::default()));
}
Ok(RaftState::new(
hard_state,
util::conf_state_from_region(self.region()),
))
}
#[inline]
pub fn region(&self) -> &metapb::Region {
&self.region
}
#[inline]
pub fn set_region(&mut self, region: metapb::Region) {
self.peer = find_peer_by_id(®ion, self.peer_id).cloned();
self.region = region;
}
#[inline]
pub fn raw_snapshot(&self) -> EK::Snapshot {
self.engines.kv.snapshot()
}
#[inline]
pub fn save_snapshot_raft_state_to(
&self,
snapshot_index: u64,
kv_wb: &mut impl Mutable,
) -> Result<()> {
let mut snapshot_raft_state = self.raft_state().clone();
snapshot_raft_state
.mut_hard_state()
.set_commit(snapshot_index);
snapshot_raft_state.set_last_index(snapshot_index);
kv_wb.put_msg_cf(
CF_RAFT,
&keys::snapshot_raft_state_key(self.region.get_id()),
&snapshot_raft_state,
)?;
Ok(())
}
#[inline]
pub fn save_apply_state_to(&self, kv_wb: &mut impl Mutable) -> Result<()> {
kv_wb.put_msg_cf(
CF_RAFT,
&keys::apply_state_key(self.region.get_id()),
self.apply_state(),
)?;
Ok(())
}
fn validate_snap(&self, snap: &Snapshot, request_index: u64) -> bool {
let idx = snap.get_metadata().get_index();
if idx < self.truncated_index() || idx < request_index {
// stale snapshot, should generate again.
info!(
"snapshot is stale, generate again";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"snap_index" => idx,
"truncated_index" => self.truncated_index(),
"request_index" => request_index,
);
STORE_SNAPSHOT_VALIDATION_FAILURE_COUNTER.stale.inc();
return false;
}
let mut snap_data = RaftSnapshotData::default();
if let Err(e) = snap_data.merge_from_bytes(snap.get_data()) {
error!(
"failed to decode snapshot, it may be corrupted";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"err" => ?e,
);
STORE_SNAPSHOT_VALIDATION_FAILURE_COUNTER.decode.inc();
return false;
}
let snap_epoch = snap_data.get_region().get_region_epoch();
let latest_epoch = self.region().get_region_epoch();
if snap_epoch.get_conf_ver() < latest_epoch.get_conf_ver() {
info!(
"snapshot epoch is stale";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"snap_epoch" => ?snap_epoch,
"latest_epoch" => ?latest_epoch,
);
STORE_SNAPSHOT_VALIDATION_FAILURE_COUNTER.epoch.inc();
return false;
}
true
}
/// Gets a snapshot. Returns `SnapshotTemporarilyUnavailable` if there is no
/// available snapshot.
pub fn snapshot(&self, request_index: u64, to: u64) -> raft::Result<Snapshot> {
fail_point!("ignore generate snapshot", self.peer_id == 1, |_| {
Err(raft::Error::Store(
raft::StorageError::SnapshotTemporarilyUnavailable,
))
});
if self.peer.as_ref().unwrap().is_witness {
// witness could be the leader for a while, do not generate snapshot now
return Err(raft::Error::Store(
raft::StorageError::SnapshotTemporarilyUnavailable,
));
}
if find_peer_by_id(&self.region, to).map_or(false, |p| p.is_witness) {
// Although we always sending snapshot task behind apply task to get latest
// snapshot, we can't use `last_applying_idx` here, as below the judgment
// condition will generate an witness snapshot directly, the new non-witness
// will ingore this mismatch snapshot and can't request snapshot successfully
// again.
if self.applied_index() < request_index {
// It may be a request from non-witness. In order to avoid generating mismatch
// snapshots, wait for apply non-witness to complete
return Err(raft::Error::Store(
raft::StorageError::SnapshotTemporarilyUnavailable,
));
}
// generate an empty snapshot for witness directly
return Ok(util::new_empty_snapshot(
self.region.clone(),
self.applied_index(),
self.applied_term(),
true, // for witness
));
}
let mut snap_state = self.snap_state.borrow_mut();
let mut tried_cnt = self.snap_tried_cnt.borrow_mut();
let mut tried = false;
let mut last_canceled = false;
if let SnapState::Generating {
canceled, receiver, ..
} = &*snap_state
{
tried = true;
last_canceled = canceled.load(Ordering::SeqCst);
match receiver.try_recv() {
Err(TryRecvError::Empty) => {
return Err(raft::Error::Store(
raft::StorageError::SnapshotTemporarilyUnavailable,
));
}
Ok(s) if !last_canceled => {
*snap_state = SnapState::Relax;
*tried_cnt = 0;
if self.validate_snap(&s, request_index) {
info!("start sending snapshot"; "region_id" => self.region.get_id(),
"peer_id" => self.peer_id, "request_peer" => to,);
return Ok(s);
}
}
Err(TryRecvError::Disconnected) | Ok(_) => {
*snap_state = SnapState::Relax;
warn!(
"failed to try generating snapshot";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"times" => *tried_cnt,
"request_peer" => to,
);
}
}
}
if SnapState::Relax != *snap_state {
panic!("{} unexpected state: {:?}", self.tag, *snap_state);
}
match find_peer_by_id(&self.region, to) {
Some(to_peer) => {
let max_snap_try_cnt = (|| {
fail_point!("ignore_snap_try_cnt", |_| usize::MAX);
MAX_SNAP_TRY_CNT
})();
if *tried_cnt >= max_snap_try_cnt {
let cnt = *tried_cnt;
*tried_cnt = 0;
return Err(raft::Error::Store(box_err!(
"failed to get snapshot after {} times",
cnt
)));
}
if !tried || !last_canceled {
*tried_cnt += 1;
}
info!(
"requesting snapshot";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"request_index" => request_index,
"request_peer" => to,
);
let (sender, receiver) = mpsc::sync_channel(1);
let canceled = Arc::new(AtomicBool::new(false));
let index = Arc::new(AtomicU64::new(0));
*snap_state = SnapState::Generating {
canceled: canceled.clone(),
index: index.clone(),
receiver,
};
let task = GenSnapTask::new(
self.region.get_id(),
index,
canceled,
sender,
to_peer.clone(),
);
self.set_gen_snap_task(task);
}
None => {
warn!(
"failed to find peer";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"times" => *tried_cnt,
"request_peer" => to,
);
}
}
Err(raft::Error::Store(
raft::StorageError::SnapshotTemporarilyUnavailable,
))
}
pub fn need_gen_snap_precheck(&self) -> Option<metapb::Peer> {
let mut gen_task = self.gen_snap_task.borrow_mut();
let task = gen_task.as_mut()?;
if task.precheck_remaining_ticks == 0 {
// Use random tick counts to space out the requests.
task.precheck_remaining_ticks =
rand::thread_rng().gen_range(1..=SNAP_GEN_PRECHECK_MAX_TICK_INTERVAL);
Some(task.to_peer.clone())
} else {
task.precheck_remaining_ticks -= 1;
None
}
}
pub fn set_gen_snap_task_for_balance(&self) {
if let Some(gen_task) = self.gen_snap_task.borrow_mut().as_mut() {
gen_task.set_for_balance();
}
}
pub fn get_gen_snap_task(&self) -> Ref<'_, Option<GenSnapTask>> {
self.gen_snap_task.borrow()
}
pub fn has_gen_snap_task(&self) -> bool {
self.gen_snap_task.borrow().is_some()
}
pub fn take_gen_snap_task(&self) -> Option<GenSnapTask> {
let mut task = self.gen_snap_task.borrow_mut();
(*task).take()
}
pub fn set_gen_snap_task(&self, task: GenSnapTask) {
let mut gen_snap_task = self.gen_snap_task.borrow_mut();
assert!(gen_snap_task.is_none(), "{:?}", gen_snap_task);
*gen_snap_task = Some(task);
}
pub fn on_compact_raftlog(&mut self, idx: u64) {
self.entry_storage.compact_entry_cache(idx);
self.cancel_generating_snap(Some(idx));
}
// Apply the peer with given snapshot.
pub fn apply_snapshot(
&mut self,
snap: &Snapshot,
task: &mut WriteTask<EK, ER>,
destroy_regions: &[metapb::Region],
) -> Result<(metapb::Region, bool)> {
info!(
"begin to apply snapshot";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
);
let mut snap_data = RaftSnapshotData::default();
snap_data.merge_from_bytes(snap.get_data())?;
let for_witness = snap_data.get_meta().get_for_witness();
let region_id = self.get_region_id();
let region = snap_data.take_region();
if region.get_id() != region_id {
return Err(box_err!(
"mismatch region id {} != {}",
region_id,
region.get_id()
));
}
if task.raft_wb.is_none() {
task.raft_wb = Some(self.engines.raft.log_batch(64));
}
let raft_wb = task.raft_wb.as_mut().unwrap();
let kv_wb = task.extra_write.ensure_v1(|| self.engines.kv.write_batch());
if self.is_initialized() {
// we can only delete the old data when the peer is initialized.
let first_index = self.entry_storage.first_index();
// It's possible that logs between `last_compacted_idx` and `first_index` are
// being deleted in raftlog_gc worker. But it's OK as:
// - If the peer accepts a new snapshot, it must start with an index larger than
// this `first_index`;
// - If the peer accepts new entries after this snapshot or new snapshot, it
// must start with the new applied index, which is larger than `first_index`.
// So new logs won't be deleted by on going raftlog_gc task accidentally.
// It's possible that there will be some logs between `last_compacted_idx` and
// `first_index` are not deleted. So a cleanup task for the range should be
// triggered after applying the snapshot.
self.clear_meta(first_index, kv_wb, raft_wb)?;
}
// Write its source peers' `RegionLocalState` together with itself for atomicity
for r in destroy_regions {
write_peer_state(kv_wb, r, PeerState::Tombstone, None)?;
}
// Witness snapshot is applied atomically as no async applying operation to
// region worker, so no need to set the peer state to `Applying`
let state = if for_witness {
PeerState::Normal
} else {
PeerState::Applying
};
write_peer_state(kv_wb, ®ion, state, None)?;
let snap_index = snap.get_metadata().get_index();
let snap_term = snap.get_metadata().get_term();
self.raft_state_mut().set_last_index(snap_index);
self.set_last_term(snap_term);
self.apply_state_mut().set_applied_index(snap_index);
self.set_applied_term(snap_term);
// The snapshot only contains log which index > applied index, so
// here the truncate state's (index, term) is in snapshot metadata.
self.apply_state_mut()
.mut_truncated_state()
.set_index(snap_index);
self.apply_state_mut()
.mut_truncated_state()
.set_term(snap_term);
// `region` will be updated after persisting.
// Although there is an interval that other metadata are updated while `region`
// is not after handing snapshot from ready, at the time of writing, it's no
// problem for now.
// The reason why the update of `region` is delayed is that we expect `region`
// stays consistent with the one in `StoreMeta::regions` which should be updated
// after persisting due to atomic snapshot and peer create process. So if we can
// fix these issues in future(maybe not?), the `region` and `StoreMeta::regions`
// can updated here immediately.
info!(
"apply snapshot with state ok";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"region" => ?region,
"state" => ?self.apply_state(),
"for_witness" => for_witness,
);
Ok((region, for_witness))
}
/// Delete all meta belong to the region. Results are stored in `wb`.
pub fn clear_meta(
&mut self,
first_index: u64,
kv_wb: &mut EK::WriteBatch,
raft_wb: &mut ER::LogBatch,
) -> Result<()> {
let region_id = self.get_region_id();
clear_meta(
&self.engines,
kv_wb,
raft_wb,
region_id,
first_index,
self.raft_state(),
)?;
self.entry_storage.clear();
Ok(())
}
/// Delete all data belong to the region.
/// If return Err, data may get partial deleted.
pub fn clear_data(&self) -> Result<()> {
let (start_key, end_key) = (enc_start_key(self.region()), enc_end_key(self.region()));
let region_id = self.get_region_id();
box_try!(
self.region_scheduler
.schedule(RegionTask::destroy(region_id, start_key, end_key))
);
Ok(())
}
/// Delete all data that is not covered by `new_region`.
fn clear_extra_data(
&self,
old_region: &metapb::Region,
new_region: &metapb::Region,
) -> Result<()> {
let (old_start_key, old_end_key) = (enc_start_key(old_region), enc_end_key(old_region));
let (new_start_key, new_end_key) = (enc_start_key(new_region), enc_end_key(new_region));
if old_start_key < new_start_key {
box_try!(self.region_scheduler.schedule(RegionTask::destroy(
old_region.get_id(),
old_start_key,
new_start_key
)));
}
if new_end_key < old_end_key {
box_try!(self.region_scheduler.schedule(RegionTask::destroy(
old_region.get_id(),
new_end_key,
old_end_key
)));
}
Ok(())
}
/// Delete all extra split data from the `start_key` to `end_key`.
pub fn clear_extra_split_data(&self, start_key: Vec<u8>, end_key: Vec<u8>) -> Result<()> {
box_try!(self.region_scheduler.schedule(RegionTask::destroy(
self.get_region_id(),
start_key,
end_key
)));
Ok(())
}
pub fn raft_engine(&self) -> &ER {
self.entry_storage.raft_engine()
}
/// Check whether the storage has finished applying snapshot.
#[inline]
pub fn is_applying_snapshot(&self) -> bool {
matches!(*self.snap_state.borrow(), SnapState::Applying(_))
}
#[inline]
pub fn is_generating_snapshot(&self) -> bool {
fail_point!("is_generating_snapshot", |_| { true });
matches!(*self.snap_state.borrow(), SnapState::Generating { .. })
}
/// Check if the storage is applying a snapshot.
#[inline]
pub fn check_applying_snap(&mut self) -> CheckApplyingSnapStatus {
let mut res = CheckApplyingSnapStatus::Idle;
let new_state = match *self.snap_state.borrow() {
SnapState::Applying(ref status) => {
let s = status.load(Ordering::Relaxed);
if s == JOB_STATUS_FINISHED {
res = CheckApplyingSnapStatus::Success;
SnapState::Relax
} else if s == JOB_STATUS_CANCELLED {
SnapState::ApplyAborted
} else if s == JOB_STATUS_FAILED {
// Cleanup region and treat it as tombstone.
warn!("{} applying snapshot failed", self.tag);
SnapState::ApplyAborted
} else {
return CheckApplyingSnapStatus::Applying;
}
}
_ => return res,
};
*self.snap_state.borrow_mut() = new_state;
res
}
/// Cancel applying snapshot, return true if the job can be considered not
/// be run again.
pub fn cancel_applying_snap(&mut self) -> bool {
let is_canceled = match *self.snap_state.borrow() {
SnapState::Applying(ref status) => {
if status
.compare_exchange(
JOB_STATUS_PENDING,
JOB_STATUS_CANCELLING,
Ordering::SeqCst,
Ordering::SeqCst,
)
.is_ok()
{
true
} else if status
.compare_exchange(
JOB_STATUS_RUNNING,
JOB_STATUS_CANCELLING,
Ordering::SeqCst,
Ordering::SeqCst,
)
.is_ok()
{
return false;
} else {
false
}
}
_ => return false,
};
if is_canceled {
*self.snap_state.borrow_mut() = SnapState::ApplyAborted;
return true;
}
// now status can only be JOB_STATUS_CANCELLING, JOB_STATUS_CANCELLED,
// JOB_STATUS_FAILED and JOB_STATUS_FINISHED.
self.check_applying_snap() != CheckApplyingSnapStatus::Applying
}
/// Cancel generating snapshot.
pub fn cancel_generating_snap(&self, compact_to: Option<u64>) {
let snap_state = self.snap_state.borrow();
if let SnapState::Generating {
ref canceled,
ref index,
..
} = *snap_state
{
if !canceled.load(Ordering::SeqCst) {
if let Some(idx) = compact_to {
let snap_index = index.load(Ordering::SeqCst);
// Do not cancel if the snapshot is still valid after the
// compaction.
if snap_index == 0 || idx <= snap_index + 1 {
return;
}
}
canceled.store(true, Ordering::SeqCst);
// Cancel snapshot precheck.
self.take_gen_snap_task();
info!(
"canceled generating snap";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
);
}
}
}
#[inline]
pub fn set_snap_state(&mut self, state: SnapState) {
*self.snap_state.borrow_mut() = state
}
#[inline]
pub fn is_snap_state(&self, state: SnapState) -> bool {
*self.snap_state.borrow() == state
}
pub fn get_region_id(&self) -> u64 {
self.region().get_id()
}
pub fn schedule_applying_snapshot(&mut self) {
let status = Arc::new(AtomicUsize::new(JOB_STATUS_PENDING));
self.set_snap_state(SnapState::Applying(Arc::clone(&status)));
let task = RegionTask::Apply {
region_id: self.get_region_id(),
status,
peer_id: self.peer_id,
create_time: Instant::now_coarse(),
};
// Don't schedule the snapshot to region worker.
fail_point!("skip_schedule_applying_snapshot", |_| {});
// TODO: gracefully remove region instead.
if let Err(e) = self.region_scheduler.schedule(task) {
info!(
"failed to to schedule apply job, are we shutting down?";
"region_id" => self.region.get_id(),
"peer_id" => self.peer_id,
"err" => ?e,
);
}
}
/// Handle raft ready then generate `HandleReadyResult` and `WriteTask`.
///
/// It's caller's duty to write `WriteTask` explicitly to disk.
pub fn handle_raft_ready(
&mut self,
ready: &mut Ready,
destroy_regions: Vec<metapb::Region>,
) -> Result<(HandleReadyResult, WriteTask<EK, ER>)> {
let region_id = self.get_region_id();
let prev_raft_state = self.raft_state().clone();
let mut write_task = WriteTask::new(region_id, self.peer_id, ready.number());
let mut res = if ready.snapshot().is_empty() {
HandleReadyResult::SendIoTask
} else {
fail_point!("raft_before_apply_snap");
let last_first_index = self.first_index().unwrap();
let (snap_region, for_witness) =
self.apply_snapshot(ready.snapshot(), &mut write_task, &destroy_regions)?;
let res = HandleReadyResult::Snapshot(Box::new(HandleSnapshotResult {
msgs: ready.take_persisted_messages(),
snap_region,
destroy_regions,
last_first_index,
for_witness,
}));
fail_point!("raft_after_apply_snap");
res
};
if !ready.entries().is_empty() {
self.append(ready.take_entries(), &mut write_task);
}
// Last index is 0 means the peer is created from raft message
// and has not applied snapshot yet, so skip persistent hard state.
if self.raft_state().get_last_index() > 0 {
if let Some(hs) = ready.hs() {
self.raft_state_mut().set_hard_state(hs.clone());