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
;
7 use anyhow
::{bail, format_err, Error}
;
8 use lazy_static
::lazy_static
;
10 use proxmox
::tools
::fs
::{replace_file, CreateOptions}
;
12 use super::backup_info
::{BackupGroup, BackupDir}
;
13 use super::chunk_store
::ChunkStore
;
14 use super::dynamic_index
::{DynamicIndexReader, DynamicIndexWriter}
;
15 use super::fixed_index
::{FixedIndexReader, FixedIndexWriter}
;
16 use super::manifest
::{MANIFEST_BLOB_NAME, CLIENT_LOG_BLOB_NAME, BackupManifest}
;
18 use super::{DataBlob, ArchiveType, archive_type}
;
19 use crate::config
::datastore
;
20 use crate::task
::TaskState
;
22 use crate::tools
::format
::HumanByte
;
23 use crate::tools
::fs
::{lock_dir_noblock, DirLockGuard}
;
24 use crate::api2
::types
::{GarbageCollectionStatus, Userid}
;
25 use crate::server
::UPID
;
28 static ref DATASTORE_MAP
: Mutex
<HashMap
<String
, Arc
<DataStore
>>> = Mutex
::new(HashMap
::new());
31 /// Datastore Management
33 /// A Datastore can store severals backups, and provides the
34 /// management interface for backup.
35 pub struct DataStore
{
36 chunk_store
: Arc
<ChunkStore
>,
37 gc_mutex
: Mutex
<bool
>,
38 last_gc_status
: Mutex
<GarbageCollectionStatus
>,
43 pub fn lookup_datastore(name
: &str) -> Result
<Arc
<DataStore
>, Error
> {
45 let (config
, _digest
) = datastore
::config()?
;
46 let config
: datastore
::DataStoreConfig
= config
.lookup("datastore", name
)?
;
48 let mut map
= DATASTORE_MAP
.lock().unwrap();
50 if let Some(datastore
) = map
.get(name
) {
51 // Compare Config - if changed, create new Datastore object!
52 if datastore
.chunk_store
.base
== PathBuf
::from(&config
.path
) {
53 return Ok(datastore
.clone());
57 let datastore
= DataStore
::open(name
)?
;
59 let datastore
= Arc
::new(datastore
);
60 map
.insert(name
.to_string(), datastore
.clone());
65 pub fn open(store_name
: &str) -> Result
<Self, Error
> {
67 let (config
, _digest
) = datastore
::config()?
;
68 let (_
, store_config
) = config
.sections
.get(store_name
)
69 .ok_or(format_err
!("no such datastore '{}'", store_name
))?
;
71 let path
= store_config
["path"].as_str().unwrap();
73 Self::open_with_path(store_name
, Path
::new(path
))
76 pub fn open_with_path(store_name
: &str, path
: &Path
) -> Result
<Self, Error
> {
77 let chunk_store
= ChunkStore
::open(store_name
, path
)?
;
79 let gc_status
= GarbageCollectionStatus
::default();
82 chunk_store
: Arc
::new(chunk_store
),
83 gc_mutex
: Mutex
::new(false),
84 last_gc_status
: Mutex
::new(gc_status
),
88 pub fn get_chunk_iterator(
91 impl Iterator
<Item
= (Result
<tools
::fs
::ReadDirEntry
, Error
>, usize, bool
)>,
94 self.chunk_store
.get_chunk_iterator()
97 pub fn create_fixed_writer
<P
: AsRef
<Path
>>(&self, filename
: P
, size
: usize, chunk_size
: usize) -> Result
<FixedIndexWriter
, Error
> {
99 let index
= FixedIndexWriter
::create(self.chunk_store
.clone(), filename
.as_ref(), size
, chunk_size
)?
;
104 pub fn open_fixed_reader
<P
: AsRef
<Path
>>(&self, filename
: P
) -> Result
<FixedIndexReader
, Error
> {
106 let full_path
= self.chunk_store
.relative_path(filename
.as_ref());
108 let index
= FixedIndexReader
::open(&full_path
)?
;
113 pub fn create_dynamic_writer
<P
: AsRef
<Path
>>(
115 ) -> Result
<DynamicIndexWriter
, Error
> {
117 let index
= DynamicIndexWriter
::create(
118 self.chunk_store
.clone(), filename
.as_ref())?
;
123 pub fn open_dynamic_reader
<P
: AsRef
<Path
>>(&self, filename
: P
) -> Result
<DynamicIndexReader
, Error
> {
125 let full_path
= self.chunk_store
.relative_path(filename
.as_ref());
127 let index
= DynamicIndexReader
::open(&full_path
)?
;
132 pub fn open_index
<P
>(&self, filename
: P
) -> Result
<Box
<dyn IndexFile
+ Send
>, Error
>
136 let filename
= filename
.as_ref();
137 let out
: Box
<dyn IndexFile
+ Send
> =
138 match archive_type(filename
)?
{
139 ArchiveType
::DynamicIndex
=> Box
::new(self.open_dynamic_reader(filename
)?
),
140 ArchiveType
::FixedIndex
=> Box
::new(self.open_fixed_reader(filename
)?
),
141 _
=> bail
!("cannot open index file of unknown type: {:?}", filename
),
146 pub fn name(&self) -> &str {
147 self.chunk_store
.name()
150 pub fn base_path(&self) -> PathBuf
{
151 self.chunk_store
.base_path()
154 /// Cleanup a backup directory
156 /// Removes all files not mentioned in the manifest.
157 pub fn cleanup_backup_dir(&self, backup_dir
: &BackupDir
, manifest
: &BackupManifest
158 ) -> Result
<(), Error
> {
160 let mut full_path
= self.base_path();
161 full_path
.push(backup_dir
.relative_path());
163 let mut wanted_files
= HashSet
::new();
164 wanted_files
.insert(MANIFEST_BLOB_NAME
.to_string());
165 wanted_files
.insert(CLIENT_LOG_BLOB_NAME
.to_string());
166 manifest
.files().iter().for_each(|item
| { wanted_files.insert(item.filename.clone()); }
);
168 for item
in tools
::fs
::read_subdir(libc
::AT_FDCWD
, &full_path
)?
{
169 if let Ok(item
) = item
{
170 if let Some(file_type
) = item
.file_type() {
171 if file_type
!= nix
::dir
::Type
::File { continue; }
173 let file_name
= item
.file_name().to_bytes();
174 if file_name
== b
"." || file_name
== b
".." { continue; }
;
176 if let Ok(name
) = std
::str::from_utf8(file_name
) {
177 if wanted_files
.contains(name
) { continue; }
179 println
!("remove unused file {:?}", item
.file_name());
180 let dirfd
= item
.parent_fd();
181 let _res
= unsafe { libc::unlinkat(dirfd, item.file_name().as_ptr(), 0) }
;
188 /// Returns the absolute path for a backup_group
189 pub fn group_path(&self, backup_group
: &BackupGroup
) -> PathBuf
{
190 let mut full_path
= self.base_path();
191 full_path
.push(backup_group
.group_path());
195 /// Returns the absolute path for backup_dir
196 pub fn snapshot_path(&self, backup_dir
: &BackupDir
) -> PathBuf
{
197 let mut full_path
= self.base_path();
198 full_path
.push(backup_dir
.relative_path());
202 /// Remove a complete backup group including all snapshots
203 pub fn remove_backup_group(&self, backup_group
: &BackupGroup
) -> Result
<(), Error
> {
205 let full_path
= self.group_path(backup_group
);
207 let _guard
= tools
::fs
::lock_dir_noblock(&full_path
, "backup group", "possible running backup")?
;
209 log
::info
!("removing backup group {:?}", full_path
);
211 // remove all individual backup dirs first to ensure nothing is using them
212 for snap
in backup_group
.list_backups(&self.base_path())?
{
213 self.remove_backup_dir(&snap
.backup_dir
, false)?
;
216 // no snapshots left, we can now safely remove the empty folder
217 std
::fs
::remove_dir_all(&full_path
)
220 "removing backup group directory {:?} failed - {}",
229 /// Remove a backup directory including all content
230 pub fn remove_backup_dir(&self, backup_dir
: &BackupDir
, force
: bool
) -> Result
<(), Error
> {
232 let full_path
= self.snapshot_path(backup_dir
);
236 _guard
= lock_dir_noblock(&full_path
, "snapshot", "possibly running or in use")?
;
239 log
::info
!("removing backup snapshot {:?}", full_path
);
240 std
::fs
::remove_dir_all(&full_path
)
243 "removing backup snapshot {:?} failed - {}",
252 /// Returns the time of the last successful backup
254 /// Or None if there is no backup in the group (or the group dir does not exist).
255 pub fn last_successful_backup(&self, backup_group
: &BackupGroup
) -> Result
<Option
<i64>, Error
> {
256 let base_path
= self.base_path();
257 let mut group_path
= base_path
.clone();
258 group_path
.push(backup_group
.group_path());
260 if group_path
.exists() {
261 backup_group
.last_successful_backup(&base_path
)
267 /// Returns the backup owner.
269 /// The backup owner is the user who first created the backup group.
270 pub fn get_owner(&self, backup_group
: &BackupGroup
) -> Result
<Userid
, Error
> {
271 let mut full_path
= self.base_path();
272 full_path
.push(backup_group
.group_path());
273 full_path
.push("owner");
274 let owner
= proxmox
::tools
::fs
::file_read_firstline(full_path
)?
;
275 Ok(owner
.trim_end().parse()?
) // remove trailing newline
278 /// Set the backup owner.
281 backup_group
: &BackupGroup
,
284 ) -> Result
<(), Error
> {
285 let mut path
= self.base_path();
286 path
.push(backup_group
.group_path());
289 let mut open_options
= std
::fs
::OpenOptions
::new();
290 open_options
.write(true);
291 open_options
.truncate(true);
294 open_options
.create(true);
296 open_options
.create_new(true);
299 let mut file
= open_options
.open(&path
)
300 .map_err(|err
| format_err
!("unable to create owner file {:?} - {}", path
, err
))?
;
302 writeln
!(file
, "{}", userid
)
303 .map_err(|err
| format_err
!("unable to write owner file {:?} - {}", path
, err
))?
;
308 /// Create (if it does not already exists) and lock a backup group
310 /// And set the owner to 'userid'. If the group already exists, it returns the
311 /// current owner (instead of setting the owner).
313 /// This also acquires an exclusive lock on the directory and returns the lock guard.
314 pub fn create_locked_backup_group(
316 backup_group
: &BackupGroup
,
318 ) -> Result
<(Userid
, DirLockGuard
), Error
> {
319 // create intermediate path first:
320 let base_path
= self.base_path();
322 let mut full_path
= base_path
.clone();
323 full_path
.push(backup_group
.backup_type());
324 std
::fs
::create_dir_all(&full_path
)?
;
326 full_path
.push(backup_group
.backup_id());
328 // create the last component now
329 match std
::fs
::create_dir(&full_path
) {
331 let guard
= lock_dir_noblock(&full_path
, "backup group", "another backup is already running")?
;
332 self.set_owner(backup_group
, userid
, false)?
;
333 let owner
= self.get_owner(backup_group
)?
; // just to be sure
336 Err(ref err
) if err
.kind() == io
::ErrorKind
::AlreadyExists
=> {
337 let guard
= lock_dir_noblock(&full_path
, "backup group", "another backup is already running")?
;
338 let owner
= self.get_owner(backup_group
)?
; // just to be sure
341 Err(err
) => bail
!("unable to create backup group {:?} - {}", full_path
, err
),
345 /// Creates a new backup snapshot inside a BackupGroup
347 /// The BackupGroup directory needs to exist.
348 pub fn create_locked_backup_dir(&self, backup_dir
: &BackupDir
)
349 -> Result
<(PathBuf
, bool
, DirLockGuard
), Error
>
351 let relative_path
= backup_dir
.relative_path();
352 let mut full_path
= self.base_path();
353 full_path
.push(&relative_path
);
356 lock_dir_noblock(&full_path
, "snapshot", "internal error - tried creating snapshot that's already in use");
358 match std
::fs
::create_dir(&full_path
) {
359 Ok(_
) => Ok((relative_path
, true, lock()?
)),
360 Err(ref e
) if e
.kind() == io
::ErrorKind
::AlreadyExists
=> Ok((relative_path
, false, lock()?
)),
361 Err(e
) => Err(e
.into())
365 pub fn list_images(&self) -> Result
<Vec
<PathBuf
>, Error
> {
366 let base
= self.base_path();
368 let mut list
= vec
![];
370 use walkdir
::WalkDir
;
372 let walker
= WalkDir
::new(&base
).same_file_system(true).into_iter();
374 // make sure we skip .chunks (and other hidden files to keep it simple)
375 fn is_hidden(entry
: &walkdir
::DirEntry
) -> bool
{
378 .map(|s
| s
.starts_with("."))
381 let handle_entry_err
= |err
: walkdir
::Error
| {
382 if let Some(inner
) = err
.io_error() {
383 let path
= err
.path().unwrap_or(Path
::new(""));
385 io
::ErrorKind
::PermissionDenied
=> {
386 // only allow to skip ext4 fsck directory, avoid GC if, for example,
387 // a user got file permissions wrong on datastore rsync to new server
388 if err
.depth() > 1 || !path
.ends_with("lost+found") {
389 bail
!("cannot continue garbage-collection safely, permission denied on: {}", path
.display())
392 _
=> bail
!("unexpected error on datastore traversal: {} - {}", inner
, path
.display()),
397 for entry
in walker
.filter_entry(|e
| !is_hidden(e
)) {
398 let path
= match entry
{
399 Ok(entry
) => entry
.into_path(),
401 handle_entry_err(err
)?
;
405 if let Ok(archive_type
) = archive_type(&path
) {
406 if archive_type
== ArchiveType
::FixedIndex
|| archive_type
== ArchiveType
::DynamicIndex
{
415 // mark chunks used by ``index`` as used
416 fn index_mark_used_chunks
<I
: IndexFile
>(
419 file_name
: &Path
, // only used for error reporting
420 status
: &mut GarbageCollectionStatus
,
421 worker
: &dyn TaskState
,
422 ) -> Result
<(), Error
> {
424 status
.index_file_count
+= 1;
425 status
.index_data_bytes
+= index
.index_bytes();
427 for pos
in 0..index
.index_count() {
428 worker
.check_abort()?
;
429 tools
::fail_on_shutdown()?
;
430 let digest
= index
.index_digest(pos
).unwrap();
431 if let Err(err
) = self.chunk_store
.touch_chunk(digest
) {
434 "warning: unable to access chunk {}, required by {:?} - {}",
435 proxmox
::tools
::digest_to_hex(digest
),
446 status
: &mut GarbageCollectionStatus
,
447 worker
: &dyn TaskState
,
448 ) -> Result
<(), Error
> {
450 let image_list
= self.list_images()?
;
452 let image_count
= image_list
.len();
456 let mut last_percentage
: usize = 0;
458 for path
in image_list
{
460 worker
.check_abort()?
;
461 tools
::fail_on_shutdown()?
;
463 let full_path
= self.chunk_store
.relative_path(&path
);
464 match std
::fs
::File
::open(&full_path
) {
466 if let Ok(archive_type
) = archive_type(&path
) {
467 if archive_type
== ArchiveType
::FixedIndex
{
468 let index
= FixedIndexReader
::new(file
)?
;
469 self.index_mark_used_chunks(index
, &path
, status
, worker
)?
;
470 } else if archive_type
== ArchiveType
::DynamicIndex
{
471 let index
= DynamicIndexReader
::new(file
)?
;
472 self.index_mark_used_chunks(index
, &path
, status
, worker
)?
;
477 if err
.kind() == std
::io
::ErrorKind
::NotFound
{
478 // simply ignore vanished files
480 return Err(err
.into());
486 let percentage
= done
*100/image_count
;
487 if percentage
> last_percentage
{
490 "percentage done: phase1 {}% ({} of {} index files)",
495 last_percentage
= percentage
;
502 pub fn last_gc_status(&self) -> GarbageCollectionStatus
{
503 self.last_gc_status
.lock().unwrap().clone()
506 pub fn garbage_collection_running(&self) -> bool
{
507 if let Ok(_
) = self.gc_mutex
.try_lock() { false }
else { true }
510 pub fn garbage_collection(&self, worker
: &dyn TaskState
, upid
: &UPID
) -> Result
<(), Error
> {
512 if let Ok(ref mut _mutex
) = self.gc_mutex
.try_lock() {
514 // avoids that we run GC if an old daemon process has still a
515 // running backup writer, which is not save as we have no "oldest
516 // writer" information and thus no safe atime cutoff
517 let _exclusive_lock
= self.chunk_store
.try_exclusive_lock()?
;
519 let phase1_start_time
= proxmox
::tools
::time
::epoch_i64();
520 let oldest_writer
= self.chunk_store
.oldest_writer().unwrap_or(phase1_start_time
);
522 let mut gc_status
= GarbageCollectionStatus
::default();
523 gc_status
.upid
= Some(upid
.to_string());
525 crate::task_log
!(worker
, "Start GC phase1 (mark used chunks)");
527 self.mark_used_chunks(&mut gc_status
, worker
)?
;
529 crate::task_log
!(worker
, "Start GC phase2 (sweep unused chunks)");
530 self.chunk_store
.sweep_unused_chunks(
539 "Removed garbage: {}",
540 HumanByte
::from(gc_status
.removed_bytes
),
542 crate::task_log
!(worker
, "Removed chunks: {}", gc_status
.removed_chunks
);
543 if gc_status
.pending_bytes
> 0 {
546 "Pending removals: {} (in {} chunks)",
547 HumanByte
::from(gc_status
.pending_bytes
),
548 gc_status
.pending_chunks
,
551 if gc_status
.removed_bad
> 0 {
552 crate::task_log
!(worker
, "Removed bad files: {}", gc_status
.removed_bad
);
557 "Original data usage: {}",
558 HumanByte
::from(gc_status
.index_data_bytes
),
561 if gc_status
.index_data_bytes
> 0 {
562 let comp_per
= (gc_status
.disk_bytes
as f64 * 100.)/gc_status
.index_data_bytes
as f64;
565 "On-Disk usage: {} ({:.2}%)",
566 HumanByte
::from(gc_status
.disk_bytes
),
571 crate::task_log
!(worker
, "On-Disk chunks: {}", gc_status
.disk_chunks
);
573 if gc_status
.disk_chunks
> 0 {
574 let avg_chunk
= gc_status
.disk_bytes
/(gc_status
.disk_chunks
as u64);
575 crate::task_log
!(worker
, "Average chunk size: {}", HumanByte
::from(avg_chunk
));
578 *self.last_gc_status
.lock().unwrap() = gc_status
;
581 bail
!("Start GC failed - (already running/locked)");
587 pub fn try_shared_chunk_store_lock(&self) -> Result
<tools
::ProcessLockSharedGuard
, Error
> {
588 self.chunk_store
.try_shared_lock()
591 pub fn chunk_path(&self, digest
:&[u8; 32]) -> (PathBuf
, String
) {
592 self.chunk_store
.chunk_path(digest
)
595 pub fn cond_touch_chunk(&self, digest
: &[u8; 32], fail_if_not_exist
: bool
) -> Result
<bool
, Error
> {
596 self.chunk_store
.cond_touch_chunk(digest
, fail_if_not_exist
)
603 ) -> Result
<(bool
, u64), Error
> {
604 self.chunk_store
.insert_chunk(chunk
, digest
)
607 pub fn load_blob(&self, backup_dir
: &BackupDir
, filename
: &str) -> Result
<DataBlob
, Error
> {
608 let mut path
= self.base_path();
609 path
.push(backup_dir
.relative_path());
612 proxmox
::try_block
!({
613 let mut file
= std
::fs
::File
::open(&path
)?
;
614 DataBlob
::load_from_reader(&mut file
)
615 }).map_err(|err
| format_err
!("unable to load blob '{:?}' - {}", path
, err
))
619 pub fn load_chunk(&self, digest
: &[u8; 32]) -> Result
<DataBlob
, Error
> {
621 let (chunk_path
, digest_str
) = self.chunk_store
.chunk_path(digest
);
623 proxmox
::try_block
!({
624 let mut file
= std
::fs
::File
::open(&chunk_path
)?
;
625 DataBlob
::load_from_reader(&mut file
)
626 }).map_err(|err
| format_err
!(
627 "store '{}', unable to load chunk '{}' - {}",
634 pub fn load_manifest(
636 backup_dir
: &BackupDir
,
637 ) -> Result
<(BackupManifest
, u64), Error
> {
638 let blob
= self.load_blob(backup_dir
, MANIFEST_BLOB_NAME
)?
;
639 let raw_size
= blob
.raw_size();
640 let manifest
= BackupManifest
::try_from(blob
)?
;
641 Ok((manifest
, raw_size
))
644 pub fn store_manifest(
646 backup_dir
: &BackupDir
,
647 manifest
: BackupManifest
,
648 ) -> Result
<(), Error
> {
649 let manifest
= serde_json
::to_value(manifest
)?
;
650 let manifest
= serde_json
::to_string_pretty(&manifest
)?
;
651 let blob
= DataBlob
::encode(manifest
.as_bytes(), None
, true)?
;
652 let raw_data
= blob
.raw_data();
654 let mut path
= self.base_path();
655 path
.push(backup_dir
.relative_path());
656 path
.push(MANIFEST_BLOB_NAME
);
658 replace_file(&path
, raw_data
, CreateOptions
::new())?
;