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