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