]> git.proxmox.com Git - proxmox-backup.git/blame - src/backup/chunk_store.rs
clippy: use chars / byte string literals
[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;
f6b1d1cc 14use crate::task::TaskState;
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]);
d8d8af98 47 buf.push(b'/');
128b37fe
DM
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
44288184 83 match create_path(&base, Some(default_options), Some(options.clone())) {
c687da9e
SI
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 {
12c65bac 107 // eprintln!("ChunkStore::create {}%", percentage);
bc616633 108 last_percentage = percentage;
e95950e4 109 }
35cf5daa
DM
110 }
111
277fc5a3 112 Self::open(name, base)
35cf5daa
DM
113 }
114
7e210bd0 115 fn lockfile_path<P: Into<PathBuf>>(base: P) -> PathBuf {
44288184 116 let mut lockfile_path: PathBuf = base.into();
35cf5daa 117
7e210bd0
DM
118 lockfile_path.push(".lock");
119
120 lockfile_path
121 }
122
123 pub fn open<P: Into<PathBuf>>(name: &str, base: P) -> Result<Self, Error> {
124
125 let base: PathBuf = base.into();
68469eeb
DM
126
127 if !base.is_absolute() {
128 bail!("expected absolute path - got {:?}", base);
129 }
130
45773720
DM
131 let chunk_dir = Self::chunk_dir(&base);
132
ce55dbbc 133 if let Err(err) = std::fs::metadata(&chunk_dir) {
277fc5a3 134 bail!("unable to open chunk store '{}' at {:?} - {}", name, chunk_dir, err);
ce55dbbc 135 }
45773720 136
7e210bd0 137 let lockfile_path = Self::lockfile_path(&base);
45773720 138
43b13033 139 let locker = tools::ProcessLocker::new(&lockfile_path)?;
35cf5daa 140
b8d4766a 141 Ok(ChunkStore {
277fc5a3 142 name: name.to_owned(),
b8d4766a
DM
143 base,
144 chunk_dir,
43b13033 145 locker,
b8d4766a
DM
146 mutex: Mutex::new(false)
147 })
35cf5daa
DM
148 }
149
a660978c 150 pub fn touch_chunk(&self, digest: &[u8; 32]) -> Result<(), Error> {
2585a8a4
DM
151 self.cond_touch_chunk(digest, true)?;
152 Ok(())
153 }
154
155 pub fn cond_touch_chunk(&self, digest: &[u8; 32], fail_if_not_exist: bool) -> Result<bool, Error> {
a660978c 156 let (chunk_path, _digest_str) = self.chunk_path(digest);
fd192564
SR
157 self.cond_touch_path(&chunk_path, fail_if_not_exist)
158 }
3d5c11e5 159
fd192564 160 pub fn cond_touch_path(&self, path: &Path, fail_if_not_exist: bool) -> Result<bool, Error> {
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
fd192564 171 let res = 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
fd192564 181 bail!("update atime failed for chunk/file {:?} - {}", 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 228
d8d8af98 229 let bad = bytes.ends_with(b".bad");
a9767cf7 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,
f6b1d1cc 282 worker: &dyn TaskState,
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;
f6b1d1cc
WB
301 crate::task_log!(
302 worker,
7956877f 303 "processed {}% ({} chunks)",
f6b1d1cc
WB
304 percentage,
305 chunk_count,
306 );
a5736098 307 }
92da93b2 308
f6b1d1cc 309 worker.check_abort()?;
92da93b2
DM
310 tools::fail_on_shutdown()?;
311
fdd71f52 312 let (dirfd, entry) = match entry {
c7f481b6 313 Ok(entry) => (entry.parent_fd(), entry),
9850bcdf 314 Err(err) => bail!("chunk iterator on chunk store '{}' failed - {}", self.name, err),
eae8aa3a 315 };
fdd71f52 316
eae8aa3a
DM
317 let file_type = match entry.file_type() {
318 Some(file_type) => file_type,
277fc5a3 319 None => bail!("unsupported file system type on chunk store '{}'", self.name),
eae8aa3a 320 };
82bc0ad4
WB
321 if file_type != nix::dir::Type::File {
322 continue;
323 }
eae8aa3a 324
e4c2fbf1
DM
325 chunk_count += 1;
326
d85987ae
DM
327 let filename = entry.file_name();
328
15a77c4c
DM
329 let lock = self.mutex.lock();
330
9349d2a1 331 if let Ok(stat) = fstatat(dirfd, filename, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) {
fd192564 332 if stat.st_atime < min_atime {
cf459b19
DM
333 //let age = now - stat.st_atime;
334 //println!("UNLINK {} {:?}", age/(3600*24), filename);
a9767cf7 335 if let Err(err) = unlinkat(Some(dirfd), filename, UnlinkatFlags::NoRemoveDir) {
fd192564
SR
336 if bad {
337 status.still_bad += 1;
338 }
9349d2a1 339 bail!(
a9767cf7 340 "unlinking chunk {:?} failed on store '{}' - {}",
9349d2a1
WB
341 filename,
342 self.name,
343 err,
344 );
277fc5a3 345 }
fd192564
SR
346 if bad {
347 status.removed_bad += 1;
348 } else {
349 status.removed_chunks += 1;
350 }
a660978c 351 status.removed_bytes += stat.st_size as u64;
8db14689 352 } else if stat.st_atime < oldest_writer {
fd192564
SR
353 if bad {
354 status.still_bad += 1;
355 } else {
356 status.pending_chunks += 1;
357 }
8db14689 358 status.pending_bytes += stat.st_size as u64;
cf459b19 359 } else {
fd192564
SR
360 if !bad {
361 status.disk_chunks += 1;
362 }
8db14689 363 status.disk_bytes += stat.st_size as u64;
08481a0b 364 }
eae8aa3a 365 }
15a77c4c 366 drop(lock);
eae8aa3a 367 }
a5736098 368
277fc5a3 369 Ok(())
08481a0b
DM
370 }
371
f98ac774 372 pub fn insert_chunk(
9ac6ec86 373 &self,
4ee8f53d
DM
374 chunk: &DataBlob,
375 digest: &[u8; 32],
9ac6ec86 376 ) -> Result<(bool, u64), Error> {
7b2b40a8 377
bffd40d6 378 //println!("DIGEST {}", proxmox::tools::digest_to_hex(digest));
128b37fe 379
81a6ce6f 380 let (chunk_path, digest_str) = self.chunk_path(digest);
c5d82e5f
DM
381
382 let lock = self.mutex.lock();
383
384 if let Ok(metadata) = std::fs::metadata(&chunk_path) {
385 if metadata.is_file() {
068e5268 386 self.touch_chunk(digest)?;
9ac6ec86 387 return Ok((true, metadata.len()));
c5d82e5f 388 } else {
f7dd683b 389 bail!("Got unexpected file type on store '{}' for chunk {}", self.name, digest_str);
c5d82e5f
DM
390 }
391 }
128b37fe 392
c5d82e5f
DM
393 let mut tmp_path = chunk_path.clone();
394 tmp_path.set_extension("tmp");
78216a5a 395
f98ac774 396 let mut file = std::fs::File::create(&tmp_path)?;
78216a5a 397
f98ac774
DM
398 let raw_data = chunk.raw_data();
399 let encoded_size = raw_data.len() as u64;
78216a5a 400
f98ac774 401 file.write_all(raw_data)?;
128b37fe 402
c5d82e5f 403 if let Err(err) = std::fs::rename(&tmp_path, &chunk_path) {
3984a5fd 404 if std::fs::remove_file(&tmp_path).is_err() { /* ignore */ }
9349d2a1
WB
405 bail!(
406 "Atomic rename on store '{}' failed for chunk {} - {}",
407 self.name,
408 digest_str,
409 err,
410 );
c5d82e5f
DM
411 }
412
c5d82e5f
DM
413 drop(lock);
414
f98ac774 415 Ok((false, encoded_size))
128b37fe
DM
416 }
417
81a6ce6f
DM
418 pub fn chunk_path(&self, digest:&[u8; 32]) -> (PathBuf, String) {
419 let mut chunk_path = self.chunk_dir.clone();
420 let prefix = digest_to_prefix(digest);
421 chunk_path.push(&prefix);
422 let digest_str = proxmox::tools::digest_to_hex(digest);
423 chunk_path.push(&digest_str);
424 (chunk_path, digest_str)
425 }
426
606ce64b
DM
427 pub fn relative_path(&self, path: &Path) -> PathBuf {
428
429 let mut full_path = self.base.clone();
430 full_path.push(path);
431 full_path
432 }
433
92c3fd2e
DM
434 pub fn name(&self) -> &str {
435 &self.name
436 }
437
3d5c11e5
DM
438 pub fn base_path(&self) -> PathBuf {
439 self.base.clone()
440 }
43b13033
DM
441
442 pub fn try_shared_lock(&self) -> Result<tools::ProcessLockSharedGuard, Error> {
443 tools::ProcessLocker::try_shared_lock(self.locker.clone())
444 }
445
446 pub fn try_exclusive_lock(&self) -> Result<tools::ProcessLockExclusiveGuard, Error> {
447 tools::ProcessLocker::try_exclusive_lock(self.locker.clone())
448 }
35cf5daa
DM
449}
450
451
452#[test]
453fn test_chunk_store1() {
454
332dcc22
DM
455 let mut path = std::fs::canonicalize(".").unwrap(); // we need absulute path
456 path.push(".testdir");
457
35cf5daa
DM
458 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
459
332dcc22 460 let chunk_store = ChunkStore::open("test", &path);
35cf5daa
DM
461 assert!(chunk_store.is_err());
462
64599563
DM
463 let user = nix::unistd::User::from_uid(nix::unistd::Uid::current()).unwrap().unwrap();
464 let chunk_store = ChunkStore::create("test", &path, user.uid, user.gid).unwrap();
f98ac774 465
4ee8f53d 466 let (chunk, digest) = super::DataChunkBuilder::new(&[0u8, 1u8]).build().unwrap();
f98ac774 467
4ee8f53d 468 let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap();
391a2e43
DM
469 assert!(!exists);
470
4ee8f53d 471 let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap();
391a2e43 472 assert!(exists);
128b37fe 473
35cf5daa 474
64599563 475 let chunk_store = ChunkStore::create("test", &path, user.uid, user.gid);
35cf5daa
DM
476 assert!(chunk_store.is_err());
477
e0a5d1ca 478 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
35cf5daa 479}