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
use std::{
fs,
path::PathBuf,
sync::{Arc, atomic::AtomicBool, mpsc},
thread::{JoinHandle, sleep},
time::Duration,
};
use tracing::{debug, error, info};
use crate::database::{config::cleaner_config::CleanerConfig, sstable::version::Version};
pub struct Cleaner {
config: CleanerConfig,
under_shutdown: Arc<AtomicBool>,
version_channel: mpsc::Receiver<(Arc<Version>, Vec<PathBuf>)>,
}
impl Cleaner {
pub fn new(
config: CleanerConfig,
under_shutdown: Arc<AtomicBool>,
version_channel: mpsc::Receiver<(Arc<Version>, Vec<PathBuf>)>,
) -> Self {
Self {
config,
version_channel,
under_shutdown,
}
}
pub fn init(self) -> JoinHandle<u64> {
std::thread::spawn(move || {
let mut version_up_for_removal: Option<(Arc<Version>, Vec<PathBuf>)> = None;
loop {
if self
.under_shutdown
.load(std::sync::atomic::Ordering::Relaxed)
{
return 0;
}
if version_up_for_removal.is_none() {
// we will poll the mpsc
match self.version_channel.try_recv() {
Ok(v) => {
version_up_for_removal = Some(v);
}
Err(_e) => {}
}
}
while let Some((version, files)) = &version_up_for_removal {
// we will check if this is last copy of verion i.e nobody is using this version than we can remove the files
if Arc::strong_count(version) == 1 {
info!(
"Cleaner Droping version total {} files will be deleted",
files.len()
);
for file in files {
debug!("deleting the file {:?}", file);
match fs::remove_file(file) {
Ok(_) => {}
Err(e) => {
error!("Error while deleting the file {:?}", e)
}
}
}
match self.version_channel.try_recv() {
Ok(v) => {
version_up_for_removal = Some(v);
}
Err(_e) => {
version_up_for_removal = None;
}
}
info!("Cleaner droped version");
} else {
sleep(Duration::from_millis(
(self.config.cleaning_interval / 10) as u64,
));
}
}
sleep(Duration::from_millis(self.config.cleaning_interval as u64));
}
})
}
}