]> git.proxmox.com Git - proxmox-backup.git/blame - src/backup/chunk_store.rs
add global var to indicate server shutdown requests
[proxmox-backup.git] / src / backup / chunk_store.rs
CommitLineData
35cf5daa 1use failure::*;
43b13033 2
35cf5daa 3use std::path::{Path, PathBuf};
78216a5a 4use std::io::{Read, Write};
43b13033
DM
5use std::sync::{Arc, Mutex};
6use std::os::unix::io::AsRawFd;
128b37fe 7
7b2b40a8 8use openssl::sha;
35cf5daa 9
365bb90f
DM
10use crate::tools;
11
64e53b28
DM
12pub struct GarbageCollectionStatus {
13 pub used_bytes: usize,
14 pub used_chunks: usize,
15 pub disk_bytes: usize,
16 pub disk_chunks: usize,
17}
18
19impl Default for GarbageCollectionStatus {
20 fn default() -> Self {
21 GarbageCollectionStatus {
22 used_bytes: 0,
23 used_chunks: 0,
24 disk_bytes: 0,
25 disk_chunks: 0,
26 }
27 }
28}
29
e5064ba6 30/// File system based chunk store
35cf5daa 31pub struct ChunkStore {
277fc5a3 32 name: String, // used for error reporting
2c32fdde 33 pub (crate) base: PathBuf,
35cf5daa 34 chunk_dir: PathBuf,
c5d82e5f 35 mutex: Mutex<bool>,
43b13033 36 locker: Arc<Mutex<tools::ProcessLocker>>,
128b37fe
DM
37}
38
176e4af9
DM
39// TODO: what about sysctl setting vm.vfs_cache_pressure (0 - 100) ?
40
247cdbce
DM
41pub fn verify_chunk_size(size: u64) -> Result<(), Error> {
42
43 static SIZES: [u64; 7] = [64*1024, 128*1024, 256*1024, 512*1024, 1024*1024, 2048*1024, 4096*1024];
44
45 if !SIZES.contains(&size) {
46 bail!("Got unsupported chunk size '{}'", size);
47 }
48 Ok(())
49}
50
08481a0b 51fn digest_to_prefix(digest: &[u8]) -> PathBuf {
128b37fe 52
e95950e4 53 let mut buf = Vec::<u8>::with_capacity(2+1+2+1);
128b37fe 54
22968600
DM
55 const HEX_CHARS: &'static [u8; 16] = b"0123456789abcdef";
56
128b37fe
DM
57 buf.push(HEX_CHARS[(digest[0] as usize) >> 4]);
58 buf.push(HEX_CHARS[(digest[0] as usize) &0xf]);
e95950e4 59 buf.push(HEX_CHARS[(digest[1] as usize) >> 4]);
128b37fe 60 buf.push(HEX_CHARS[(digest[1] as usize) & 0xf]);
128b37fe
DM
61 buf.push('/' as u8);
62
63 let path = unsafe { String::from_utf8_unchecked(buf)};
64
65 path.into()
35cf5daa
DM
66}
67
68impl ChunkStore {
69
45773720
DM
70 fn chunk_dir<P: AsRef<Path>>(path: P) -> PathBuf {
71
72 let mut chunk_dir: PathBuf = PathBuf::from(path.as_ref());
73 chunk_dir.push(".chunks");
74
75 chunk_dir
76 }
77
277fc5a3 78 pub fn create<P: Into<PathBuf>>(name: &str, path: P) -> Result<Self, Error> {
35cf5daa 79
45773720 80 let base: PathBuf = path.into();
68469eeb
DM
81
82 if !base.is_absolute() {
83 bail!("expected absolute path - got {:?}", base);
84 }
85
45773720 86 let chunk_dir = Self::chunk_dir(&base);
35cf5daa 87
2989f6bf 88 if let Err(err) = std::fs::create_dir(&base) {
277fc5a3 89 bail!("unable to create chunk store '{}' at {:?} - {}", name, base, err);
2989f6bf
DM
90 }
91
92 if let Err(err) = std::fs::create_dir(&chunk_dir) {
277fc5a3 93 bail!("unable to create chunk store '{}' subdir {:?} - {}", name, chunk_dir, err);
2989f6bf 94 }
35cf5daa 95
bc616633 96 // create 64*1024 subdirs
e95950e4
DM
97 let mut last_percentage = 0;
98
bc616633 99 for i in 0..64*1024 {
af3e7d75 100 let mut l1path = chunk_dir.clone();
bc616633 101 l1path.push(format!("{:04x}", i));
2989f6bf 102 if let Err(err) = std::fs::create_dir(&l1path) {
277fc5a3 103 bail!("unable to create chunk store '{}' subdir {:?} - {}", name, l1path, err);
2989f6bf 104 }
bc616633
DM
105 let percentage = (i*100)/(64*1024);
106 if percentage != last_percentage {
107 eprintln!("Percentage done: {}", percentage);
108 last_percentage = percentage;
e95950e4 109 }
35cf5daa
DM
110 }
111
277fc5a3 112 Self::open(name, base)
35cf5daa
DM
113 }
114
277fc5a3 115 pub fn open<P: Into<PathBuf>>(name: &str, path: P) -> Result<Self, Error> {
35cf5daa 116
45773720 117 let base: PathBuf = path.into();
68469eeb
DM
118
119 if !base.is_absolute() {
120 bail!("expected absolute path - got {:?}", base);
121 }
122
45773720
DM
123 let chunk_dir = Self::chunk_dir(&base);
124
ce55dbbc 125 if let Err(err) = std::fs::metadata(&chunk_dir) {
277fc5a3 126 bail!("unable to open chunk store '{}' at {:?} - {}", name, chunk_dir, err);
ce55dbbc 127 }
45773720
DM
128
129 let mut lockfile_path = base.clone();
130 lockfile_path.push(".lock");
131
43b13033 132 let locker = tools::ProcessLocker::new(&lockfile_path)?;
35cf5daa 133
b8d4766a 134 Ok(ChunkStore {
277fc5a3 135 name: name.to_owned(),
b8d4766a
DM
136 base,
137 chunk_dir,
43b13033 138 locker,
b8d4766a
DM
139 mutex: Mutex::new(false)
140 })
35cf5daa
DM
141 }
142
7394ca3e 143 pub fn touch_chunk(&self, digest:&[u8]) -> Result<(), Error> {
3d5c11e5 144
a198d74f 145 let mut chunk_path = self.chunk_dir.clone();
08481a0b 146 let prefix = digest_to_prefix(&digest);
3d5c11e5 147 chunk_path.push(&prefix);
22968600 148 let digest_str = tools::digest_to_hex(&digest);
3d5c11e5
DM
149 chunk_path.push(&digest_str);
150
7ee2aa1b
DM
151 const UTIME_NOW: i64 = ((1 << 30) - 1);
152 const UTIME_OMIT: i64 = ((1 << 30) - 2);
153
a198d74f 154 let times: [libc::timespec; 2] = [
7ee2aa1b
DM
155 libc::timespec { tv_sec: 0, tv_nsec: UTIME_NOW },
156 libc::timespec { tv_sec: 0, tv_nsec: UTIME_OMIT }
157 ];
158
159 use nix::NixPath;
160
161 let res = chunk_path.with_nix_path(|cstr| unsafe {
162 libc::utimensat(-1, cstr.as_ptr(), &times[0], libc::AT_SYMLINK_NOFOLLOW)
163 })?;
164
165 if let Err(err) = nix::errno::Errno::result(res) {
166 bail!("updata atime failed for chunk {:?} - {}", chunk_path, err);
167 }
168
3d5c11e5
DM
169 Ok(())
170 }
171
df9973e8 172 pub fn read_chunk(&self, digest:&[u8], buffer: &mut Vec<u8>) -> Result<(), Error> {
96df2fb4
DM
173
174 let mut chunk_path = self.chunk_dir.clone();
175 let prefix = digest_to_prefix(&digest);
176 chunk_path.push(&prefix);
22968600 177 let digest_str = tools::digest_to_hex(&digest);
96df2fb4
DM
178 chunk_path.push(&digest_str);
179
d2690f74 180 buffer.clear();
78216a5a 181 let f = std::fs::File::open(&chunk_path)?;
141f062e 182 let mut decoder = zstd::stream::Decoder::new(f)?;
df9973e8 183
78216a5a 184 decoder.read_to_end(buffer)?;
96df2fb4 185
df9973e8 186 Ok(())
96df2fb4
DM
187 }
188
9739aca4
WB
189 pub fn get_chunk_iterator(
190 &self,
eff25eca 191 print_percentage: bool,
9739aca4 192 ) -> Result<
3a50ddd0 193 impl Iterator<Item = Result<tools::fs::ReadDirEntry, Error>> + std::iter::FusedIterator,
9739aca4
WB
194 Error
195 > {
196 use nix::dir::Dir;
197 use nix::fcntl::OFlag;
198 use nix::sys::stat::Mode;
199
200 let base_handle = match Dir::open(
201 &self.chunk_dir, OFlag::O_RDONLY, Mode::empty()) {
202 Ok(h) => h,
203 Err(err) => bail!("unable to open store '{}' chunk dir {:?} - {}",
204 self.name, self.chunk_dir, err),
205 };
206
c7f481b6
WB
207 let mut verbose = true;
208 let mut last_percentage = 0;
209
9739aca4 210 Ok((0..0x10000).filter_map(move |index| {
eff25eca
WB
211 if print_percentage {
212 let percentage = (index * 100) / 0x10000;
213 if last_percentage != percentage {
214 last_percentage = percentage;
215 eprintln!("percentage done: {}", percentage);
216 }
c7f481b6
WB
217 }
218 let subdir: &str = &format!("{:04x}", index);
219 match tools::fs::read_subdir(base_handle.as_raw_fd(), subdir) {
220 Err(e) => {
221 if verbose {
222 eprintln!("Error iterating through chunks: {}", e);
223 verbose = false;
224 }
225 None
226 }
227 Ok(iter) => Some(iter),
228 }
229 })
62f2422f
WB
230 .flatten()
231 .filter(|entry| {
232 // Check that the file name is actually a hash! (64 hex digits)
233 let entry = match entry {
234 Err(_) => return true, // pass errors onwards
235 Ok(ref entry) => entry,
236 };
237 let bytes = entry.file_name().to_bytes();
238 if bytes.len() != 64 {
239 return false;
240 }
241 for b in bytes {
242 if !b.is_ascii_hexdigit() {
243 return false;
244 }
245 }
246 true
247 }))
c7f481b6
WB
248 }
249
11861a48
DM
250 pub fn oldest_writer(&self) -> Option<i64> {
251 tools::ProcessLocker::oldest_shared_lock(self.locker.clone())
252 }
253
254 pub fn sweep_unused_chunks(
255 &self,
256 oldest_writer: Option<i64>,
257 status: &mut GarbageCollectionStatus
258 ) -> Result<(), Error> {
9349d2a1 259 use nix::sys::stat::fstatat;
08481a0b 260
fdd71f52 261 let now = unsafe { libc::time(std::ptr::null_mut()) };
c7f481b6 262
11861a48
DM
263 let mut min_atime = now - 3600*24; // at least 24h (see mount option relatime)
264
265 if let Some(stamp) = oldest_writer {
266 if stamp < min_atime {
267 min_atime = stamp;
268 }
269 }
270
271 min_atime -= 300; // add 5 mins gap for safety
272
eff25eca 273 for entry in self.get_chunk_iterator(true)? {
fdd71f52 274 let (dirfd, entry) = match entry {
c7f481b6
WB
275 Ok(entry) => (entry.parent_fd(), entry),
276 Err(_) => continue, // ignore errors
eae8aa3a 277 };
fdd71f52 278
eae8aa3a
DM
279 let file_type = match entry.file_type() {
280 Some(file_type) => file_type,
277fc5a3 281 None => bail!("unsupported file system type on chunk store '{}'", self.name),
eae8aa3a 282 };
82bc0ad4
WB
283 if file_type != nix::dir::Type::File {
284 continue;
285 }
eae8aa3a 286
d85987ae
DM
287 let filename = entry.file_name();
288
15a77c4c
DM
289 let lock = self.mutex.lock();
290
9349d2a1 291 if let Ok(stat) = fstatat(dirfd, filename, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) {
eae8aa3a 292 let age = now - stat.st_atime;
e95950e4 293 //println!("FOUND {} {:?}", age/(3600*24), filename);
11861a48 294 if stat.st_atime < min_atime {
eae8aa3a 295 println!("UNLINK {} {:?}", age/(3600*24), filename);
fdd71f52 296 let res = unsafe { libc::unlinkat(dirfd, filename.as_ptr(), 0) };
277fc5a3
DM
297 if res != 0 {
298 let err = nix::Error::last();
9349d2a1
WB
299 bail!(
300 "unlink chunk {:?} failed on store '{}' - {}",
301 filename,
302 self.name,
303 err,
304 );
277fc5a3 305 }
64e53b28
DM
306 } else {
307 status.disk_chunks += 1;
308 status.disk_bytes += stat.st_size as usize;
08481a0b 309 }
eae8aa3a 310 }
15a77c4c 311 drop(lock);
eae8aa3a 312 }
277fc5a3 313 Ok(())
08481a0b
DM
314 }
315
798f7fa0 316 pub fn insert_chunk(&self, chunk: &[u8]) -> Result<(bool, [u8; 32], u64), Error> {
128b37fe 317
7b2b40a8 318 // fixme: use Sha512/256 when available
9ac6ec86
WB
319 let digest = sha::sha256(chunk);
320 let (new, csize) = self.insert_chunk_noverify(&digest, chunk)?;
321 Ok((new, digest, csize))
322 }
7b2b40a8 323
9ac6ec86
WB
324 pub fn insert_chunk_noverify(
325 &self,
326 digest: &[u8; 32],
327 chunk: &[u8],
328 ) -> Result<(bool, u64), Error> {
7b2b40a8 329
22968600 330 //println!("DIGEST {}", tools::digest_to_hex(&digest));
128b37fe 331
af3e7d75 332 let mut chunk_path = self.chunk_dir.clone();
9ac6ec86 333 let prefix = digest_to_prefix(digest);
c5d82e5f 334 chunk_path.push(&prefix);
9ac6ec86 335 let digest_str = tools::digest_to_hex(digest);
c5d82e5f
DM
336 chunk_path.push(&digest_str);
337
338 let lock = self.mutex.lock();
339
340 if let Ok(metadata) = std::fs::metadata(&chunk_path) {
341 if metadata.is_file() {
9ac6ec86 342 return Ok((true, metadata.len()));
c5d82e5f 343 } else {
f7dd683b 344 bail!("Got unexpected file type on store '{}' for chunk {}", self.name, digest_str);
c5d82e5f
DM
345 }
346 }
128b37fe 347
c5d82e5f
DM
348 let mut tmp_path = chunk_path.clone();
349 tmp_path.set_extension("tmp");
78216a5a
DM
350
351 let f = std::fs::File::create(&tmp_path)?;
352
141f062e 353 let mut encoder = zstd::stream::Encoder::new(f, 1)?;
78216a5a
DM
354
355 encoder.write_all(chunk)?;
141f062e 356 let f = encoder.finish()?;
128b37fe 357
c5d82e5f
DM
358 if let Err(err) = std::fs::rename(&tmp_path, &chunk_path) {
359 if let Err(_) = std::fs::remove_file(&tmp_path) { /* ignore */ }
9349d2a1
WB
360 bail!(
361 "Atomic rename on store '{}' failed for chunk {} - {}",
362 self.name,
363 digest_str,
364 err,
365 );
c5d82e5f
DM
366 }
367
798f7fa0
DM
368 // fixme: is there a better way to get the compressed size?
369 let stat = nix::sys::stat::fstat(f.as_raw_fd())?;
370 let compressed_size = stat.st_size as u64;
371
77703d95 372 //println!("PATH {:?}", chunk_path);
128b37fe 373
c5d82e5f
DM
374 drop(lock);
375
9ac6ec86 376 Ok((false, compressed_size))
128b37fe
DM
377 }
378
606ce64b
DM
379 pub fn relative_path(&self, path: &Path) -> PathBuf {
380
381 let mut full_path = self.base.clone();
382 full_path.push(path);
383 full_path
384 }
385
3d5c11e5
DM
386 pub fn base_path(&self) -> PathBuf {
387 self.base.clone()
388 }
43b13033
DM
389
390 pub fn try_shared_lock(&self) -> Result<tools::ProcessLockSharedGuard, Error> {
391 tools::ProcessLocker::try_shared_lock(self.locker.clone())
392 }
393
394 pub fn try_exclusive_lock(&self) -> Result<tools::ProcessLockExclusiveGuard, Error> {
395 tools::ProcessLocker::try_exclusive_lock(self.locker.clone())
396 }
35cf5daa
DM
397}
398
399
400#[test]
401fn test_chunk_store1() {
402
332dcc22
DM
403 let mut path = std::fs::canonicalize(".").unwrap(); // we need absulute path
404 path.push(".testdir");
405
35cf5daa
DM
406 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
407
332dcc22 408 let chunk_store = ChunkStore::open("test", &path);
35cf5daa
DM
409 assert!(chunk_store.is_err());
410
332dcc22 411 let chunk_store = ChunkStore::create("test", &path).unwrap();
798f7fa0 412 let (exists, _, _) = chunk_store.insert_chunk(&[0u8, 1u8]).unwrap();
391a2e43
DM
413 assert!(!exists);
414
798f7fa0 415 let (exists, _, _) = chunk_store.insert_chunk(&[0u8, 1u8]).unwrap();
391a2e43 416 assert!(exists);
128b37fe 417
35cf5daa 418
332dcc22 419 let chunk_store = ChunkStore::create("test", &path);
35cf5daa
DM
420 assert!(chunk_store.is_err());
421
e0a5d1ca 422 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
35cf5daa 423}