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