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