]> git.proxmox.com Git - proxmox-backup.git/blob - src/backup/chunk_store.rs
src/backup/data_blob.rs: new load_from_reader(), which verifies the CRC
[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 done: {}", 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)> + 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 {
223 continue;
224 }
225 if !bytes.iter().all(u8::is_ascii_hexdigit) {
226 continue;
227 }
228 return Some((Ok(entry), percentage));
229 }
230 Some(Err(err)) => {
231 // stop after first error
232 done = true;
233 // and pass the error through:
234 return Some((Err(err), percentage));
235 }
236 None => (), // open next directory
237 }
238 }
239
240 inner = None;
241
242 if at == 0x10000 {
243 done = true;
244 return None;
245 }
246
247 let subdir: &str = &format!("{:04x}", at);
248 percentage = (at * 100) / 0x10000;
249 at += 1;
250 match tools::fs::read_subdir(base_handle.as_raw_fd(), subdir) {
251 Ok(dir) => {
252 inner = Some(dir);
253 // start reading:
254 continue;
255 }
256 Err(ref err) if err.as_errno() == Some(nix::errno::Errno::ENOENT) => {
257 // non-existing directories are okay, just keep going:
258 continue;
259 }
260 Err(err) => {
261 // other errors are fatal, so end our iteration
262 done = true;
263 // and pass the error through:
264 return Some((Err(format_err!("unable to read subdir '{}' - {}", subdir, err)), percentage));
265 }
266 }
267 }
268 }).fuse())
269 }
270
271 pub fn oldest_writer(&self) -> Option<i64> {
272 tools::ProcessLocker::oldest_shared_lock(self.locker.clone())
273 }
274
275 pub fn sweep_unused_chunks(
276 &self,
277 oldest_writer: i64,
278 status: &mut GarbageCollectionStatus,
279 worker: &WorkerTask,
280 ) -> Result<(), Error> {
281 use nix::sys::stat::fstatat;
282
283 let now = unsafe { libc::time(std::ptr::null_mut()) };
284
285 let mut min_atime = now - 3600*24; // at least 24h (see mount option relatime)
286
287 if oldest_writer < min_atime {
288 min_atime = oldest_writer;
289 }
290
291 min_atime -= 300; // add 5 mins gap for safety
292
293 let mut last_percentage = 0;
294 let mut chunk_count = 0;
295
296 for (entry, percentage) in self.get_chunk_iterator()? {
297 if last_percentage != percentage {
298 last_percentage = percentage;
299 worker.log(format!("percentage done: {}, chunk count: {}", percentage, chunk_count));
300 }
301
302 worker.fail_on_abort()?;
303 tools::fail_on_shutdown()?;
304
305 let (dirfd, entry) = match entry {
306 Ok(entry) => (entry.parent_fd(), entry),
307 Err(err) => bail!("chunk iterator on chunk store '{}' failed - {}", self.name, err),
308 };
309
310 let file_type = match entry.file_type() {
311 Some(file_type) => file_type,
312 None => bail!("unsupported file system type on chunk store '{}'", self.name),
313 };
314 if file_type != nix::dir::Type::File {
315 continue;
316 }
317
318 chunk_count += 1;
319
320 let filename = entry.file_name();
321
322 let lock = self.mutex.lock();
323
324 if let Ok(stat) = fstatat(dirfd, filename, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) {
325 if stat.st_atime < min_atime {
326 //let age = now - stat.st_atime;
327 //println!("UNLINK {} {:?}", age/(3600*24), filename);
328 let res = unsafe { libc::unlinkat(dirfd, filename.as_ptr(), 0) };
329 if res != 0 {
330 let err = nix::Error::last();
331 bail!(
332 "unlink chunk {:?} failed on store '{}' - {}",
333 filename,
334 self.name,
335 err,
336 );
337 }
338 status.removed_chunks += 1;
339 status.removed_bytes += stat.st_size as u64;
340 } else {
341 if stat.st_atime < oldest_writer {
342 status.pending_chunks += 1;
343 status.pending_bytes += stat.st_size as u64;
344 } else {
345 status.disk_chunks += 1;
346 status.disk_bytes += stat.st_size as u64;
347 }
348 }
349 }
350 drop(lock);
351 }
352
353 Ok(())
354 }
355
356 pub fn insert_chunk(
357 &self,
358 chunk: &DataBlob,
359 digest: &[u8; 32],
360 ) -> Result<(bool, u64), Error> {
361
362 //println!("DIGEST {}", proxmox::tools::digest_to_hex(digest));
363
364 let (chunk_path, digest_str) = self.chunk_path(digest);
365
366 let lock = self.mutex.lock();
367
368 if let Ok(metadata) = std::fs::metadata(&chunk_path) {
369 if metadata.is_file() {
370 return Ok((true, metadata.len()));
371 } else {
372 bail!("Got unexpected file type on store '{}' for chunk {}", self.name, digest_str);
373 }
374 }
375
376 let mut tmp_path = chunk_path.clone();
377 tmp_path.set_extension("tmp");
378
379 let mut file = std::fs::File::create(&tmp_path)?;
380
381 let raw_data = chunk.raw_data();
382 let encoded_size = raw_data.len() as u64;
383
384 file.write_all(raw_data)?;
385
386 if let Err(err) = std::fs::rename(&tmp_path, &chunk_path) {
387 if let Err(_) = std::fs::remove_file(&tmp_path) { /* ignore */ }
388 bail!(
389 "Atomic rename on store '{}' failed for chunk {} - {}",
390 self.name,
391 digest_str,
392 err,
393 );
394 }
395
396 drop(lock);
397
398 Ok((false, encoded_size))
399 }
400
401 pub fn chunk_path(&self, digest:&[u8; 32]) -> (PathBuf, String) {
402 let mut chunk_path = self.chunk_dir.clone();
403 let prefix = digest_to_prefix(digest);
404 chunk_path.push(&prefix);
405 let digest_str = proxmox::tools::digest_to_hex(digest);
406 chunk_path.push(&digest_str);
407 (chunk_path, digest_str)
408 }
409
410 pub fn relative_path(&self, path: &Path) -> PathBuf {
411
412 let mut full_path = self.base.clone();
413 full_path.push(path);
414 full_path
415 }
416
417 pub fn name(&self) -> &str {
418 &self.name
419 }
420
421 pub fn base_path(&self) -> PathBuf {
422 self.base.clone()
423 }
424
425 pub fn try_shared_lock(&self) -> Result<tools::ProcessLockSharedGuard, Error> {
426 tools::ProcessLocker::try_shared_lock(self.locker.clone())
427 }
428
429 pub fn try_exclusive_lock(&self) -> Result<tools::ProcessLockExclusiveGuard, Error> {
430 tools::ProcessLocker::try_exclusive_lock(self.locker.clone())
431 }
432 }
433
434
435 #[test]
436 fn test_chunk_store1() {
437
438 let mut path = std::fs::canonicalize(".").unwrap(); // we need absulute path
439 path.push(".testdir");
440
441 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
442
443 let chunk_store = ChunkStore::open("test", &path);
444 assert!(chunk_store.is_err());
445
446 let user = nix::unistd::User::from_uid(nix::unistd::Uid::current()).unwrap().unwrap();
447 let chunk_store = ChunkStore::create("test", &path, user.uid, user.gid).unwrap();
448
449 let (chunk, digest) = super::DataChunkBuilder::new(&[0u8, 1u8]).build().unwrap();
450
451 let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap();
452 assert!(!exists);
453
454 let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap();
455 assert!(exists);
456
457
458 let chunk_store = ChunkStore::create("test", &path, user.uid, user.gid);
459 assert!(chunk_store.is_err());
460
461 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
462 }