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
;
9 use anyhow
::{bail, format_err, Error}
;
10 use lazy_static
::lazy_static
;
12 use proxmox
::tools
::fs
::{replace_file, CreateOptions, open_file_locked}
;
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}
;
20 use super::{DataBlob, ArchiveType, archive_type}
;
21 use crate::config
::datastore
::{self, DataStoreConfig}
;
22 use crate::task
::TaskState
;
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
;
30 static ref DATASTORE_MAP
: Mutex
<HashMap
<String
, Arc
<DataStore
>>> = Mutex
::new(HashMap
::new());
33 /// Datastore Management
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
>,
46 pub fn lookup_datastore(name
: &str) -> Result
<Arc
<DataStore
>, Error
> {
48 let (config
, _digest
) = datastore
::config()?
;
49 let config
: datastore
::DataStoreConfig
= config
.lookup("datastore", name
)?
;
50 let path
= PathBuf
::from(&config
.path
);
52 let mut map
= DATASTORE_MAP
.lock().unwrap();
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)
59 return Ok(datastore
.clone());
63 let datastore
= DataStore
::open_with_path(name
, &path
, config
)?
;
65 let datastore
= Arc
::new(datastore
);
66 map
.insert(name
.to_string(), datastore
.clone());
71 fn open_with_path(store_name
: &str, path
: &Path
, config
: DataStoreConfig
) -> Result
<Self, Error
> {
72 let chunk_store
= ChunkStore
::open(store_name
, path
)?
;
74 let gc_status
= GarbageCollectionStatus
::default();
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),
84 pub fn get_chunk_iterator(
87 impl Iterator
<Item
= (Result
<tools
::fs
::ReadDirEntry
, Error
>, usize, bool
)>,
90 self.chunk_store
.get_chunk_iterator()
93 pub fn create_fixed_writer
<P
: AsRef
<Path
>>(&self, filename
: P
, size
: usize, chunk_size
: usize) -> Result
<FixedIndexWriter
, Error
> {
95 let index
= FixedIndexWriter
::create(self.chunk_store
.clone(), filename
.as_ref(), size
, chunk_size
)?
;
100 pub fn open_fixed_reader
<P
: AsRef
<Path
>>(&self, filename
: P
) -> Result
<FixedIndexReader
, Error
> {
102 let full_path
= self.chunk_store
.relative_path(filename
.as_ref());
104 let index
= FixedIndexReader
::open(&full_path
)?
;
109 pub fn create_dynamic_writer
<P
: AsRef
<Path
>>(
111 ) -> Result
<DynamicIndexWriter
, Error
> {
113 let index
= DynamicIndexWriter
::create(
114 self.chunk_store
.clone(), filename
.as_ref())?
;
119 pub fn open_dynamic_reader
<P
: AsRef
<Path
>>(&self, filename
: P
) -> Result
<DynamicIndexReader
, Error
> {
121 let full_path
= self.chunk_store
.relative_path(filename
.as_ref());
123 let index
= DynamicIndexReader
::open(&full_path
)?
;
128 pub fn open_index
<P
>(&self, filename
: P
) -> Result
<Box
<dyn IndexFile
+ Send
>, Error
>
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
),
142 pub fn name(&self) -> &str {
143 self.chunk_store
.name()
146 pub fn base_path(&self) -> PathBuf
{
147 self.chunk_store
.base_path()
150 /// Cleanup a backup directory
152 /// Removes all files not mentioned in the manifest.
153 pub fn cleanup_backup_dir(&self, backup_dir
: &BackupDir
, manifest
: &BackupManifest
154 ) -> Result
<(), Error
> {
156 let mut full_path
= self.base_path();
157 full_path
.push(backup_dir
.relative_path());
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()); }
);
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; }
169 let file_name
= item
.file_name().to_bytes();
170 if file_name
== b
"." || file_name
== b
".." { continue; }
;
172 if let Ok(name
) = std
::str::from_utf8(file_name
) {
173 if wanted_files
.contains(name
) { continue; }
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) }
;
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());
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());
198 /// Remove a complete backup group including all snapshots
199 pub fn remove_backup_group(&self, backup_group
: &BackupGroup
) -> Result
<(), Error
> {
201 let full_path
= self.group_path(backup_group
);
203 let _guard
= tools
::fs
::lock_dir_noblock(&full_path
, "backup group", "possible running backup")?
;
205 log
::info
!("removing backup group {:?}", full_path
);
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)?
;
212 // no snapshots left, we can now safely remove the empty folder
213 std
::fs
::remove_dir_all(&full_path
)
216 "removing backup group directory {:?} failed - {}",
225 /// Remove a backup directory including all content
226 pub fn remove_backup_dir(&self, backup_dir
: &BackupDir
, force
: bool
) -> Result
<(), Error
> {
228 let full_path
= self.snapshot_path(backup_dir
);
230 let (_guard
, _manifest_guard
);
232 _guard
= lock_dir_noblock(&full_path
, "snapshot", "possibly running or in use")?
;
233 _manifest_guard
= self.lock_manifest(backup_dir
);
236 log
::info
!("removing backup snapshot {:?}", full_path
);
237 std
::fs
::remove_dir_all(&full_path
)
240 "removing backup snapshot {:?} failed - {}",
249 /// Returns the time of the last successful backup
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());
257 if group_path
.exists() {
258 backup_group
.last_successful_backup(&base_path
)
264 /// Returns the backup owner.
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
275 /// Set the backup owner.
278 backup_group
: &BackupGroup
,
281 ) -> Result
<(), Error
> {
282 let mut path
= self.base_path();
283 path
.push(backup_group
.group_path());
286 let mut open_options
= std
::fs
::OpenOptions
::new();
287 open_options
.write(true);
288 open_options
.truncate(true);
291 open_options
.create(true);
293 open_options
.create_new(true);
296 let mut file
= open_options
.open(&path
)
297 .map_err(|err
| format_err
!("unable to create owner file {:?} - {}", path
, err
))?
;
299 writeln
!(file
, "{}", userid
)
300 .map_err(|err
| format_err
!("unable to write owner file {:?} - {}", path
, err
))?
;
305 /// Create (if it does not already exists) and lock a backup group
307 /// And set the owner to 'userid'. If the group already exists, it returns the
308 /// current owner (instead of setting the owner).
310 /// This also acquires an exclusive lock on the directory and returns the lock guard.
311 pub fn create_locked_backup_group(
313 backup_group
: &BackupGroup
,
315 ) -> Result
<(Userid
, DirLockGuard
), Error
> {
316 // create intermediate path first:
317 let base_path
= self.base_path();
319 let mut full_path
= base_path
.clone();
320 full_path
.push(backup_group
.backup_type());
321 std
::fs
::create_dir_all(&full_path
)?
;
323 full_path
.push(backup_group
.backup_id());
325 // create the last component now
326 match std
::fs
::create_dir(&full_path
) {
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
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
338 Err(err
) => bail
!("unable to create backup group {:?} - {}", full_path
, err
),
342 /// Creates a new backup snapshot inside a BackupGroup
344 /// The BackupGroup directory needs to exist.
345 pub fn create_locked_backup_dir(&self, backup_dir
: &BackupDir
)
346 -> Result
<(PathBuf
, bool
, DirLockGuard
), Error
>
348 let relative_path
= backup_dir
.relative_path();
349 let mut full_path
= self.base_path();
350 full_path
.push(&relative_path
);
353 lock_dir_noblock(&full_path
, "snapshot", "internal error - tried creating snapshot that's already in use");
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())
362 pub fn list_images(&self) -> Result
<Vec
<PathBuf
>, Error
> {
363 let base
= self.base_path();
365 let mut list
= vec
![];
367 use walkdir
::WalkDir
;
369 let walker
= WalkDir
::new(&base
).same_file_system(true).into_iter();
371 // make sure we skip .chunks (and other hidden files to keep it simple)
372 fn is_hidden(entry
: &walkdir
::DirEntry
) -> bool
{
375 .map(|s
| s
.starts_with("."))
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(""));
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())
389 _
=> bail
!("unexpected error on datastore traversal: {} - {}", inner
, path
.display()),
394 for entry
in walker
.filter_entry(|e
| !is_hidden(e
)) {
395 let path
= match entry
{
396 Ok(entry
) => entry
.into_path(),
398 handle_entry_err(err
)?
;
402 if let Ok(archive_type
) = archive_type(&path
) {
403 if archive_type
== ArchiveType
::FixedIndex
|| archive_type
== ArchiveType
::DynamicIndex
{
412 // mark chunks used by ``index`` as used
413 fn index_mark_used_chunks
<I
: IndexFile
>(
416 file_name
: &Path
, // only used for error reporting
417 status
: &mut GarbageCollectionStatus
,
418 worker
: &dyn TaskState
,
419 ) -> Result
<(), Error
> {
421 status
.index_file_count
+= 1;
422 status
.index_data_bytes
+= index
.index_bytes();
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
) {
431 "warning: unable to access chunk {}, required by {:?} - {}",
432 proxmox
::tools
::digest_to_hex(digest
),
443 status
: &mut GarbageCollectionStatus
,
444 worker
: &dyn TaskState
,
445 ) -> Result
<(), Error
> {
447 let image_list
= self.list_images()?
;
449 let image_count
= image_list
.len();
453 let mut last_percentage
: usize = 0;
455 for path
in image_list
{
457 worker
.check_abort()?
;
458 tools
::fail_on_shutdown()?
;
460 let full_path
= self.chunk_store
.relative_path(&path
);
461 match std
::fs
::File
::open(&full_path
) {
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
)?
;
474 if err
.kind() == std
::io
::ErrorKind
::NotFound
{
475 // simply ignore vanished files
477 return Err(err
.into());
483 let percentage
= done
*100/image_count
;
484 if percentage
> last_percentage
{
487 "percentage done: phase1 {}% ({} of {} index files)",
492 last_percentage
= percentage
;
499 pub fn last_gc_status(&self) -> GarbageCollectionStatus
{
500 self.last_gc_status
.lock().unwrap().clone()
503 pub fn garbage_collection_running(&self) -> bool
{
504 if let Ok(_
) = self.gc_mutex
.try_lock() { false }
else { true }
507 pub fn garbage_collection(&self, worker
: &dyn TaskState
, upid
: &UPID
) -> Result
<(), Error
> {
509 if let Ok(ref mut _mutex
) = self.gc_mutex
.try_lock() {
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()?
;
516 let phase1_start_time
= proxmox
::tools
::time
::epoch_i64();
517 let oldest_writer
= self.chunk_store
.oldest_writer().unwrap_or(phase1_start_time
);
519 let mut gc_status
= GarbageCollectionStatus
::default();
520 gc_status
.upid
= Some(upid
.to_string());
522 crate::task_log
!(worker
, "Start GC phase1 (mark used chunks)");
524 self.mark_used_chunks(&mut gc_status
, worker
)?
;
526 crate::task_log
!(worker
, "Start GC phase2 (sweep unused chunks)");
527 self.chunk_store
.sweep_unused_chunks(
536 "Removed garbage: {}",
537 HumanByte
::from(gc_status
.removed_bytes
),
539 crate::task_log
!(worker
, "Removed chunks: {}", gc_status
.removed_chunks
);
540 if gc_status
.pending_bytes
> 0 {
543 "Pending removals: {} (in {} chunks)",
544 HumanByte
::from(gc_status
.pending_bytes
),
545 gc_status
.pending_chunks
,
548 if gc_status
.removed_bad
> 0 {
549 crate::task_log
!(worker
, "Removed bad files: {}", gc_status
.removed_bad
);
554 "Original data usage: {}",
555 HumanByte
::from(gc_status
.index_data_bytes
),
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;
562 "On-Disk usage: {} ({:.2}%)",
563 HumanByte
::from(gc_status
.disk_bytes
),
568 crate::task_log
!(worker
, "On-Disk chunks: {}", gc_status
.disk_chunks
);
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
));
575 *self.last_gc_status
.lock().unwrap() = gc_status
;
578 bail
!("Start GC failed - (already running/locked)");
584 pub fn try_shared_chunk_store_lock(&self) -> Result
<tools
::ProcessLockSharedGuard
, Error
> {
585 self.chunk_store
.try_shared_lock()
588 pub fn chunk_path(&self, digest
:&[u8; 32]) -> (PathBuf
, String
) {
589 self.chunk_store
.chunk_path(digest
)
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
)
600 ) -> Result
<(bool
, u64), Error
> {
601 self.chunk_store
.insert_chunk(chunk
, digest
)
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());
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
))
616 pub fn load_chunk(&self, digest
: &[u8; 32]) -> Result
<DataBlob
, Error
> {
618 let (chunk_path
, digest_str
) = self.chunk_store
.chunk_path(digest
);
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 '{}' - {}",
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
);
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)
644 "unable to acquire manifest lock {:?} - {}", &path
, err
649 /// Load the manifest without a lock. Must not be written back.
650 pub fn load_manifest(
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
))
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(
664 backup_dir
: &BackupDir
,
665 update_fn
: impl FnOnce(&mut BackupManifest
),
666 ) -> Result
<(), Error
> {
668 let _guard
= self.lock_manifest(backup_dir
)?
;
669 let (mut manifest
, _
) = self.load_manifest(&backup_dir
)?
;
671 update_fn(&mut manifest
);
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();
678 let mut path
= self.base_path();
679 path
.push(backup_dir
.relative_path());
680 path
.push(MANIFEST_BLOB_NAME
);
682 // atomic replace invalidates flock - no other writes past this point!
683 replace_file(&path
, raw_data
, CreateOptions
::new())?
;
688 pub fn verify_new(&self) -> bool
{