]> git.proxmox.com Git - proxmox-backup.git/blame - src/backup/chunk_store.rs
backup: touch all chunks, even if they exist
[proxmox-backup.git] / src / backup / chunk_store.rs
CommitLineData
f7d4e4b5 1use anyhow::{bail, format_err, Error};
43b13033 2
35cf5daa 3use std::path::{Path, PathBuf};
f98ac774 4use std::io::Write;
43b13033
DM
5use std::sync::{Arc, Mutex};
6use std::os::unix::io::AsRawFd;
128b37fe 7
0b97bc61
DM
8use proxmox::tools::fs::{CreateOptions, create_path, create_dir};
9
365bb90f 10use crate::tools;
a92830dc
DM
11use crate::api2::types::GarbageCollectionStatus;
12
4ee8f53d 13use super::DataBlob;
a5736098 14use crate::server::WorkerTask;
365bb90f 15
e5064ba6 16/// File system based chunk store
35cf5daa 17pub struct ChunkStore {
277fc5a3 18 name: String, // used for error reporting
2c32fdde 19 pub (crate) base: PathBuf,
35cf5daa 20 chunk_dir: PathBuf,
c5d82e5f 21 mutex: Mutex<bool>,
43b13033 22 locker: Arc<Mutex<tools::ProcessLocker>>,
128b37fe
DM
23}
24
176e4af9
DM
25// TODO: what about sysctl setting vm.vfs_cache_pressure (0 - 100) ?
26
36898ffc 27pub fn verify_chunk_size(size: usize) -> Result<(), Error> {
247cdbce 28
36898ffc 29 static SIZES: [usize; 7] = [64*1024, 128*1024, 256*1024, 512*1024, 1024*1024, 2048*1024, 4096*1024];
247cdbce
DM
30
31 if !SIZES.contains(&size) {
32 bail!("Got unsupported chunk size '{}'", size);
33 }
34 Ok(())
35}
36
08481a0b 37fn digest_to_prefix(digest: &[u8]) -> PathBuf {
128b37fe 38
e95950e4 39 let mut buf = Vec::<u8>::with_capacity(2+1+2+1);
128b37fe 40
62ee2eb4 41 const HEX_CHARS: &[u8; 16] = b"0123456789abcdef";
22968600 42
128b37fe
DM
43 buf.push(HEX_CHARS[(digest[0] as usize) >> 4]);
44 buf.push(HEX_CHARS[(digest[0] as usize) &0xf]);
e95950e4 45 buf.push(HEX_CHARS[(digest[1] as usize) >> 4]);
128b37fe 46 buf.push(HEX_CHARS[(digest[1] as usize) & 0xf]);
128b37fe
DM
47 buf.push('/' as u8);
48
49 let path = unsafe { String::from_utf8_unchecked(buf)};
50
51 path.into()
35cf5daa
DM
52}
53
54impl ChunkStore {
55
45773720
DM
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
64599563 64 pub fn create<P>(name: &str, path: P, uid: nix::unistd::Uid, gid: nix::unistd::Gid) -> Result<Self, Error>
afdcfb5b
WB
65 where
66 P: Into<PathBuf>,
67 {
35cf5daa 68
45773720 69 let base: PathBuf = path.into();
68469eeb
DM
70
71 if !base.is_absolute() {
72 bail!("expected absolute path - got {:?}", base);
73 }
74
45773720 75 let chunk_dir = Self::chunk_dir(&base);
35cf5daa 76
e67770d4 77 let options = CreateOptions::new()
64599563
DM
78 .owner(uid)
79 .group(gid);
e67770d4 80
0b97bc61
DM
81 let default_options = CreateOptions::new();
82
c687da9e
SI
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))? },
2989f6bf
DM
86 }
87
0b97bc61 88 if let Err(err) = create_dir(&chunk_dir, options.clone()) {
277fc5a3 89 bail!("unable to create chunk store '{}' subdir {:?} - {}", name, chunk_dir, err);
2989f6bf 90 }
35cf5daa 91
7e210bd0
DM
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
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));
0b97bc61 102 if let Err(err) = create_dir(&l1path, options.clone()) {
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 {
49a92084 107 eprintln!("{}%", percentage);
bc616633 108 last_percentage = percentage;
e95950e4 109 }
35cf5daa
DM
110 }
111
7e210bd0 112
277fc5a3 113 Self::open(name, base)
35cf5daa
DM
114 }
115
7e210bd0
DM
116 fn lockfile_path<P: Into<PathBuf>>(base: P) -> PathBuf {
117 let base: PathBuf = base.into();
35cf5daa 118
7e210bd0
DM
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();
68469eeb
DM
128
129 if !base.is_absolute() {
130 bail!("expected absolute path - got {:?}", base);
131 }
132
45773720
DM
133 let chunk_dir = Self::chunk_dir(&base);
134
ce55dbbc 135 if let Err(err) = std::fs::metadata(&chunk_dir) {
277fc5a3 136 bail!("unable to open chunk store '{}' at {:?} - {}", name, chunk_dir, err);
ce55dbbc 137 }
45773720 138
7e210bd0 139 let lockfile_path = Self::lockfile_path(&base);
45773720 140
43b13033 141 let locker = tools::ProcessLocker::new(&lockfile_path)?;
35cf5daa 142
b8d4766a 143 Ok(ChunkStore {
277fc5a3 144 name: name.to_owned(),
b8d4766a
DM
145 base,
146 chunk_dir,
43b13033 147 locker,
b8d4766a
DM
148 mutex: Mutex::new(false)
149 })
35cf5daa
DM
150 }
151
a660978c 152 pub fn touch_chunk(&self, digest: &[u8; 32]) -> Result<(), Error> {
2585a8a4
DM
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> {
3d5c11e5 158
a660978c 159 let (chunk_path, _digest_str) = self.chunk_path(digest);
3d5c11e5 160
07ce44a6
DM
161 const UTIME_NOW: i64 = (1 << 30) - 1;
162 const UTIME_OMIT: i64 = (1 << 30) - 2;
7ee2aa1b 163
a198d74f 164 let times: [libc::timespec; 2] = [
7ee2aa1b
DM
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 {
2585a8a4
DM
172 let tmp = libc::utimensat(-1, cstr.as_ptr(), &times[0], libc::AT_SYMLINK_NOFOLLOW);
173 nix::errno::Errno::result(tmp)
7ee2aa1b
DM
174 })?;
175
2585a8a4
DM
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
b96b11cd 181 bail!("update atime failed for chunk {:?} - {}", chunk_path, err);
7ee2aa1b
DM
182 }
183
2585a8a4 184 Ok(true)
3d5c11e5
DM
185 }
186
9739aca4
WB
187 pub fn get_chunk_iterator(
188 &self,
189 ) -> Result<
a9767cf7 190 impl Iterator<Item = (Result<tools::fs::ReadDirEntry, Error>, usize, bool)> + std::iter::FusedIterator,
9739aca4
WB
191 Error
192 > {
193 use nix::dir::Dir;
194 use nix::fcntl::OFlag;
195 use nix::sys::stat::Mode;
196
a24e3993
DM
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 })?;
9739aca4 206
a3f3e91d
WB
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();
a9767cf7 222 if bytes.len() != 64 && bytes.len() != 64 + ".0.bad".len() {
a3f3e91d
WB
223 continue;
224 }
a9767cf7 225 if !bytes.iter().take(64).all(u8::is_ascii_hexdigit) {
a3f3e91d
WB
226 continue;
227 }
a9767cf7
SR
228
229 let bad = bytes.ends_with(".bad".as_bytes());
230 return Some((Ok(entry), percentage, bad));
a3f3e91d
WB
231 }
232 Some(Err(err)) => {
233 // stop after first error
234 done = true;
235 // and pass the error through:
a9767cf7 236 return Some((Err(err), percentage, false));
a3f3e91d
WB
237 }
238 None => (), // open next directory
c7f481b6 239 }
c7f481b6 240 }
a3f3e91d
WB
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:
a9767cf7 266 return Some((Err(format_err!("unable to read subdir '{}' - {}", subdir, err)), percentage, false));
a3f3e91d 267 }
62f2422f
WB
268 }
269 }
a3f3e91d 270 }).fuse())
c7f481b6
WB
271 }
272
11861a48
DM
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,
cf459b19 279 oldest_writer: i64,
d3d566f7 280 phase1_start_time: i64,
a5736098 281 status: &mut GarbageCollectionStatus,
99641a6b 282 worker: &WorkerTask,
11861a48 283 ) -> Result<(), Error> {
9349d2a1 284 use nix::sys::stat::fstatat;
a9767cf7 285 use nix::unistd::{unlinkat, UnlinkatFlags};
08481a0b 286
d3d566f7 287 let mut min_atime = phase1_start_time - 3600*24; // at least 24h (see mount option relatime)
11861a48 288
cf459b19
DM
289 if oldest_writer < min_atime {
290 min_atime = oldest_writer;
11861a48
DM
291 }
292
293 min_atime -= 300; // add 5 mins gap for safety
294
a5736098 295 let mut last_percentage = 0;
e4c2fbf1
DM
296 let mut chunk_count = 0;
297
a9767cf7 298 for (entry, percentage, bad) in self.get_chunk_iterator()? {
a5736098
DM
299 if last_percentage != percentage {
300 last_percentage = percentage;
8317873c 301 worker.log(format!("percentage done: phase2 {}% (processed {} chunks)", percentage, chunk_count));
a5736098 302 }
92da93b2 303
99641a6b 304 worker.fail_on_abort()?;
92da93b2
DM
305 tools::fail_on_shutdown()?;
306
fdd71f52 307 let (dirfd, entry) = match entry {
c7f481b6 308 Ok(entry) => (entry.parent_fd(), entry),
9850bcdf 309 Err(err) => bail!("chunk iterator on chunk store '{}' failed - {}", self.name, err),
eae8aa3a 310 };
fdd71f52 311
eae8aa3a
DM
312 let file_type = match entry.file_type() {
313 Some(file_type) => file_type,
277fc5a3 314 None => bail!("unsupported file system type on chunk store '{}'", self.name),
eae8aa3a 315 };
82bc0ad4
WB
316 if file_type != nix::dir::Type::File {
317 continue;
318 }
eae8aa3a 319
e4c2fbf1
DM
320 chunk_count += 1;
321
d85987ae
DM
322 let filename = entry.file_name();
323
15a77c4c
DM
324 let lock = self.mutex.lock();
325
9349d2a1 326 if let Ok(stat) = fstatat(dirfd, filename, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) {
a9767cf7
SR
327 if bad {
328 match std::ffi::CString::new(&filename.to_bytes()[..64]) {
329 Ok(orig_filename) => {
330 match fstatat(
331 dirfd,
332 orig_filename.as_c_str(),
333 nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW)
334 {
335 Ok(_) => { /* do nothing */ },
336 Err(nix::Error::Sys(nix::errno::Errno::ENOENT)) => {
337 // chunk hasn't been rewritten yet, keep
338 // .bad file around for manual recovery
339 continue;
340 },
341 Err(err) => {
342 // some other error, warn user and keep
343 // .bad file around too
344 worker.warn(format!(
345 "error during stat on '{:?}' - {}",
346 orig_filename,
347 err,
348 ));
349 continue;
350 }
351 }
352 },
353 Err(err) => {
354 worker.warn(format!(
355 "could not get original filename from .bad file '{:?}' - {}",
356 filename,
357 err,
358 ));
359 continue;
360 }
361 }
362
363 if let Err(err) = unlinkat(Some(dirfd), filename, UnlinkatFlags::NoRemoveDir) {
364 worker.warn(format!(
365 "unlinking corrupt chunk {:?} failed on store '{}' - {}",
366 filename,
367 self.name,
368 err,
369 ));
370 } else {
371 status.removed_bad += 1;
372 status.removed_bytes += stat.st_size as u64;
373 }
374 } else if stat.st_atime < min_atime {
cf459b19
DM
375 //let age = now - stat.st_atime;
376 //println!("UNLINK {} {:?}", age/(3600*24), filename);
a9767cf7 377 if let Err(err) = unlinkat(Some(dirfd), filename, UnlinkatFlags::NoRemoveDir) {
9349d2a1 378 bail!(
a9767cf7 379 "unlinking chunk {:?} failed on store '{}' - {}",
9349d2a1
WB
380 filename,
381 self.name,
382 err,
383 );
277fc5a3 384 }
a660978c
DM
385 status.removed_chunks += 1;
386 status.removed_bytes += stat.st_size as u64;
cf459b19
DM
387 } else {
388 if stat.st_atime < oldest_writer {
389 status.pending_chunks += 1;
390 status.pending_bytes += stat.st_size as u64;
391 } else {
392 status.disk_chunks += 1;
393 status.disk_bytes += stat.st_size as u64;
394 }
08481a0b 395 }
eae8aa3a 396 }
15a77c4c 397 drop(lock);
eae8aa3a 398 }
a5736098 399
277fc5a3 400 Ok(())
08481a0b
DM
401 }
402
f98ac774 403 pub fn insert_chunk(
9ac6ec86 404 &self,
4ee8f53d
DM
405 chunk: &DataBlob,
406 digest: &[u8; 32],
9ac6ec86 407 ) -> Result<(bool, u64), Error> {
7b2b40a8 408
bffd40d6 409 //println!("DIGEST {}", proxmox::tools::digest_to_hex(digest));
128b37fe 410
81a6ce6f 411 let (chunk_path, digest_str) = self.chunk_path(digest);
c5d82e5f
DM
412
413 let lock = self.mutex.lock();
414
415 if let Ok(metadata) = std::fs::metadata(&chunk_path) {
416 if metadata.is_file() {
068e5268 417 self.touch_chunk(digest)?;
9ac6ec86 418 return Ok((true, metadata.len()));
c5d82e5f 419 } else {
f7dd683b 420 bail!("Got unexpected file type on store '{}' for chunk {}", self.name, digest_str);
c5d82e5f
DM
421 }
422 }
128b37fe 423
c5d82e5f
DM
424 let mut tmp_path = chunk_path.clone();
425 tmp_path.set_extension("tmp");
78216a5a 426
f98ac774 427 let mut file = std::fs::File::create(&tmp_path)?;
78216a5a 428
f98ac774
DM
429 let raw_data = chunk.raw_data();
430 let encoded_size = raw_data.len() as u64;
78216a5a 431
f98ac774 432 file.write_all(raw_data)?;
128b37fe 433
c5d82e5f
DM
434 if let Err(err) = std::fs::rename(&tmp_path, &chunk_path) {
435 if let Err(_) = std::fs::remove_file(&tmp_path) { /* ignore */ }
9349d2a1
WB
436 bail!(
437 "Atomic rename on store '{}' failed for chunk {} - {}",
438 self.name,
439 digest_str,
440 err,
441 );
c5d82e5f
DM
442 }
443
c5d82e5f
DM
444 drop(lock);
445
f98ac774 446 Ok((false, encoded_size))
128b37fe
DM
447 }
448
81a6ce6f
DM
449 pub fn chunk_path(&self, digest:&[u8; 32]) -> (PathBuf, String) {
450 let mut chunk_path = self.chunk_dir.clone();
451 let prefix = digest_to_prefix(digest);
452 chunk_path.push(&prefix);
453 let digest_str = proxmox::tools::digest_to_hex(digest);
454 chunk_path.push(&digest_str);
455 (chunk_path, digest_str)
456 }
457
606ce64b
DM
458 pub fn relative_path(&self, path: &Path) -> PathBuf {
459
460 let mut full_path = self.base.clone();
461 full_path.push(path);
462 full_path
463 }
464
92c3fd2e
DM
465 pub fn name(&self) -> &str {
466 &self.name
467 }
468
3d5c11e5
DM
469 pub fn base_path(&self) -> PathBuf {
470 self.base.clone()
471 }
43b13033
DM
472
473 pub fn try_shared_lock(&self) -> Result<tools::ProcessLockSharedGuard, Error> {
474 tools::ProcessLocker::try_shared_lock(self.locker.clone())
475 }
476
477 pub fn try_exclusive_lock(&self) -> Result<tools::ProcessLockExclusiveGuard, Error> {
478 tools::ProcessLocker::try_exclusive_lock(self.locker.clone())
479 }
35cf5daa
DM
480}
481
482
483#[test]
484fn test_chunk_store1() {
485
332dcc22
DM
486 let mut path = std::fs::canonicalize(".").unwrap(); // we need absulute path
487 path.push(".testdir");
488
35cf5daa
DM
489 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
490
332dcc22 491 let chunk_store = ChunkStore::open("test", &path);
35cf5daa
DM
492 assert!(chunk_store.is_err());
493
64599563
DM
494 let user = nix::unistd::User::from_uid(nix::unistd::Uid::current()).unwrap().unwrap();
495 let chunk_store = ChunkStore::create("test", &path, user.uid, user.gid).unwrap();
f98ac774 496
4ee8f53d 497 let (chunk, digest) = super::DataChunkBuilder::new(&[0u8, 1u8]).build().unwrap();
f98ac774 498
4ee8f53d 499 let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap();
391a2e43
DM
500 assert!(!exists);
501
4ee8f53d 502 let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap();
391a2e43 503 assert!(exists);
128b37fe 504
35cf5daa 505
64599563 506 let chunk_store = ChunkStore::create("test", &path, user.uid, user.gid);
35cf5daa
DM
507 assert!(chunk_store.is_err());
508
e0a5d1ca 509 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
35cf5daa 510}