forked from tikv/raft-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.rs
More file actions
2846 lines (2644 loc) · 103 KB
/
engine.rs
File metadata and controls
2846 lines (2644 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
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 (c) 2017-present, PingCAP, Inc. Licensed under Apache-2.0.
use std::cell::{Cell, RefCell};
use std::marker::PhantomData;
use std::path::Path;
use std::sync::{Arc, Mutex, mpsc};
use std::thread::{Builder as ThreadBuilder, JoinHandle};
use std::time::{Duration, Instant};
use log::{error, info};
use protobuf::{Message, parse_from_bytes};
use crate::config::{Config, RecoveryMode};
use crate::consistency::ConsistencyChecker;
use crate::env::{DefaultFileSystem, FileSystem};
use crate::event_listener::EventListener;
use crate::file_pipe_log::debug::LogItemReader;
use crate::file_pipe_log::{DefaultMachineFactory, FilePipeLog, FilePipeLogBuilder};
use crate::log_batch::{Command, LogBatch, MessageExt};
use crate::memtable::{EntryIndex, MemTableRecoverContextFactory, MemTables};
use crate::metrics::*;
use crate::pipe_log::{FileBlockHandle, FileId, LogQueue, PipeLog};
use crate::purge::{PurgeHook, PurgeManager};
use crate::write_barrier::{WriteBarrier, Writer};
use crate::{Error, GlobalStats, Result, perf_context};
const METRICS_FLUSH_INTERVAL: Duration = Duration::from_secs(30);
/// Max times for `write`.
const MAX_WRITE_ATTEMPT: u64 = 2;
pub struct Engine<F = DefaultFileSystem, P = FilePipeLog<F>>
where
F: FileSystem,
P: PipeLog,
{
cfg: Arc<Config>,
listeners: Vec<Arc<dyn EventListener>>,
#[allow(dead_code)]
stats: Arc<GlobalStats>,
memtables: MemTables,
pipe_log: Arc<P>,
purge_manager: PurgeManager<P>,
write_barrier: WriteBarrier<LogBatch, Result<FileBlockHandle>>,
tx: Mutex<mpsc::Sender<()>>,
metrics_flusher: Option<JoinHandle<()>>,
_phantom: PhantomData<F>,
}
impl Engine<DefaultFileSystem, FilePipeLog<DefaultFileSystem>> {
pub fn open(cfg: Config) -> Result<Engine<DefaultFileSystem, FilePipeLog<DefaultFileSystem>>> {
Self::open_with_listeners(cfg, vec![])
}
pub fn open_with_listeners(
cfg: Config,
listeners: Vec<Arc<dyn EventListener>>,
) -> Result<Engine<DefaultFileSystem, FilePipeLog<DefaultFileSystem>>> {
Self::open_with(cfg, Arc::new(DefaultFileSystem), listeners)
}
}
impl<F> Engine<F, FilePipeLog<F>>
where
F: FileSystem,
{
pub fn open_with_file_system(
cfg: Config,
file_system: Arc<F>,
) -> Result<Engine<F, FilePipeLog<F>>> {
Self::open_with(cfg, file_system, vec![])
}
pub fn open_with(
mut cfg: Config,
file_system: Arc<F>,
mut listeners: Vec<Arc<dyn EventListener>>,
) -> Result<Engine<F, FilePipeLog<F>>> {
cfg.sanitize()?;
listeners.push(Arc::new(PurgeHook::default()) as Arc<dyn EventListener>);
let start = Instant::now();
let mut builder = FilePipeLogBuilder::new(cfg.clone(), file_system, listeners.clone());
builder.scan()?;
let factory = MemTableRecoverContextFactory::new(&cfg);
let (append, rewrite) = builder.recover(&factory)?;
let pipe_log = Arc::new(builder.finish()?);
rewrite.merge_append_context(append);
let (memtables, stats) = rewrite.finish();
info!("Recovering raft logs takes {:?}", start.elapsed());
let cfg = Arc::new(cfg);
let purge_manager = PurgeManager::new(
cfg.clone(),
memtables.clone(),
pipe_log.clone(),
stats.clone(),
listeners.clone(),
);
let (tx, rx) = mpsc::channel();
let stats_clone = stats.clone();
let memtables_clone = memtables.clone();
let metrics_flusher = ThreadBuilder::new()
.name("re-metrics".into())
.spawn(move || {
loop {
stats_clone.flush_metrics();
memtables_clone.flush_metrics();
if rx.recv_timeout(METRICS_FLUSH_INTERVAL).is_ok() {
break;
}
}
})?;
Ok(Self {
cfg,
listeners,
stats,
memtables,
pipe_log,
purge_manager,
write_barrier: Default::default(),
tx: Mutex::new(tx),
metrics_flusher: Some(metrics_flusher),
_phantom: PhantomData,
})
}
}
impl<F, P> Engine<F, P>
where
F: FileSystem,
P: PipeLog,
{
/// Writes the content of `log_batch` into the engine and returns written
/// bytes. If `sync` is true, the write will be followed by a call to
/// `fdatasync` on the log file.
pub fn write(&self, log_batch: &mut LogBatch, mut sync: bool) -> Result<usize> {
if log_batch.is_empty() {
return Ok(0);
}
let start = Instant::now();
let (len, compression_ratio) = log_batch.finish_populate(
self.cfg.batch_compression_threshold.0 as usize,
self.cfg.compression_level,
)?;
debug_assert!(len > 0);
let mut attempt_count = 0_u64;
let block_handle = loop {
// Max retry count is limited to `WRITE_MAX_RETRY_TIMES`, that is, 2.
// If the first `append` retry because of NOSPC error, the next `append`
// should success, unless there exists several abnormal cases in the IO device.
// In that case, `Engine::write` must return `Err`.
attempt_count += 1;
let mut writer = Writer::new(log_batch, sync);
// Snapshot and clear the current perf context temporarily, so the write group
// leader will collect the perf context diff later.
let mut perf_context = take_perf_context();
let before_enter = Instant::now();
if let Some(mut group) = self.write_barrier.enter(&mut writer) {
let now = Instant::now();
let _t = StopWatch::new_with(&*ENGINE_WRITE_LEADER_DURATION_HISTOGRAM, now);
for writer in group.iter_mut() {
writer.entered_time = Some(now);
sync |= writer.sync;
let log_batch = writer.mut_payload();
let res = self.pipe_log.append(LogQueue::Append, log_batch);
writer.set_output(res);
}
perf_context!(log_write_duration).observe_since(now);
if sync {
// As per trait protocol, sync error should be retriable. But we panic anyway to
// save the trouble of propagating it to other group members.
self.pipe_log.sync(LogQueue::Append).expect("pipe::sync()");
}
// Pass the perf context diff to all the writers.
let diff = get_perf_context();
for writer in group.iter_mut() {
writer.perf_context_diff = diff.clone();
}
}
let entered_time = writer.entered_time.unwrap();
perf_context.write_wait_duration +=
entered_time.saturating_duration_since(before_enter);
debug_assert_eq!(writer.perf_context_diff.write_wait_duration, Duration::ZERO);
perf_context += &writer.perf_context_diff;
set_perf_context(perf_context);
// Retry if `writer.finish()` returns a special 'Error::TryAgain', remarking
// that there still exists free space for this `LogBatch`.
match writer.finish() {
Ok(handle) => {
ENGINE_WRITE_PREPROCESS_DURATION_HISTOGRAM
.observe(entered_time.saturating_duration_since(start).as_secs_f64());
break handle;
}
Err(Error::TryAgain(e)) => {
if attempt_count >= MAX_WRITE_ATTEMPT {
// A special err, we will retry this LogBatch `append` by appending
// this writer to the next write group, and the current write leader
// will not hang on this write and will return timely.
return Err(Error::TryAgain(format!(
"Failed to write logbatch, exceed MAX_WRITE_ATTEMPT: ({MAX_WRITE_ATTEMPT}), err: {e}",
)));
}
info!("got err: {e}, try to write this LogBatch again");
}
Err(e) => {
return Err(e);
}
}
};
let mut now = Instant::now();
log_batch.finish_write(block_handle);
self.memtables.apply_append_writes(log_batch.drain());
for listener in &self.listeners {
listener.post_apply_memtables(block_handle.id);
}
let end = Instant::now();
let apply_duration = end.saturating_duration_since(now);
ENGINE_WRITE_APPLY_DURATION_HISTOGRAM.observe(apply_duration.as_secs_f64());
perf_context!(apply_duration).observe(apply_duration);
now = end;
ENGINE_WRITE_DURATION_HISTOGRAM.observe(now.saturating_duration_since(start).as_secs_f64());
ENGINE_WRITE_SIZE_HISTOGRAM.observe(len as f64);
ENGINE_WRITE_COMPRESSION_RATIO_HISTOGRAM.observe(compression_ratio);
Ok(len)
}
/// Synchronizes the Raft engine.
pub fn sync(&self) -> Result<()> {
self.write(&mut LogBatch::default(), true)?;
Ok(())
}
pub fn get_message<S: Message>(&self, region_id: u64, key: &[u8]) -> Result<Option<S>> {
let _t = StopWatch::new(&*ENGINE_READ_MESSAGE_DURATION_HISTOGRAM);
if let Some(memtable) = self.memtables.get(region_id) {
if let Some(value) = memtable.read().get(key) {
return Ok(Some(parse_from_bytes(&value)?));
}
}
Ok(None)
}
pub fn get(&self, region_id: u64, key: &[u8]) -> Option<Vec<u8>> {
let _t = StopWatch::new(&*ENGINE_READ_MESSAGE_DURATION_HISTOGRAM);
if let Some(memtable) = self.memtables.get(region_id) {
return memtable.read().get(key);
}
None
}
/// Iterates over [start_key, end_key) range of Raft Group key-values and
/// yields messages of the required type. Unparsable items are skipped.
pub fn scan_messages<S, C>(
&self,
region_id: u64,
start_key: Option<&[u8]>,
end_key: Option<&[u8]>,
reverse: bool,
mut callback: C,
) -> Result<()>
where
S: Message,
C: FnMut(&[u8], S) -> bool,
{
self.scan_raw_messages(region_id, start_key, end_key, reverse, move |k, raw_v| {
if let Ok(v) = parse_from_bytes(raw_v) {
callback(k, v)
} else {
true
}
})
}
/// Iterates over [start_key, end_key) range of Raft Group key-values and
/// yields all key value pairs as bytes.
pub fn scan_raw_messages<C>(
&self,
region_id: u64,
start_key: Option<&[u8]>,
end_key: Option<&[u8]>,
reverse: bool,
callback: C,
) -> Result<()>
where
C: FnMut(&[u8], &[u8]) -> bool,
{
let _t = StopWatch::new(&*ENGINE_READ_MESSAGE_DURATION_HISTOGRAM);
if let Some(memtable) = self.memtables.get(region_id) {
memtable
.read()
.scan(start_key, end_key, reverse, callback)?;
}
Ok(())
}
pub fn get_entry<M: MessageExt>(
&self,
region_id: u64,
log_idx: u64,
) -> Result<Option<M::Entry>> {
let _t = StopWatch::new(&*ENGINE_READ_ENTRY_DURATION_HISTOGRAM);
if let Some(memtable) = self.memtables.get(region_id) {
if let Some(idx) = memtable.read().get_entry(log_idx) {
ENGINE_READ_ENTRY_COUNT_HISTOGRAM.observe(1.0);
return Ok(Some(read_entry_from_file::<M, _>(
self.pipe_log.as_ref(),
&idx,
)?));
}
}
Ok(None)
}
/// Purges expired logs files and returns a set of Raft group ids that need
/// to be compacted.
pub fn purge_expired_files(&self) -> Result<Vec<u64>> {
self.purge_manager.purge_expired_files()
}
/// Returns count of fetched entries.
pub fn fetch_entries_to<M: MessageExt>(
&self,
region_id: u64,
begin: u64,
end: u64,
max_size: Option<usize>,
vec: &mut Vec<M::Entry>,
) -> Result<usize> {
let _t = StopWatch::new(&*ENGINE_READ_ENTRY_DURATION_HISTOGRAM);
if let Some(memtable) = self.memtables.get(region_id) {
let mut ents_idx: Vec<EntryIndex> = Vec::with_capacity((end - begin) as usize);
memtable
.read()
.fetch_entries_to(begin, end, max_size, &mut ents_idx)?;
for i in ents_idx.iter() {
vec.push({
match read_entry_from_file::<M, _>(self.pipe_log.as_ref(), i) {
Ok(entry) => entry,
Err(e) => {
// The index is not found in the file, it means the entry is already
// stale by `compact` or `rewrite`. Retry to read the entry from the
// memtable.
let immutable = memtable.read();
// Ensure that the corresponding memtable is locked with a read lock
// before completing the fetching of entries
// from the raft logs. This prevents the
// scenario where the index could become stale while
// being concurrently updated by the `rewrite` operation.
if let Some(idx) = immutable.get_entry(i.index) {
read_entry_from_file::<M, _>(self.pipe_log.as_ref(), &idx)?
} else {
return Err(e);
}
}
}
});
}
ENGINE_READ_ENTRY_COUNT_HISTOGRAM.observe(ents_idx.len() as f64);
return Ok(ents_idx.len());
}
Ok(0)
}
pub fn first_index(&self, region_id: u64) -> Option<u64> {
if let Some(memtable) = self.memtables.get(region_id) {
return memtable.read().first_index();
}
None
}
pub fn last_index(&self, region_id: u64) -> Option<u64> {
if let Some(memtable) = self.memtables.get(region_id) {
return memtable.read().last_index();
}
None
}
/// Deletes log entries before `index` in the specified Raft group. Returns
/// the number of deleted entries.
pub fn compact_to(&self, region_id: u64, index: u64) -> u64 {
let first_index = match self.first_index(region_id) {
Some(index) => index,
None => return 0,
};
let mut log_batch = LogBatch::default();
log_batch.add_command(region_id, Command::Compact { index });
if let Err(e) = self.write(&mut log_batch, false) {
error!("Failed to write Compact command: {e}");
}
self.first_index(region_id).unwrap_or(index) - first_index
}
pub fn raft_groups(&self) -> Vec<u64> {
self.memtables.fold(vec![], |mut v, m| {
v.push(m.region_id());
v
})
}
/// Returns `true` if the engine contains no Raft Group. Empty Raft Group
/// that isn't cleaned is counted as well.
pub fn is_empty(&self) -> bool {
self.memtables.is_empty()
}
/// Returns the sequence number range of active log files in the specific
/// log queue.
/// For testing only.
pub fn file_span(&self, queue: LogQueue) -> (u64, u64) {
self.pipe_log.file_span(queue)
}
pub fn get_used_size(&self) -> usize {
self.pipe_log.total_size(LogQueue::Append) + self.pipe_log.total_size(LogQueue::Rewrite)
}
pub fn path(&self) -> &str {
self.cfg.dir.as_str()
}
#[cfg(feature = "internals")]
pub fn purge_manager(&self) -> &PurgeManager<P> {
&self.purge_manager
}
}
impl<F, P> Drop for Engine<F, P>
where
F: FileSystem,
P: PipeLog,
{
fn drop(&mut self) {
self.tx.lock().unwrap().send(()).unwrap();
if let Some(t) = self.metrics_flusher.take() {
t.join().unwrap();
}
}
}
impl Engine<DefaultFileSystem, FilePipeLog<DefaultFileSystem>> {
pub fn consistency_check(path: &Path) -> Result<Vec<(u64, u64)>> {
Self::consistency_check_with_file_system(path, Arc::new(DefaultFileSystem))
}
#[cfg(feature = "scripting")]
pub fn unsafe_repair(path: &Path, queue: Option<LogQueue>, script: String) -> Result<()> {
Self::unsafe_repair_with_file_system(path, queue, script, Arc::new(DefaultFileSystem))
}
pub fn dump(path: &Path) -> Result<LogItemReader<DefaultFileSystem>> {
Self::dump_with_file_system(path, Arc::new(DefaultFileSystem))
}
}
impl<F> Engine<F, FilePipeLog<F>>
where
F: FileSystem,
{
/// Returns a list of corrupted Raft groups, including their ids and last
/// valid log index. Head or tail corruption cannot be detected.
pub fn consistency_check_with_file_system(
path: &Path,
file_system: Arc<F>,
) -> Result<Vec<(u64, u64)>> {
if !path.exists() {
return Err(Error::InvalidArgument(format!(
"raft-engine directory '{}' does not exist.",
path.to_str().unwrap()
)));
}
let cfg = Config {
dir: path.to_str().unwrap().to_owned(),
recovery_mode: RecoveryMode::TolerateAnyCorruption,
..Default::default()
};
let mut builder = FilePipeLogBuilder::new(cfg, file_system, Vec::new());
builder.scan()?;
let (append, rewrite) =
builder.recover(&DefaultMachineFactory::<ConsistencyChecker>::default())?;
let mut map = rewrite.finish();
for (id, index) in append.finish() {
map.entry(id).or_insert(index);
}
let mut list: Vec<(u64, u64)> = map.into_iter().collect();
list.sort_unstable();
Ok(list)
}
#[cfg(feature = "scripting")]
pub fn unsafe_repair_with_file_system(
path: &Path,
queue: Option<LogQueue>,
script: String,
file_system: Arc<F>,
) -> Result<()> {
use crate::file_pipe_log::{RecoveryConfig, ReplayMachine};
if !path.exists() {
return Err(Error::InvalidArgument(format!(
"raft-engine directory '{}' does not exist.",
path.to_str().unwrap()
)));
}
let cfg = Config {
dir: path.to_str().unwrap().to_owned(),
recovery_mode: RecoveryMode::TolerateAnyCorruption,
..Default::default()
};
let recovery_mode = cfg.recovery_mode;
let read_block_size = cfg.recovery_read_block_size.0;
let mut builder = FilePipeLogBuilder::new(cfg, file_system.clone(), Vec::new());
builder.scan()?;
let factory = crate::filter::RhaiFilterMachineFactory::from_script(script);
let mut machine = None;
if queue.is_none() || queue.unwrap() == LogQueue::Append {
machine = Some(builder.recover_queue(
file_system.clone(),
RecoveryConfig {
queue: LogQueue::Append,
mode: recovery_mode,
concurrency: 1,
read_block_size,
},
&factory,
)?);
}
if queue.is_none() || queue.unwrap() == LogQueue::Rewrite {
let machine2 = builder.recover_queue(
file_system.clone(),
RecoveryConfig {
queue: LogQueue::Rewrite,
mode: recovery_mode,
concurrency: 1,
read_block_size,
},
&factory,
)?;
if let Some(machine) = &mut machine {
machine.merge(machine2, LogQueue::Rewrite)?;
}
}
if let Some(machine) = machine {
machine.finish(file_system.as_ref(), path)?;
}
Ok(())
}
/// Dumps all operations.
pub fn dump_with_file_system(path: &Path, file_system: Arc<F>) -> Result<LogItemReader<F>> {
if !path.exists() {
return Err(Error::InvalidArgument(format!(
"raft-engine directory or file '{}' does not exist.",
path.to_str().unwrap()
)));
}
if path.is_dir() {
LogItemReader::new_directory_reader(file_system, path)
} else {
LogItemReader::new_file_reader(file_system, path)
}
}
}
struct BlockCache {
key: Cell<FileBlockHandle>,
block: RefCell<Vec<u8>>,
}
impl BlockCache {
fn new() -> Self {
BlockCache {
key: Cell::new(FileBlockHandle {
id: FileId::new(LogQueue::Append, 0),
offset: 0,
len: 0,
}),
block: RefCell::new(Vec::new()),
}
}
fn insert(&self, key: FileBlockHandle, block: Vec<u8>) {
self.key.set(key);
self.block.replace(block);
}
}
thread_local! {
static BLOCK_CACHE: BlockCache = BlockCache::new();
}
pub(crate) fn read_entry_from_file<M, P>(pipe_log: &P, idx: &EntryIndex) -> Result<M::Entry>
where
M: MessageExt,
P: PipeLog,
{
BLOCK_CACHE.with(|cache| {
if cache.key.get() != idx.entries.unwrap() {
cache.insert(
idx.entries.unwrap(),
LogBatch::decode_entries_block(
&pipe_log.read_bytes(idx.entries.unwrap())?,
idx.entries.unwrap(),
idx.compression_type,
)?,
);
}
let e = parse_from_bytes(
&cache.block.borrow()
[idx.entry_offset as usize..(idx.entry_offset + idx.entry_len) as usize],
)?;
assert_eq!(M::index(&e), idx.index);
Ok(e)
})
}
pub(crate) fn read_entry_bytes_from_file<P>(pipe_log: &P, idx: &EntryIndex) -> Result<Vec<u8>>
where
P: PipeLog,
{
BLOCK_CACHE.with(|cache| {
if cache.key.get() != idx.entries.unwrap() {
cache.insert(
idx.entries.unwrap(),
LogBatch::decode_entries_block(
&pipe_log.read_bytes(idx.entries.unwrap())?,
idx.entries.unwrap(),
idx.compression_type,
)?,
);
}
Ok(cache.block.borrow()
[idx.entry_offset as usize..(idx.entry_offset + idx.entry_len) as usize]
.to_owned())
})
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::env::{ObfuscatedFileSystem, Permission};
use crate::file_pipe_log::{FileNameExt, parse_reserved_file_name};
use crate::log_batch::AtomicGroupBuilder;
use crate::pipe_log::Version;
use crate::test_util::{PanicGuard, generate_entries};
use crate::util::ReadableSize;
use kvproto::raft_serverpb::RaftLocalState;
use raft::eraftpb::Entry;
use rand::{Rng, thread_rng};
use std::collections::{BTreeSet, HashSet};
use std::fs::OpenOptions;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
pub(crate) type RaftLogEngine<F = DefaultFileSystem> = Engine<F>;
impl<F: FileSystem> RaftLogEngine<F> {
fn append(&self, rid: u64, start_index: u64, end_index: u64, data: Option<&[u8]>) {
let entries = generate_entries(start_index, end_index, data);
if !entries.is_empty() {
let mut batch = LogBatch::default();
batch.add_entries::<Entry>(rid, &entries).unwrap();
batch
.put_message(
rid,
b"last_index".to_vec(),
&RaftLocalState {
last_index: entries[entries.len() - 1].index,
..Default::default()
},
)
.unwrap();
self.write(&mut batch, true).unwrap();
}
}
fn clean(&self, rid: u64) {
let mut log_batch = LogBatch::default();
log_batch.add_command(rid, Command::Clean);
self.write(&mut log_batch, true).unwrap();
}
fn decode_last_index(&self, rid: u64) -> Option<u64> {
self.get_message::<RaftLocalState>(rid, b"last_index")
.unwrap()
.map(|s| s.last_index)
}
fn reopen(self) -> Self {
let cfg: Config = self.cfg.as_ref().clone();
let file_system = self.pipe_log.file_system();
let mut listeners = self.listeners.clone();
listeners.pop();
drop(self);
RaftLogEngine::open_with(cfg, file_system, listeners).unwrap()
}
fn scan_entries<FR: Fn(u64, LogQueue, &[u8])>(
&self,
rid: u64,
start: u64,
end: u64,
reader: FR,
) {
let mut entries = Vec::new();
self.fetch_entries_to::<Entry>(
rid,
self.first_index(rid).unwrap(),
self.last_index(rid).unwrap() + 1,
None,
&mut entries,
)
.unwrap();
assert_eq!(entries.first().unwrap().index, start, "{rid}");
assert_eq!(entries.last().unwrap().index + 1, end);
assert_eq!(
entries.last().unwrap().index,
self.decode_last_index(rid).unwrap()
);
assert_eq!(entries.len(), (end - start) as usize);
for e in entries.iter() {
let entry_index = self
.memtables
.get(rid)
.unwrap()
.read()
.get_entry(e.index)
.unwrap();
assert_eq!(&self.get_entry::<Entry>(rid, e.index).unwrap().unwrap(), e);
reader(e.index, entry_index.entries.unwrap().id.queue, &e.data);
}
}
fn file_count(&self, queue: Option<LogQueue>) -> usize {
if let Some(queue) = queue {
let (a, b) = self.file_span(queue);
(b - a + 1) as usize
} else {
self.file_count(Some(LogQueue::Append)) + self.file_count(Some(LogQueue::Rewrite))
}
}
}
#[test]
fn test_empty_engine() {
let dir = tempfile::Builder::new()
.prefix("test_empty_engine")
.tempdir()
.unwrap();
let mut sub_dir = PathBuf::from(dir.as_ref());
sub_dir.push("raft-engine");
let cfg = Config {
dir: sub_dir.to_str().unwrap().to_owned(),
..Default::default()
};
RaftLogEngine::open_with_file_system(cfg, Arc::new(ObfuscatedFileSystem::default()))
.unwrap();
}
#[test]
fn test_get_entry() {
let normal_batch_size = 10;
let compressed_batch_size = 5120;
for &entry_size in &[normal_batch_size, compressed_batch_size] {
let dir = tempfile::Builder::new()
.prefix("test_get_entry")
.tempdir()
.unwrap();
let cfg = Config {
dir: dir.path().to_str().unwrap().to_owned(),
target_file_size: ReadableSize(1),
..Default::default()
};
let engine = RaftLogEngine::open_with_file_system(
cfg.clone(),
Arc::new(ObfuscatedFileSystem::default()),
)
.unwrap();
assert_eq!(engine.path(), dir.path().to_str().unwrap());
let data = vec![b'x'; entry_size];
for i in 10..20 {
let rid = i;
let index = i;
engine.append(rid, index, index + 2, Some(&data));
}
for i in 10..20 {
let rid = i;
let index = i;
engine.scan_entries(rid, index, index + 2, |_, q, d| {
assert_eq!(q, LogQueue::Append);
assert_eq!(d, &data);
});
}
// Recover the engine.
let engine = engine.reopen();
for i in 10..20 {
let rid = i;
let index = i;
engine.scan_entries(rid, index, index + 2, |_, q, d| {
assert_eq!(q, LogQueue::Append);
assert_eq!(d, &data);
});
}
}
}
#[test]
fn test_clean_raft_group() {
fn run_steps(steps: &[Option<(u64, u64)>]) {
let rid = 1;
let data = vec![b'x'; 1024];
for rewrite_step in 1..=steps.len() {
for exit_purge in [None, Some(1), Some(2)] {
let _guard = PanicGuard::with_prompt(format!(
"case: [{steps:?}, {rewrite_step}, {exit_purge:?}]",
));
let dir = tempfile::Builder::new()
.prefix("test_clean_raft_group")
.tempdir()
.unwrap();
let cfg = Config {
dir: dir.path().to_str().unwrap().to_owned(),
target_file_size: ReadableSize(1),
..Default::default()
};
let engine = RaftLogEngine::open_with_file_system(
cfg.clone(),
Arc::new(ObfuscatedFileSystem::default()),
)
.unwrap();
for (i, step) in steps.iter().enumerate() {
if let Some((start, end)) = *step {
engine.append(rid, start, end, Some(&data));
} else {
engine.clean(rid);
}
if i + 1 == rewrite_step {
engine
.purge_manager
.must_rewrite_append_queue(None, exit_purge);
}
}
let engine = engine.reopen();
if let Some((start, end)) = *steps.last().unwrap() {
engine.scan_entries(rid, start, end, |_, _, d| {
assert_eq!(d, &data);
});
} else {
assert!(engine.raft_groups().is_empty());
}
engine.purge_manager.must_rewrite_append_queue(None, None);
let engine = engine.reopen();
if let Some((start, end)) = *steps.last().unwrap() {
engine.scan_entries(rid, start, end, |_, _, d| {
assert_eq!(d, &data);
});
} else {
assert!(engine.raft_groups().is_empty());
}
}
}
}
run_steps(&[Some((1, 5)), None, Some((2, 6)), None, Some((3, 7)), None]);
run_steps(&[Some((1, 5)), None, Some((2, 6)), None, Some((3, 7))]);
run_steps(&[Some((1, 5)), None, Some((2, 6)), None]);
run_steps(&[Some((1, 5)), None, Some((2, 6))]);
run_steps(&[Some((1, 5)), None]);
}
#[test]
fn test_key_value_scan() {
fn key(i: u64) -> Vec<u8> {
format!("k{i}").as_bytes().to_vec()
}
fn value(i: u64) -> Vec<u8> {
format!("v{i}").as_bytes().to_vec()
}
fn rich_value(i: u64) -> RaftLocalState {
RaftLocalState {
last_index: i,
..Default::default()
}
}
let dir = tempfile::Builder::new()
.prefix("test_key_value_scan")
.tempdir()
.unwrap();
let cfg = Config {
dir: dir.path().to_str().unwrap().to_owned(),
target_file_size: ReadableSize(1),
..Default::default()
};
let rid = 1;
let engine =
RaftLogEngine::open_with_file_system(cfg, Arc::new(ObfuscatedFileSystem::default()))
.unwrap();
engine
.scan_messages::<RaftLocalState, _>(rid, None, None, false, |_, _| {
panic!("unexpected message.");
})
.unwrap();
let mut batch = LogBatch::default();
let mut res = Vec::new();
let mut rich_res = Vec::new();
batch.put(rid, key(1), value(1)).unwrap();
batch.put(rid, key(2), value(2)).unwrap();
batch.put(rid, key(3), value(3)).unwrap();
engine.write(&mut batch, false).unwrap();
engine
.scan_raw_messages(rid, None, None, false, |k, v| {
res.push((k.to_vec(), v.to_vec()));
true
})
.unwrap();
assert_eq!(
res,
vec![(key(1), value(1)), (key(2), value(2)), (key(3), value(3))]
);
res.clear();
engine
.scan_raw_messages(rid, None, None, true, |k, v| {
res.push((k.to_vec(), v.to_vec()));
true
})
.unwrap();
assert_eq!(
res,
vec![(key(3), value(3)), (key(2), value(2)), (key(1), value(1))]
);
res.clear();
engine
.scan_messages::<RaftLocalState, _>(rid, None, None, false, |_, _| {
panic!("unexpected message.")
})
.unwrap();
batch.put_message(rid, key(22), &rich_value(22)).unwrap();
batch.put_message(rid, key(33), &rich_value(33)).unwrap();
engine.write(&mut batch, false).unwrap();
engine
.scan_messages(rid, None, None, false, |k, v| {
rich_res.push((k.to_vec(), v));
false
})
.unwrap();
assert_eq!(rich_res, vec![(key(22), rich_value(22))]);
rich_res.clear();
engine
.scan_messages(rid, None, None, true, |k, v| {
rich_res.push((k.to_vec(), v));
false
})
.unwrap();
assert_eq!(rich_res, vec![(key(33), rich_value(33))]);
rich_res.clear();
}
#[test]
fn test_delete_key_value() {
let dir = tempfile::Builder::new()
.prefix("test_delete_key_value")
.tempdir()
.unwrap();
let cfg = Config {
dir: dir.path().to_str().unwrap().to_owned(),
target_file_size: ReadableSize(1),
..Default::default()
};
let rid = 1;
let key = b"key".to_vec();
let (v1, v2) = (b"v1".to_vec(), b"v2".to_vec());
let mut batch_1 = LogBatch::default();
batch_1.put(rid, key.clone(), v1).unwrap();
let mut batch_2 = LogBatch::default();
batch_2.put(rid, key.clone(), v2.clone()).unwrap();
let mut delete_batch = LogBatch::default();
delete_batch.delete(rid, key.clone());