]> git.proxmox.com Git - proxmox-backup.git/blob - src/backup/datastore.rs
gc: don't limit index listing to same filesystem
[proxmox-backup.git] / src / backup / datastore.rs
1 use std::collections::{HashSet, HashMap};
2 use std::io::{self, Write};
3 use std::path::{Path, PathBuf};
4 use std::sync::{Arc, Mutex};
5 use std::convert::TryFrom;
6 use std::str::FromStr;
7 use std::time::Duration;
8 use std::fs::File;
9
10 use anyhow::{bail, format_err, Error};
11 use lazy_static::lazy_static;
12
13 use proxmox::tools::fs::{replace_file, file_read_optional_string, CreateOptions, open_file_locked};
14
15 use super::backup_info::{BackupGroup, BackupDir};
16 use super::chunk_store::ChunkStore;
17 use super::dynamic_index::{DynamicIndexReader, DynamicIndexWriter};
18 use super::fixed_index::{FixedIndexReader, FixedIndexWriter};
19 use super::manifest::{MANIFEST_BLOB_NAME, MANIFEST_LOCK_NAME, CLIENT_LOG_BLOB_NAME, BackupManifest};
20 use super::index::*;
21 use super::{DataBlob, ArchiveType, archive_type};
22 use crate::config::datastore::{self, DataStoreConfig};
23 use crate::task::TaskState;
24 use crate::tools;
25 use crate::tools::format::HumanByte;
26 use crate::tools::fs::{lock_dir_noblock, DirLockGuard};
27 use crate::api2::types::{Authid, GarbageCollectionStatus};
28 use crate::server::UPID;
29
30 lazy_static! {
31 static ref DATASTORE_MAP: Mutex<HashMap<String, Arc<DataStore>>> = Mutex::new(HashMap::new());
32 }
33
34 /// Datastore Management
35 ///
36 /// A Datastore can store severals backups, and provides the
37 /// management interface for backup.
38 pub struct DataStore {
39 chunk_store: Arc<ChunkStore>,
40 gc_mutex: Mutex<bool>,
41 last_gc_status: Mutex<GarbageCollectionStatus>,
42 verify_new: bool,
43 }
44
45 impl DataStore {
46
47 pub fn lookup_datastore(name: &str) -> Result<Arc<DataStore>, Error> {
48
49 let (config, _digest) = datastore::config()?;
50 let config: datastore::DataStoreConfig = config.lookup("datastore", name)?;
51 let path = PathBuf::from(&config.path);
52
53 let mut map = DATASTORE_MAP.lock().unwrap();
54
55 if let Some(datastore) = map.get(name) {
56 // Compare Config - if changed, create new Datastore object!
57 if datastore.chunk_store.base == path &&
58 datastore.verify_new == config.verify_new.unwrap_or(false)
59 {
60 return Ok(datastore.clone());
61 }
62 }
63
64 let datastore = DataStore::open_with_path(name, &path, config)?;
65
66 let datastore = Arc::new(datastore);
67 map.insert(name.to_string(), datastore.clone());
68
69 Ok(datastore)
70 }
71
72 fn open_with_path(store_name: &str, path: &Path, config: DataStoreConfig) -> Result<Self, Error> {
73 let chunk_store = ChunkStore::open(store_name, path)?;
74
75 let mut gc_status_path = chunk_store.base_path();
76 gc_status_path.push(".gc-status");
77
78 let gc_status = if let Some(state) = file_read_optional_string(gc_status_path)? {
79 match serde_json::from_str(&state) {
80 Ok(state) => state,
81 Err(err) => {
82 eprintln!("error reading gc-status: {}", err);
83 GarbageCollectionStatus::default()
84 }
85 }
86 } else {
87 GarbageCollectionStatus::default()
88 };
89
90 Ok(Self {
91 chunk_store: Arc::new(chunk_store),
92 gc_mutex: Mutex::new(false),
93 last_gc_status: Mutex::new(gc_status),
94 verify_new: config.verify_new.unwrap_or(false),
95 })
96 }
97
98 pub fn get_chunk_iterator(
99 &self,
100 ) -> Result<
101 impl Iterator<Item = (Result<tools::fs::ReadDirEntry, Error>, usize, bool)>,
102 Error
103 > {
104 self.chunk_store.get_chunk_iterator()
105 }
106
107 pub fn create_fixed_writer<P: AsRef<Path>>(&self, filename: P, size: usize, chunk_size: usize) -> Result<FixedIndexWriter, Error> {
108
109 let index = FixedIndexWriter::create(self.chunk_store.clone(), filename.as_ref(), size, chunk_size)?;
110
111 Ok(index)
112 }
113
114 pub fn open_fixed_reader<P: AsRef<Path>>(&self, filename: P) -> Result<FixedIndexReader, Error> {
115
116 let full_path = self.chunk_store.relative_path(filename.as_ref());
117
118 let index = FixedIndexReader::open(&full_path)?;
119
120 Ok(index)
121 }
122
123 pub fn create_dynamic_writer<P: AsRef<Path>>(
124 &self, filename: P,
125 ) -> Result<DynamicIndexWriter, Error> {
126
127 let index = DynamicIndexWriter::create(
128 self.chunk_store.clone(), filename.as_ref())?;
129
130 Ok(index)
131 }
132
133 pub fn open_dynamic_reader<P: AsRef<Path>>(&self, filename: P) -> Result<DynamicIndexReader, Error> {
134
135 let full_path = self.chunk_store.relative_path(filename.as_ref());
136
137 let index = DynamicIndexReader::open(&full_path)?;
138
139 Ok(index)
140 }
141
142 pub fn open_index<P>(&self, filename: P) -> Result<Box<dyn IndexFile + Send>, Error>
143 where
144 P: AsRef<Path>,
145 {
146 let filename = filename.as_ref();
147 let out: Box<dyn IndexFile + Send> =
148 match archive_type(filename)? {
149 ArchiveType::DynamicIndex => Box::new(self.open_dynamic_reader(filename)?),
150 ArchiveType::FixedIndex => Box::new(self.open_fixed_reader(filename)?),
151 _ => bail!("cannot open index file of unknown type: {:?}", filename),
152 };
153 Ok(out)
154 }
155
156 pub fn name(&self) -> &str {
157 self.chunk_store.name()
158 }
159
160 pub fn base_path(&self) -> PathBuf {
161 self.chunk_store.base_path()
162 }
163
164 /// Cleanup a backup directory
165 ///
166 /// Removes all files not mentioned in the manifest.
167 pub fn cleanup_backup_dir(&self, backup_dir: &BackupDir, manifest: &BackupManifest
168 ) -> Result<(), Error> {
169
170 let mut full_path = self.base_path();
171 full_path.push(backup_dir.relative_path());
172
173 let mut wanted_files = HashSet::new();
174 wanted_files.insert(MANIFEST_BLOB_NAME.to_string());
175 wanted_files.insert(CLIENT_LOG_BLOB_NAME.to_string());
176 manifest.files().iter().for_each(|item| { wanted_files.insert(item.filename.clone()); });
177
178 for item in tools::fs::read_subdir(libc::AT_FDCWD, &full_path)? {
179 if let Ok(item) = item {
180 if let Some(file_type) = item.file_type() {
181 if file_type != nix::dir::Type::File { continue; }
182 }
183 let file_name = item.file_name().to_bytes();
184 if file_name == b"." || file_name == b".." { continue; };
185
186 if let Ok(name) = std::str::from_utf8(file_name) {
187 if wanted_files.contains(name) { continue; }
188 }
189 println!("remove unused file {:?}", item.file_name());
190 let dirfd = item.parent_fd();
191 let _res = unsafe { libc::unlinkat(dirfd, item.file_name().as_ptr(), 0) };
192 }
193 }
194
195 Ok(())
196 }
197
198 /// Returns the absolute path for a backup_group
199 pub fn group_path(&self, backup_group: &BackupGroup) -> PathBuf {
200 let mut full_path = self.base_path();
201 full_path.push(backup_group.group_path());
202 full_path
203 }
204
205 /// Returns the absolute path for backup_dir
206 pub fn snapshot_path(&self, backup_dir: &BackupDir) -> PathBuf {
207 let mut full_path = self.base_path();
208 full_path.push(backup_dir.relative_path());
209 full_path
210 }
211
212 /// Remove a complete backup group including all snapshots
213 pub fn remove_backup_group(&self, backup_group: &BackupGroup) -> Result<(), Error> {
214
215 let full_path = self.group_path(backup_group);
216
217 let _guard = tools::fs::lock_dir_noblock(&full_path, "backup group", "possible running backup")?;
218
219 log::info!("removing backup group {:?}", full_path);
220
221 // remove all individual backup dirs first to ensure nothing is using them
222 for snap in backup_group.list_backups(&self.base_path())? {
223 self.remove_backup_dir(&snap.backup_dir, false)?;
224 }
225
226 // no snapshots left, we can now safely remove the empty folder
227 std::fs::remove_dir_all(&full_path)
228 .map_err(|err| {
229 format_err!(
230 "removing backup group directory {:?} failed - {}",
231 full_path,
232 err,
233 )
234 })?;
235
236 Ok(())
237 }
238
239 /// Remove a backup directory including all content
240 pub fn remove_backup_dir(&self, backup_dir: &BackupDir, force: bool) -> Result<(), Error> {
241
242 let full_path = self.snapshot_path(backup_dir);
243
244 let (_guard, _manifest_guard);
245 if !force {
246 _guard = lock_dir_noblock(&full_path, "snapshot", "possibly running or in use")?;
247 _manifest_guard = self.lock_manifest(backup_dir);
248 }
249
250 log::info!("removing backup snapshot {:?}", full_path);
251 std::fs::remove_dir_all(&full_path)
252 .map_err(|err| {
253 format_err!(
254 "removing backup snapshot {:?} failed - {}",
255 full_path,
256 err,
257 )
258 })?;
259
260 Ok(())
261 }
262
263 /// Returns the time of the last successful backup
264 ///
265 /// Or None if there is no backup in the group (or the group dir does not exist).
266 pub fn last_successful_backup(&self, backup_group: &BackupGroup) -> Result<Option<i64>, Error> {
267 let base_path = self.base_path();
268 let mut group_path = base_path.clone();
269 group_path.push(backup_group.group_path());
270
271 if group_path.exists() {
272 backup_group.last_successful_backup(&base_path)
273 } else {
274 Ok(None)
275 }
276 }
277
278 /// Returns the backup owner.
279 ///
280 /// The backup owner is the entity who first created the backup group.
281 pub fn get_owner(&self, backup_group: &BackupGroup) -> Result<Authid, Error> {
282 let mut full_path = self.base_path();
283 full_path.push(backup_group.group_path());
284 full_path.push("owner");
285 let owner = proxmox::tools::fs::file_read_firstline(full_path)?;
286 Ok(owner.trim_end().parse()?) // remove trailing newline
287 }
288
289 /// Set the backup owner.
290 pub fn set_owner(
291 &self,
292 backup_group: &BackupGroup,
293 auth_id: &Authid,
294 force: bool,
295 ) -> Result<(), Error> {
296 let mut path = self.base_path();
297 path.push(backup_group.group_path());
298 path.push("owner");
299
300 let mut open_options = std::fs::OpenOptions::new();
301 open_options.write(true);
302 open_options.truncate(true);
303
304 if force {
305 open_options.create(true);
306 } else {
307 open_options.create_new(true);
308 }
309
310 let mut file = open_options.open(&path)
311 .map_err(|err| format_err!("unable to create owner file {:?} - {}", path, err))?;
312
313 writeln!(file, "{}", auth_id)
314 .map_err(|err| format_err!("unable to write owner file {:?} - {}", path, err))?;
315
316 Ok(())
317 }
318
319 /// Create (if it does not already exists) and lock a backup group
320 ///
321 /// And set the owner to 'userid'. If the group already exists, it returns the
322 /// current owner (instead of setting the owner).
323 ///
324 /// This also acquires an exclusive lock on the directory and returns the lock guard.
325 pub fn create_locked_backup_group(
326 &self,
327 backup_group: &BackupGroup,
328 auth_id: &Authid,
329 ) -> Result<(Authid, DirLockGuard), Error> {
330 // create intermediate path first:
331 let base_path = self.base_path();
332
333 let mut full_path = base_path.clone();
334 full_path.push(backup_group.backup_type());
335 std::fs::create_dir_all(&full_path)?;
336
337 full_path.push(backup_group.backup_id());
338
339 // create the last component now
340 match std::fs::create_dir(&full_path) {
341 Ok(_) => {
342 let guard = lock_dir_noblock(&full_path, "backup group", "another backup is already running")?;
343 self.set_owner(backup_group, auth_id, false)?;
344 let owner = self.get_owner(backup_group)?; // just to be sure
345 Ok((owner, guard))
346 }
347 Err(ref err) if err.kind() == io::ErrorKind::AlreadyExists => {
348 let guard = lock_dir_noblock(&full_path, "backup group", "another backup is already running")?;
349 let owner = self.get_owner(backup_group)?; // just to be sure
350 Ok((owner, guard))
351 }
352 Err(err) => bail!("unable to create backup group {:?} - {}", full_path, err),
353 }
354 }
355
356 /// Creates a new backup snapshot inside a BackupGroup
357 ///
358 /// The BackupGroup directory needs to exist.
359 pub fn create_locked_backup_dir(&self, backup_dir: &BackupDir)
360 -> Result<(PathBuf, bool, DirLockGuard), Error>
361 {
362 let relative_path = backup_dir.relative_path();
363 let mut full_path = self.base_path();
364 full_path.push(&relative_path);
365
366 let lock = ||
367 lock_dir_noblock(&full_path, "snapshot", "internal error - tried creating snapshot that's already in use");
368
369 match std::fs::create_dir(&full_path) {
370 Ok(_) => Ok((relative_path, true, lock()?)),
371 Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => Ok((relative_path, false, lock()?)),
372 Err(e) => Err(e.into())
373 }
374 }
375
376 pub fn list_images(&self) -> Result<Vec<PathBuf>, Error> {
377 let base = self.base_path();
378
379 let mut list = vec![];
380
381 use walkdir::WalkDir;
382
383 let walker = WalkDir::new(&base).into_iter();
384
385 // make sure we skip .chunks (and other hidden files to keep it simple)
386 fn is_hidden(entry: &walkdir::DirEntry) -> bool {
387 entry.file_name()
388 .to_str()
389 .map(|s| s.starts_with("."))
390 .unwrap_or(false)
391 }
392 let handle_entry_err = |err: walkdir::Error| {
393 if let Some(inner) = err.io_error() {
394 let path = err.path().unwrap_or(Path::new(""));
395 match inner.kind() {
396 io::ErrorKind::PermissionDenied => {
397 // only allow to skip ext4 fsck directory, avoid GC if, for example,
398 // a user got file permissions wrong on datastore rsync to new server
399 if err.depth() > 1 || !path.ends_with("lost+found") {
400 bail!("cannot continue garbage-collection safely, permission denied on: {}", path.display())
401 }
402 },
403 _ => bail!("unexpected error on datastore traversal: {} - {}", inner, path.display()),
404 }
405 }
406 Ok(())
407 };
408 for entry in walker.filter_entry(|e| !is_hidden(e)) {
409 let path = match entry {
410 Ok(entry) => entry.into_path(),
411 Err(err) => {
412 handle_entry_err(err)?;
413 continue
414 },
415 };
416 if let Ok(archive_type) = archive_type(&path) {
417 if archive_type == ArchiveType::FixedIndex || archive_type == ArchiveType::DynamicIndex {
418 list.push(path);
419 }
420 }
421 }
422
423 Ok(list)
424 }
425
426 // mark chunks used by ``index`` as used
427 fn index_mark_used_chunks<I: IndexFile>(
428 &self,
429 index: I,
430 file_name: &Path, // only used for error reporting
431 status: &mut GarbageCollectionStatus,
432 worker: &dyn TaskState,
433 ) -> Result<(), Error> {
434
435 status.index_file_count += 1;
436 status.index_data_bytes += index.index_bytes();
437
438 for pos in 0..index.index_count() {
439 worker.check_abort()?;
440 tools::fail_on_shutdown()?;
441 let digest = index.index_digest(pos).unwrap();
442 if let Err(err) = self.chunk_store.touch_chunk(digest) {
443 crate::task_warn!(
444 worker,
445 "warning: unable to access chunk {}, required by {:?} - {}",
446 proxmox::tools::digest_to_hex(digest),
447 file_name,
448 err,
449 );
450
451 // touch any corresponding .bad files to keep them around, meaning if a chunk is
452 // rewritten correctly they will be removed automatically, as well as if no index
453 // file requires the chunk anymore (won't get to this loop then)
454 for i in 0..=9 {
455 let bad_ext = format!("{}.bad", i);
456 let mut bad_path = PathBuf::new();
457 bad_path.push(self.chunk_path(digest).0);
458 bad_path.set_extension(bad_ext);
459 self.chunk_store.cond_touch_path(&bad_path, false)?;
460 }
461 }
462 }
463 Ok(())
464 }
465
466 fn mark_used_chunks(
467 &self,
468 status: &mut GarbageCollectionStatus,
469 worker: &dyn TaskState,
470 ) -> Result<(), Error> {
471
472 let image_list = self.list_images()?;
473 let image_count = image_list.len();
474
475 let mut done = 0;
476 let mut last_percentage: usize = 0;
477
478 let mut strange_paths_count: u64 = 0;
479
480 for img in image_list {
481
482 worker.check_abort()?;
483 tools::fail_on_shutdown()?;
484
485 if let Some(backup_dir_path) = img.parent() {
486 let backup_dir_path = backup_dir_path.strip_prefix(self.base_path())?;
487 if let Some(backup_dir_str) = backup_dir_path.to_str() {
488 if BackupDir::from_str(backup_dir_str).is_err() {
489 strange_paths_count += 1;
490 }
491 }
492 }
493
494 match std::fs::File::open(&img) {
495 Ok(file) => {
496 if let Ok(archive_type) = archive_type(&img) {
497 if archive_type == ArchiveType::FixedIndex {
498 let index = FixedIndexReader::new(file).map_err(|e| {
499 format_err!("can't read index '{}' - {}", img.to_string_lossy(), e)
500 })?;
501 self.index_mark_used_chunks(index, &img, status, worker)?;
502 } else if archive_type == ArchiveType::DynamicIndex {
503 let index = DynamicIndexReader::new(file).map_err(|e| {
504 format_err!("can't read index '{}' - {}", img.to_string_lossy(), e)
505 })?;
506 self.index_mark_used_chunks(index, &img, status, worker)?;
507 }
508 }
509 }
510 Err(err) if err.kind() == io::ErrorKind::NotFound => (), // ignore vanished files
511 Err(err) => bail!("can't open index {} - {}", img.to_string_lossy(), err),
512 }
513 done += 1;
514
515 let percentage = done*100/image_count;
516 if percentage > last_percentage {
517 crate::task_log!(
518 worker,
519 "marked {}% ({} of {} index files)",
520 percentage,
521 done,
522 image_count,
523 );
524 last_percentage = percentage;
525 }
526 }
527
528 if strange_paths_count > 0 {
529 crate::task_log!(
530 worker,
531 "found (and marked) {} index files outside of expected directory scheme",
532 strange_paths_count,
533 );
534 }
535
536
537 Ok(())
538 }
539
540 pub fn last_gc_status(&self) -> GarbageCollectionStatus {
541 self.last_gc_status.lock().unwrap().clone()
542 }
543
544 pub fn garbage_collection_running(&self) -> bool {
545 if let Ok(_) = self.gc_mutex.try_lock() { false } else { true }
546 }
547
548 pub fn garbage_collection(&self, worker: &dyn TaskState, upid: &UPID) -> Result<(), Error> {
549
550 if let Ok(ref mut _mutex) = self.gc_mutex.try_lock() {
551
552 // avoids that we run GC if an old daemon process has still a
553 // running backup writer, which is not save as we have no "oldest
554 // writer" information and thus no safe atime cutoff
555 let _exclusive_lock = self.chunk_store.try_exclusive_lock()?;
556
557 let phase1_start_time = proxmox::tools::time::epoch_i64();
558 let oldest_writer = self.chunk_store.oldest_writer().unwrap_or(phase1_start_time);
559
560 let mut gc_status = GarbageCollectionStatus::default();
561 gc_status.upid = Some(upid.to_string());
562
563 crate::task_log!(worker, "Start GC phase1 (mark used chunks)");
564
565 self.mark_used_chunks(&mut gc_status, worker)?;
566
567 crate::task_log!(worker, "Start GC phase2 (sweep unused chunks)");
568 self.chunk_store.sweep_unused_chunks(
569 oldest_writer,
570 phase1_start_time,
571 &mut gc_status,
572 worker,
573 )?;
574
575 crate::task_log!(
576 worker,
577 "Removed garbage: {}",
578 HumanByte::from(gc_status.removed_bytes),
579 );
580 crate::task_log!(worker, "Removed chunks: {}", gc_status.removed_chunks);
581 if gc_status.pending_bytes > 0 {
582 crate::task_log!(
583 worker,
584 "Pending removals: {} (in {} chunks)",
585 HumanByte::from(gc_status.pending_bytes),
586 gc_status.pending_chunks,
587 );
588 }
589 if gc_status.removed_bad > 0 {
590 crate::task_log!(worker, "Removed bad chunks: {}", gc_status.removed_bad);
591 }
592
593 if gc_status.still_bad > 0 {
594 crate::task_log!(worker, "Leftover bad chunks: {}", gc_status.still_bad);
595 }
596
597 crate::task_log!(
598 worker,
599 "Original data usage: {}",
600 HumanByte::from(gc_status.index_data_bytes),
601 );
602
603 if gc_status.index_data_bytes > 0 {
604 let comp_per = (gc_status.disk_bytes as f64 * 100.)/gc_status.index_data_bytes as f64;
605 crate::task_log!(
606 worker,
607 "On-Disk usage: {} ({:.2}%)",
608 HumanByte::from(gc_status.disk_bytes),
609 comp_per,
610 );
611 }
612
613 crate::task_log!(worker, "On-Disk chunks: {}", gc_status.disk_chunks);
614
615 let deduplication_factor = if gc_status.disk_bytes > 0 {
616 (gc_status.index_data_bytes as f64)/(gc_status.disk_bytes as f64)
617 } else {
618 1.0
619 };
620
621 crate::task_log!(worker, "Deduplication factor: {:.2}", deduplication_factor);
622
623 if gc_status.disk_chunks > 0 {
624 let avg_chunk = gc_status.disk_bytes/(gc_status.disk_chunks as u64);
625 crate::task_log!(worker, "Average chunk size: {}", HumanByte::from(avg_chunk));
626 }
627
628 if let Ok(serialized) = serde_json::to_string(&gc_status) {
629 let mut path = self.base_path();
630 path.push(".gc-status");
631
632 let backup_user = crate::backup::backup_user()?;
633 let mode = nix::sys::stat::Mode::from_bits_truncate(0o0644);
634 // set the correct owner/group/permissions while saving file
635 // owner(rw) = backup, group(r)= backup
636 let options = CreateOptions::new()
637 .perm(mode)
638 .owner(backup_user.uid)
639 .group(backup_user.gid);
640
641 // ignore errors
642 let _ = replace_file(path, serialized.as_bytes(), options);
643 }
644
645 *self.last_gc_status.lock().unwrap() = gc_status;
646
647 } else {
648 bail!("Start GC failed - (already running/locked)");
649 }
650
651 Ok(())
652 }
653
654 pub fn try_shared_chunk_store_lock(&self) -> Result<tools::ProcessLockSharedGuard, Error> {
655 self.chunk_store.try_shared_lock()
656 }
657
658 pub fn chunk_path(&self, digest:&[u8; 32]) -> (PathBuf, String) {
659 self.chunk_store.chunk_path(digest)
660 }
661
662 pub fn cond_touch_chunk(&self, digest: &[u8; 32], fail_if_not_exist: bool) -> Result<bool, Error> {
663 self.chunk_store.cond_touch_chunk(digest, fail_if_not_exist)
664 }
665
666 pub fn insert_chunk(
667 &self,
668 chunk: &DataBlob,
669 digest: &[u8; 32],
670 ) -> Result<(bool, u64), Error> {
671 self.chunk_store.insert_chunk(chunk, digest)
672 }
673
674 pub fn load_blob(&self, backup_dir: &BackupDir, filename: &str) -> Result<DataBlob, Error> {
675 let mut path = self.base_path();
676 path.push(backup_dir.relative_path());
677 path.push(filename);
678
679 proxmox::try_block!({
680 let mut file = std::fs::File::open(&path)?;
681 DataBlob::load_from_reader(&mut file)
682 }).map_err(|err| format_err!("unable to load blob '{:?}' - {}", path, err))
683 }
684
685
686 pub fn load_chunk(&self, digest: &[u8; 32]) -> Result<DataBlob, Error> {
687
688 let (chunk_path, digest_str) = self.chunk_store.chunk_path(digest);
689
690 proxmox::try_block!({
691 let mut file = std::fs::File::open(&chunk_path)?;
692 DataBlob::load_from_reader(&mut file)
693 }).map_err(|err| format_err!(
694 "store '{}', unable to load chunk '{}' - {}",
695 self.name(),
696 digest_str,
697 err,
698 ))
699 }
700
701 fn lock_manifest(
702 &self,
703 backup_dir: &BackupDir,
704 ) -> Result<File, Error> {
705 let mut path = self.base_path();
706 path.push(backup_dir.relative_path());
707 path.push(&MANIFEST_LOCK_NAME);
708
709 // update_manifest should never take a long time, so if someone else has
710 // the lock we can simply block a bit and should get it soon
711 open_file_locked(&path, Duration::from_secs(5), true)
712 .map_err(|err| {
713 format_err!(
714 "unable to acquire manifest lock {:?} - {}", &path, err
715 )
716 })
717 }
718
719 /// Load the manifest without a lock. Must not be written back.
720 pub fn load_manifest(
721 &self,
722 backup_dir: &BackupDir,
723 ) -> Result<(BackupManifest, u64), Error> {
724 let blob = self.load_blob(backup_dir, MANIFEST_BLOB_NAME)?;
725 let raw_size = blob.raw_size();
726 let manifest = BackupManifest::try_from(blob)?;
727 Ok((manifest, raw_size))
728 }
729
730 /// Update the manifest of the specified snapshot. Never write a manifest directly,
731 /// only use this method - anything else may break locking guarantees.
732 pub fn update_manifest(
733 &self,
734 backup_dir: &BackupDir,
735 update_fn: impl FnOnce(&mut BackupManifest),
736 ) -> Result<(), Error> {
737
738 let _guard = self.lock_manifest(backup_dir)?;
739 let (mut manifest, _) = self.load_manifest(&backup_dir)?;
740
741 update_fn(&mut manifest);
742
743 let manifest = serde_json::to_value(manifest)?;
744 let manifest = serde_json::to_string_pretty(&manifest)?;
745 let blob = DataBlob::encode(manifest.as_bytes(), None, true)?;
746 let raw_data = blob.raw_data();
747
748 let mut path = self.base_path();
749 path.push(backup_dir.relative_path());
750 path.push(MANIFEST_BLOB_NAME);
751
752 // atomic replace invalidates flock - no other writes past this point!
753 replace_file(&path, raw_data, CreateOptions::new())?;
754
755 Ok(())
756 }
757
758 pub fn verify_new(&self) -> bool {
759 self.verify_new
760 }
761 }