]> git.proxmox.com Git - proxmox-backup.git/blob - src/backup/chunk_store.rs
src/backup/chunk_store.rs: use ? insteadf of unwrap
[proxmox-backup.git] / src / backup / chunk_store.rs
1 use anyhow::{bail, format_err, Error};
2
3 use std::path::{Path, PathBuf};
4 use std::io::Write;
5 use std::sync::{Arc, Mutex};
6 use std::os::unix::io::AsRawFd;
7
8 use proxmox::tools::fs::{CreateOptions, create_path, create_dir};
9
10 use crate::tools;
11 use crate::api2::types::GarbageCollectionStatus;
12
13 use super::DataBlob;
14 use crate::server::WorkerTask;
15
16 /// File system based chunk store
17 pub struct ChunkStore {
18 name: String, // used for error reporting
19 pub (crate) base: PathBuf,
20 chunk_dir: PathBuf,
21 mutex: Mutex<bool>,
22 locker: Arc<Mutex<tools::ProcessLocker>>,
23 }
24
25 // TODO: what about sysctl setting vm.vfs_cache_pressure (0 - 100) ?
26
27 pub fn verify_chunk_size(size: usize) -> Result<(), Error> {
28
29 static SIZES: [usize; 7] = [64*1024, 128*1024, 256*1024, 512*1024, 1024*1024, 2048*1024, 4096*1024];
30
31 if !SIZES.contains(&size) {
32 bail!("Got unsupported chunk size '{}'", size);
33 }
34 Ok(())
35 }
36
37 fn digest_to_prefix(digest: &[u8]) -> PathBuf {
38
39 let mut buf = Vec::<u8>::with_capacity(2+1+2+1);
40
41 const HEX_CHARS: &[u8; 16] = b"0123456789abcdef";
42
43 buf.push(HEX_CHARS[(digest[0] as usize) >> 4]);
44 buf.push(HEX_CHARS[(digest[0] as usize) &0xf]);
45 buf.push(HEX_CHARS[(digest[1] as usize) >> 4]);
46 buf.push(HEX_CHARS[(digest[1] as usize) & 0xf]);
47 buf.push('/' as u8);
48
49 let path = unsafe { String::from_utf8_unchecked(buf)};
50
51 path.into()
52 }
53
54 impl ChunkStore {
55
56 fn chunk_dir<P: AsRef<Path>>(path: P) -> PathBuf {
57
58 let mut chunk_dir: PathBuf = PathBuf::from(path.as_ref());
59 chunk_dir.push(".chunks");
60
61 chunk_dir
62 }
63
64 pub fn create<P>(name: &str, path: P, uid: nix::unistd::Uid, gid: nix::unistd::Gid) -> Result<Self, Error>
65 where
66 P: Into<PathBuf>,
67 {
68
69 let base: PathBuf = path.into();
70
71 if !base.is_absolute() {
72 bail!("expected absolute path - got {:?}", base);
73 }
74
75 let chunk_dir = Self::chunk_dir(&base);
76
77 let options = CreateOptions::new()
78 .owner(uid)
79 .group(gid);
80
81 let default_options = CreateOptions::new();
82
83 match create_path(&base, Some(default_options.clone()), Some(options.clone())) {
84 Err(err) => bail!("unable to create chunk store '{}' at {:?} - {}", name, base, err),
85 Ok(res) => if ! res { nix::unistd::chown(&base, Some(uid), Some(gid))? },
86 }
87
88 if let Err(err) = create_dir(&chunk_dir, options.clone()) {
89 bail!("unable to create chunk store '{}' subdir {:?} - {}", name, chunk_dir, err);
90 }
91
92 // create lock file with correct owner/group
93 let lockfile_path = Self::lockfile_path(&base);
94 proxmox::tools::fs::replace_file(lockfile_path, b"", options.clone())?;
95
96 // create 64*1024 subdirs
97 let mut last_percentage = 0;
98
99 for i in 0..64*1024 {
100 let mut l1path = chunk_dir.clone();
101 l1path.push(format!("{:04x}", i));
102 if let Err(err) = create_dir(&l1path, options.clone()) {
103 bail!("unable to create chunk store '{}' subdir {:?} - {}", name, l1path, err);
104 }
105 let percentage = (i*100)/(64*1024);
106 if percentage != last_percentage {
107 eprintln!("{}%", percentage);
108 last_percentage = percentage;
109 }
110 }
111
112
113 Self::open(name, base)
114 }
115
116 fn lockfile_path<P: Into<PathBuf>>(base: P) -> PathBuf {
117 let base: PathBuf = base.into();
118
119 let mut lockfile_path = base.clone();
120 lockfile_path.push(".lock");
121
122 lockfile_path
123 }
124
125 pub fn open<P: Into<PathBuf>>(name: &str, base: P) -> Result<Self, Error> {
126
127 let base: PathBuf = base.into();
128
129 if !base.is_absolute() {
130 bail!("expected absolute path - got {:?}", base);
131 }
132
133 let chunk_dir = Self::chunk_dir(&base);
134
135 if let Err(err) = std::fs::metadata(&chunk_dir) {
136 bail!("unable to open chunk store '{}' at {:?} - {}", name, chunk_dir, err);
137 }
138
139 let lockfile_path = Self::lockfile_path(&base);
140
141 let locker = tools::ProcessLocker::new(&lockfile_path)?;
142
143 Ok(ChunkStore {
144 name: name.to_owned(),
145 base,
146 chunk_dir,
147 locker,
148 mutex: Mutex::new(false)
149 })
150 }
151
152 pub fn touch_chunk(&self, digest: &[u8; 32]) -> Result<(), Error> {
153 self.cond_touch_chunk(digest, true)?;
154 Ok(())
155 }
156
157 pub fn cond_touch_chunk(&self, digest: &[u8; 32], fail_if_not_exist: bool) -> Result<bool, Error> {
158
159 let (chunk_path, _digest_str) = self.chunk_path(digest);
160
161 const UTIME_NOW: i64 = (1 << 30) - 1;
162 const UTIME_OMIT: i64 = (1 << 30) - 2;
163
164 let times: [libc::timespec; 2] = [
165 libc::timespec { tv_sec: 0, tv_nsec: UTIME_NOW },
166 libc::timespec { tv_sec: 0, tv_nsec: UTIME_OMIT }
167 ];
168
169 use nix::NixPath;
170
171 let res = chunk_path.with_nix_path(|cstr| unsafe {
172 let tmp = libc::utimensat(-1, cstr.as_ptr(), &times[0], libc::AT_SYMLINK_NOFOLLOW);
173 nix::errno::Errno::result(tmp)
174 })?;
175
176 if let Err(err) = res {
177 if !fail_if_not_exist && err.as_errno() == Some(nix::errno::Errno::ENOENT) {
178 return Ok(false);
179 }
180
181 bail!("update atime failed for chunk {:?} - {}", chunk_path, err);
182 }
183
184 Ok(true)
185 }
186
187 pub fn get_chunk_iterator(
188 &self,
189 ) -> Result<
190 impl Iterator<Item = (Result<tools::fs::ReadDirEntry, Error>, usize, bool)> + std::iter::FusedIterator,
191 Error
192 > {
193 use nix::dir::Dir;
194 use nix::fcntl::OFlag;
195 use nix::sys::stat::Mode;
196
197 let base_handle = Dir::open(&self.chunk_dir, OFlag::O_RDONLY, Mode::empty())
198 .map_err(|err| {
199 format_err!(
200 "unable to open store '{}' chunk dir {:?} - {}",
201 self.name,
202 self.chunk_dir,
203 err,
204 )
205 })?;
206
207 let mut done = false;
208 let mut inner: Option<tools::fs::ReadDir> = None;
209 let mut at = 0;
210 let mut percentage = 0;
211 Ok(std::iter::from_fn(move || {
212 if done {
213 return None;
214 }
215
216 loop {
217 if let Some(ref mut inner) = inner {
218 match inner.next() {
219 Some(Ok(entry)) => {
220 // skip files if they're not a hash
221 let bytes = entry.file_name().to_bytes();
222 if bytes.len() != 64 && bytes.len() != 64 + ".0.bad".len() {
223 continue;
224 }
225 if !bytes.iter().take(64).all(u8::is_ascii_hexdigit) {
226 continue;
227 }
228
229 let bad = bytes.ends_with(".bad".as_bytes());
230 return Some((Ok(entry), percentage, bad));
231 }
232 Some(Err(err)) => {
233 // stop after first error
234 done = true;
235 // and pass the error through:
236 return Some((Err(err), percentage, false));
237 }
238 None => (), // open next directory
239 }
240 }
241
242 inner = None;
243
244 if at == 0x10000 {
245 done = true;
246 return None;
247 }
248
249 let subdir: &str = &format!("{:04x}", at);
250 percentage = (at * 100) / 0x10000;
251 at += 1;
252 match tools::fs::read_subdir(base_handle.as_raw_fd(), subdir) {
253 Ok(dir) => {
254 inner = Some(dir);
255 // start reading:
256 continue;
257 }
258 Err(ref err) if err.as_errno() == Some(nix::errno::Errno::ENOENT) => {
259 // non-existing directories are okay, just keep going:
260 continue;
261 }
262 Err(err) => {
263 // other errors are fatal, so end our iteration
264 done = true;
265 // and pass the error through:
266 return Some((Err(format_err!("unable to read subdir '{}' - {}", subdir, err)), percentage, false));
267 }
268 }
269 }
270 }).fuse())
271 }
272
273 pub fn oldest_writer(&self) -> Option<i64> {
274 tools::ProcessLocker::oldest_shared_lock(self.locker.clone())
275 }
276
277 pub fn sweep_unused_chunks(
278 &self,
279 oldest_writer: i64,
280 phase1_start_time: i64,
281 status: &mut GarbageCollectionStatus,
282 worker: &WorkerTask,
283 ) -> Result<(), Error> {
284 use nix::sys::stat::fstatat;
285 use nix::unistd::{unlinkat, UnlinkatFlags};
286
287 let mut min_atime = phase1_start_time - 3600*24; // at least 24h (see mount option relatime)
288
289 if oldest_writer < min_atime {
290 min_atime = oldest_writer;
291 }
292
293 min_atime -= 300; // add 5 mins gap for safety
294
295 let mut last_percentage = 0;
296 let mut chunk_count = 0;
297
298 for (entry, percentage, bad) in self.get_chunk_iterator()? {
299 if last_percentage != percentage {
300 last_percentage = percentage;
301 worker.log(format!("percentage done: phase2 {}% (processed {} chunks)", percentage, chunk_count));
302 }
303
304 worker.fail_on_abort()?;
305 tools::fail_on_shutdown()?;
306
307 let (dirfd, entry) = match entry {
308 Ok(entry) => (entry.parent_fd(), entry),
309 Err(err) => bail!("chunk iterator on chunk store '{}' failed - {}", self.name, err),
310 };
311
312 let file_type = match entry.file_type() {
313 Some(file_type) => file_type,
314 None => bail!("unsupported file system type on chunk store '{}'", self.name),
315 };
316 if file_type != nix::dir::Type::File {
317 continue;
318 }
319
320 chunk_count += 1;
321
322 let filename = entry.file_name();
323
324 let lock = self.mutex.lock();
325
326 if let Ok(stat) = fstatat(dirfd, filename, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) {
327 if bad {
328 // filename validity checked in iterator
329 let orig_filename = std::ffi::CString::new(&filename.to_bytes()[..64])?;
330 match fstatat(
331 dirfd,
332 orig_filename.as_c_str(),
333 nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW)
334 {
335 Ok(_) => {
336 match unlinkat(Some(dirfd), filename, UnlinkatFlags::NoRemoveDir) {
337 Err(err) =>
338 worker.warn(format!(
339 "unlinking corrupt chunk {:?} failed on store '{}' - {}",
340 filename,
341 self.name,
342 err,
343 )),
344 Ok(_) => {
345 status.removed_bad += 1;
346 status.removed_bytes += stat.st_size as u64;
347 }
348 }
349 },
350 Err(nix::Error::Sys(nix::errno::Errno::ENOENT)) => {
351 // chunk hasn't been rewritten yet, keep .bad file
352 },
353 Err(err) => {
354 // some other error, warn user and keep .bad file around too
355 worker.warn(format!(
356 "error during stat on '{:?}' - {}",
357 orig_filename,
358 err,
359 ));
360 }
361 }
362 } else if stat.st_atime < min_atime {
363 //let age = now - stat.st_atime;
364 //println!("UNLINK {} {:?}", age/(3600*24), filename);
365 if let Err(err) = unlinkat(Some(dirfd), filename, UnlinkatFlags::NoRemoveDir) {
366 bail!(
367 "unlinking chunk {:?} failed on store '{}' - {}",
368 filename,
369 self.name,
370 err,
371 );
372 }
373 status.removed_chunks += 1;
374 status.removed_bytes += stat.st_size as u64;
375 } else {
376 if stat.st_atime < oldest_writer {
377 status.pending_chunks += 1;
378 status.pending_bytes += stat.st_size as u64;
379 } else {
380 status.disk_chunks += 1;
381 status.disk_bytes += stat.st_size as u64;
382 }
383 }
384 }
385 drop(lock);
386 }
387
388 Ok(())
389 }
390
391 pub fn insert_chunk(
392 &self,
393 chunk: &DataBlob,
394 digest: &[u8; 32],
395 ) -> Result<(bool, u64), Error> {
396
397 //println!("DIGEST {}", proxmox::tools::digest_to_hex(digest));
398
399 let (chunk_path, digest_str) = self.chunk_path(digest);
400
401 let lock = self.mutex.lock();
402
403 if let Ok(metadata) = std::fs::metadata(&chunk_path) {
404 if metadata.is_file() {
405 self.touch_chunk(digest)?;
406 return Ok((true, metadata.len()));
407 } else {
408 bail!("Got unexpected file type on store '{}' for chunk {}", self.name, digest_str);
409 }
410 }
411
412 let mut tmp_path = chunk_path.clone();
413 tmp_path.set_extension("tmp");
414
415 let mut file = std::fs::File::create(&tmp_path)?;
416
417 let raw_data = chunk.raw_data();
418 let encoded_size = raw_data.len() as u64;
419
420 file.write_all(raw_data)?;
421
422 if let Err(err) = std::fs::rename(&tmp_path, &chunk_path) {
423 if let Err(_) = std::fs::remove_file(&tmp_path) { /* ignore */ }
424 bail!(
425 "Atomic rename on store '{}' failed for chunk {} - {}",
426 self.name,
427 digest_str,
428 err,
429 );
430 }
431
432 drop(lock);
433
434 Ok((false, encoded_size))
435 }
436
437 pub fn chunk_path(&self, digest:&[u8; 32]) -> (PathBuf, String) {
438 let mut chunk_path = self.chunk_dir.clone();
439 let prefix = digest_to_prefix(digest);
440 chunk_path.push(&prefix);
441 let digest_str = proxmox::tools::digest_to_hex(digest);
442 chunk_path.push(&digest_str);
443 (chunk_path, digest_str)
444 }
445
446 pub fn relative_path(&self, path: &Path) -> PathBuf {
447
448 let mut full_path = self.base.clone();
449 full_path.push(path);
450 full_path
451 }
452
453 pub fn name(&self) -> &str {
454 &self.name
455 }
456
457 pub fn base_path(&self) -> PathBuf {
458 self.base.clone()
459 }
460
461 pub fn try_shared_lock(&self) -> Result<tools::ProcessLockSharedGuard, Error> {
462 tools::ProcessLocker::try_shared_lock(self.locker.clone())
463 }
464
465 pub fn try_exclusive_lock(&self) -> Result<tools::ProcessLockExclusiveGuard, Error> {
466 tools::ProcessLocker::try_exclusive_lock(self.locker.clone())
467 }
468 }
469
470
471 #[test]
472 fn test_chunk_store1() {
473
474 let mut path = std::fs::canonicalize(".").unwrap(); // we need absulute path
475 path.push(".testdir");
476
477 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
478
479 let chunk_store = ChunkStore::open("test", &path);
480 assert!(chunk_store.is_err());
481
482 let user = nix::unistd::User::from_uid(nix::unistd::Uid::current()).unwrap().unwrap();
483 let chunk_store = ChunkStore::create("test", &path, user.uid, user.gid).unwrap();
484
485 let (chunk, digest) = super::DataChunkBuilder::new(&[0u8, 1u8]).build().unwrap();
486
487 let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap();
488 assert!(!exists);
489
490 let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap();
491 assert!(exists);
492
493
494 let chunk_store = ChunkStore::create("test", &path, user.uid, user.gid);
495 assert!(chunk_store.is_err());
496
497 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
498 }