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