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
;
11 use proxmox
::tools
::fs
::{replace_file, CreateOptions}
;
13 use super::backup_info
::{BackupGroup, BackupDir}
;
14 use super::chunk_store
::ChunkStore
;
15 use super::dynamic_index
::{DynamicIndexReader, DynamicIndexWriter}
;
16 use super::fixed_index
::{FixedIndexReader, FixedIndexWriter}
;
17 use super::manifest
::{MANIFEST_BLOB_NAME, CLIENT_LOG_BLOB_NAME, BackupManifest}
;
19 use super::{DataBlob, ArchiveType, archive_type}
;
20 use crate::config
::datastore
;
21 use crate::task
::TaskState
;
23 use crate::tools
::format
::HumanByte
;
24 use crate::tools
::fs
::{lock_dir_noblock, DirLockGuard}
;
25 use crate::api2
::types
::{GarbageCollectionStatus, Userid}
;
26 use crate::server
::UPID
;
29 static ref DATASTORE_MAP
: Mutex
<HashMap
<String
, Arc
<DataStore
>>> = Mutex
::new(HashMap
::new());
32 /// Datastore Management
34 /// A Datastore can store severals backups, and provides the
35 /// management interface for backup.
36 pub struct DataStore
{
37 chunk_store
: Arc
<ChunkStore
>,
38 gc_mutex
: Mutex
<bool
>,
39 last_gc_status
: Mutex
<GarbageCollectionStatus
>,
44 pub fn lookup_datastore(name
: &str) -> Result
<Arc
<DataStore
>, Error
> {
46 let (config
, _digest
) = datastore
::config()?
;
47 let config
: datastore
::DataStoreConfig
= config
.lookup("datastore", name
)?
;
49 let mut map
= DATASTORE_MAP
.lock().unwrap();
51 if let Some(datastore
) = map
.get(name
) {
52 // Compare Config - if changed, create new Datastore object!
53 if datastore
.chunk_store
.base
== PathBuf
::from(&config
.path
) {
54 return Ok(datastore
.clone());
58 let datastore
= DataStore
::open(name
)?
;
60 let datastore
= Arc
::new(datastore
);
61 map
.insert(name
.to_string(), datastore
.clone());
66 pub fn open(store_name
: &str) -> Result
<Self, Error
> {
68 let (config
, _digest
) = datastore
::config()?
;
69 let (_
, store_config
) = config
.sections
.get(store_name
)
70 .ok_or(format_err
!("no such datastore '{}'", store_name
))?
;
72 let path
= store_config
["path"].as_str().unwrap();
74 Self::open_with_path(store_name
, Path
::new(path
))
77 pub fn open_with_path(store_name
: &str, path
: &Path
) -> Result
<Self, Error
> {
78 let chunk_store
= ChunkStore
::open(store_name
, path
)?
;
80 let gc_status
= GarbageCollectionStatus
::default();
83 chunk_store
: Arc
::new(chunk_store
),
84 gc_mutex
: Mutex
::new(false),
85 last_gc_status
: Mutex
::new(gc_status
),
89 pub fn get_chunk_iterator(
92 impl Iterator
<Item
= (Result
<tools
::fs
::ReadDirEntry
, Error
>, usize, bool
)>,
95 self.chunk_store
.get_chunk_iterator()
98 pub fn create_fixed_writer
<P
: AsRef
<Path
>>(&self, filename
: P
, size
: usize, chunk_size
: usize) -> Result
<FixedIndexWriter
, Error
> {
100 let index
= FixedIndexWriter
::create(self.chunk_store
.clone(), filename
.as_ref(), size
, chunk_size
)?
;
105 pub fn open_fixed_reader
<P
: AsRef
<Path
>>(&self, filename
: P
) -> Result
<FixedIndexReader
, Error
> {
107 let full_path
= self.chunk_store
.relative_path(filename
.as_ref());
109 let index
= FixedIndexReader
::open(&full_path
)?
;
114 pub fn create_dynamic_writer
<P
: AsRef
<Path
>>(
116 ) -> Result
<DynamicIndexWriter
, Error
> {
118 let index
= DynamicIndexWriter
::create(
119 self.chunk_store
.clone(), filename
.as_ref())?
;
124 pub fn open_dynamic_reader
<P
: AsRef
<Path
>>(&self, filename
: P
) -> Result
<DynamicIndexReader
, Error
> {
126 let full_path
= self.chunk_store
.relative_path(filename
.as_ref());
128 let index
= DynamicIndexReader
::open(&full_path
)?
;
133 pub fn open_index
<P
>(&self, filename
: P
) -> Result
<Box
<dyn IndexFile
+ Send
>, Error
>
137 let filename
= filename
.as_ref();
138 let out
: Box
<dyn IndexFile
+ Send
> =
139 match archive_type(filename
)?
{
140 ArchiveType
::DynamicIndex
=> Box
::new(self.open_dynamic_reader(filename
)?
),
141 ArchiveType
::FixedIndex
=> Box
::new(self.open_fixed_reader(filename
)?
),
142 _
=> bail
!("cannot open index file of unknown type: {:?}", filename
),
147 pub fn name(&self) -> &str {
148 self.chunk_store
.name()
151 pub fn base_path(&self) -> PathBuf
{
152 self.chunk_store
.base_path()
155 /// Cleanup a backup directory
157 /// Removes all files not mentioned in the manifest.
158 pub fn cleanup_backup_dir(&self, backup_dir
: &BackupDir
, manifest
: &BackupManifest
159 ) -> Result
<(), Error
> {
161 let mut full_path
= self.base_path();
162 full_path
.push(backup_dir
.relative_path());
164 let mut wanted_files
= HashSet
::new();
165 wanted_files
.insert(MANIFEST_BLOB_NAME
.to_string());
166 wanted_files
.insert(CLIENT_LOG_BLOB_NAME
.to_string());
167 manifest
.files().iter().for_each(|item
| { wanted_files.insert(item.filename.clone()); }
);
169 for item
in tools
::fs
::read_subdir(libc
::AT_FDCWD
, &full_path
)?
{
170 if let Ok(item
) = item
{
171 if let Some(file_type
) = item
.file_type() {
172 if file_type
!= nix
::dir
::Type
::File { continue; }
174 let file_name
= item
.file_name().to_bytes();
175 if file_name
== b
"." || file_name
== b
".." { continue; }
;
177 if let Ok(name
) = std
::str::from_utf8(file_name
) {
178 if wanted_files
.contains(name
) { continue; }
180 println
!("remove unused file {:?}", item
.file_name());
181 let dirfd
= item
.parent_fd();
182 let _res
= unsafe { libc::unlinkat(dirfd, item.file_name().as_ptr(), 0) }
;
189 /// Returns the absolute path for a backup_group
190 pub fn group_path(&self, backup_group
: &BackupGroup
) -> PathBuf
{
191 let mut full_path
= self.base_path();
192 full_path
.push(backup_group
.group_path());
196 /// Returns the absolute path for backup_dir
197 pub fn snapshot_path(&self, backup_dir
: &BackupDir
) -> PathBuf
{
198 let mut full_path
= self.base_path();
199 full_path
.push(backup_dir
.relative_path());
203 /// Remove a complete backup group including all snapshots
204 pub fn remove_backup_group(&self, backup_group
: &BackupGroup
) -> Result
<(), Error
> {
206 let full_path
= self.group_path(backup_group
);
208 let _guard
= tools
::fs
::lock_dir_noblock(&full_path
, "backup group", "possible running backup")?
;
210 log
::info
!("removing backup group {:?}", full_path
);
211 std
::fs
::remove_dir_all(&full_path
)
214 "removing backup group {:?} failed - {}",
223 /// Remove a backup directory including all content
224 pub fn remove_backup_dir(&self, backup_dir
: &BackupDir
, force
: bool
) -> Result
<(), Error
> {
226 let full_path
= self.snapshot_path(backup_dir
);
230 _guard
= lock_dir_noblock(&full_path
, "snapshot", "possibly running or used as base")?
;
233 log
::info
!("removing backup snapshot {:?}", full_path
);
234 std
::fs
::remove_dir_all(&full_path
)
237 "removing backup snapshot {:?} failed - {}",
246 /// Returns the time of the last successful backup
248 /// Or None if there is no backup in the group (or the group dir does not exist).
249 pub fn last_successful_backup(&self, backup_group
: &BackupGroup
) -> Result
<Option
<i64>, Error
> {
250 let base_path
= self.base_path();
251 let mut group_path
= base_path
.clone();
252 group_path
.push(backup_group
.group_path());
254 if group_path
.exists() {
255 backup_group
.last_successful_backup(&base_path
)
261 /// Returns the backup owner.
263 /// The backup owner is the user who first created the backup group.
264 pub fn get_owner(&self, backup_group
: &BackupGroup
) -> Result
<Userid
, Error
> {
265 let mut full_path
= self.base_path();
266 full_path
.push(backup_group
.group_path());
267 full_path
.push("owner");
268 let owner
= proxmox
::tools
::fs
::file_read_firstline(full_path
)?
;
269 Ok(owner
.trim_end().parse()?
) // remove trailing newline
272 /// Set the backup owner.
275 backup_group
: &BackupGroup
,
278 ) -> Result
<(), Error
> {
279 let mut path
= self.base_path();
280 path
.push(backup_group
.group_path());
283 let mut open_options
= std
::fs
::OpenOptions
::new();
284 open_options
.write(true);
285 open_options
.truncate(true);
288 open_options
.create(true);
290 open_options
.create_new(true);
293 let mut file
= open_options
.open(&path
)
294 .map_err(|err
| format_err
!("unable to create owner file {:?} - {}", path
, err
))?
;
296 write
!(file
, "{}\n", userid
)
297 .map_err(|err
| format_err
!("unable to write owner file {:?} - {}", path
, err
))?
;
302 /// Create (if it does not already exists) and lock a backup group
304 /// And set the owner to 'userid'. If the group already exists, it returns the
305 /// current owner (instead of setting the owner).
307 /// This also acquires an exclusive lock on the directory and returns the lock guard.
308 pub fn create_locked_backup_group(
310 backup_group
: &BackupGroup
,
312 ) -> Result
<(Userid
, DirLockGuard
), Error
> {
313 // create intermediate path first:
314 let base_path
= self.base_path();
316 let mut full_path
= base_path
.clone();
317 full_path
.push(backup_group
.backup_type());
318 std
::fs
::create_dir_all(&full_path
)?
;
320 full_path
.push(backup_group
.backup_id());
322 // create the last component now
323 match std
::fs
::create_dir(&full_path
) {
325 let guard
= lock_dir_noblock(&full_path
, "backup group", "another backup is already running")?
;
326 self.set_owner(backup_group
, userid
, false)?
;
327 let owner
= self.get_owner(backup_group
)?
; // just to be sure
330 Err(ref err
) if err
.kind() == io
::ErrorKind
::AlreadyExists
=> {
331 let guard
= lock_dir_noblock(&full_path
, "backup group", "another backup is already running")?
;
332 let owner
= self.get_owner(backup_group
)?
; // just to be sure
335 Err(err
) => bail
!("unable to create backup group {:?} - {}", full_path
, err
),
339 /// Creates a new backup snapshot inside a BackupGroup
341 /// The BackupGroup directory needs to exist.
342 pub fn create_locked_backup_dir(&self, backup_dir
: &BackupDir
)
343 -> Result
<(PathBuf
, bool
, DirLockGuard
), Error
>
345 let relative_path
= backup_dir
.relative_path();
346 let mut full_path
= self.base_path();
347 full_path
.push(&relative_path
);
350 lock_dir_noblock(&full_path
, "snapshot", "internal error - tried creating snapshot that's already in use");
352 match std
::fs
::create_dir(&full_path
) {
353 Ok(_
) => Ok((relative_path
, true, lock()?
)),
354 Err(ref e
) if e
.kind() == io
::ErrorKind
::AlreadyExists
=> Ok((relative_path
, false, lock()?
)),
355 Err(e
) => Err(e
.into())
359 pub fn list_images(&self) -> Result
<Vec
<PathBuf
>, Error
> {
360 let base
= self.base_path();
362 let mut list
= vec
![];
364 use walkdir
::WalkDir
;
366 let walker
= WalkDir
::new(&base
).same_file_system(true).into_iter();
368 // make sure we skip .chunks (and other hidden files to keep it simple)
369 fn is_hidden(entry
: &walkdir
::DirEntry
) -> bool
{
372 .map(|s
| s
.starts_with("."))
375 let handle_entry_err
= |err
: walkdir
::Error
| {
376 if let Some(inner
) = err
.io_error() {
377 let path
= err
.path().unwrap_or(Path
::new(""));
379 io
::ErrorKind
::PermissionDenied
=> {
380 // only allow to skip ext4 fsck directory, avoid GC if, for example,
381 // a user got file permissions wrong on datastore rsync to new server
382 if err
.depth() > 1 || !path
.ends_with("lost+found") {
383 bail
!("cannot continue garbage-collection safely, permission denied on: {}", path
.display())
386 _
=> bail
!("unexpected error on datastore traversal: {} - {}", inner
, path
.display()),
391 for entry
in walker
.filter_entry(|e
| !is_hidden(e
)) {
392 let path
= match entry
{
393 Ok(entry
) => entry
.into_path(),
395 handle_entry_err(err
)?
;
399 if let Ok(archive_type
) = archive_type(&path
) {
400 if archive_type
== ArchiveType
::FixedIndex
|| archive_type
== ArchiveType
::DynamicIndex
{
409 // mark chunks used by ``index`` as used
410 fn index_mark_used_chunks
<I
: IndexFile
>(
413 file_name
: &Path
, // only used for error reporting
414 status
: &mut GarbageCollectionStatus
,
415 worker
: &dyn TaskState
,
416 ) -> Result
<(), Error
> {
418 status
.index_file_count
+= 1;
419 status
.index_data_bytes
+= index
.index_bytes();
421 for pos
in 0..index
.index_count() {
422 worker
.check_abort()?
;
423 tools
::fail_on_shutdown()?
;
424 let digest
= index
.index_digest(pos
).unwrap();
425 if let Err(err
) = self.chunk_store
.touch_chunk(digest
) {
428 "warning: unable to access chunk {}, required by {:?} - {}",
429 proxmox
::tools
::digest_to_hex(digest
),
440 status
: &mut GarbageCollectionStatus
,
441 worker
: &dyn TaskState
,
442 ) -> Result
<(), Error
> {
444 let image_list
= self.list_images()?
;
446 let image_count
= image_list
.len();
450 let mut last_percentage
: usize = 0;
452 for path
in image_list
{
454 worker
.check_abort()?
;
455 tools
::fail_on_shutdown()?
;
457 if let Ok(archive_type
) = archive_type(&path
) {
458 if archive_type
== ArchiveType
::FixedIndex
{
459 let index
= self.open_fixed_reader(&path
)?
;
460 self.index_mark_used_chunks(index
, &path
, status
, worker
)?
;
461 } else if archive_type
== ArchiveType
::DynamicIndex
{
462 let index
= self.open_dynamic_reader(&path
)?
;
463 self.index_mark_used_chunks(index
, &path
, status
, worker
)?
;
468 let percentage
= done
*100/image_count
;
469 if percentage
> last_percentage
{
472 "percentage done: phase1 {}% ({} of {} index files)",
477 last_percentage
= percentage
;
484 pub fn last_gc_status(&self) -> GarbageCollectionStatus
{
485 self.last_gc_status
.lock().unwrap().clone()
488 pub fn garbage_collection_running(&self) -> bool
{
489 if let Ok(_
) = self.gc_mutex
.try_lock() { false }
else { true }
492 pub fn garbage_collection(&self, worker
: &dyn TaskState
, upid
: &UPID
) -> Result
<(), Error
> {
494 if let Ok(ref mut _mutex
) = self.gc_mutex
.try_lock() {
496 // avoids that we run GC if an old daemon process has still a
497 // running backup writer, which is not save as we have no "oldest
498 // writer" information and thus no safe atime cutoff
499 let _exclusive_lock
= self.chunk_store
.try_exclusive_lock()?
;
501 let phase1_start_time
= proxmox
::tools
::time
::epoch_i64();
502 let oldest_writer
= self.chunk_store
.oldest_writer().unwrap_or(phase1_start_time
);
504 let mut gc_status
= GarbageCollectionStatus
::default();
505 gc_status
.upid
= Some(upid
.to_string());
507 crate::task_log
!(worker
, "Start GC phase1 (mark used chunks)");
509 self.mark_used_chunks(&mut gc_status
, worker
)?
;
511 crate::task_log
!(worker
, "Start GC phase2 (sweep unused chunks)");
512 self.chunk_store
.sweep_unused_chunks(
521 "Removed garbage: {}",
522 HumanByte
::from(gc_status
.removed_bytes
),
524 crate::task_log
!(worker
, "Removed chunks: {}", gc_status
.removed_chunks
);
525 if gc_status
.pending_bytes
> 0 {
528 "Pending removals: {} (in {} chunks)",
529 HumanByte
::from(gc_status
.pending_bytes
),
530 gc_status
.pending_chunks
,
533 if gc_status
.removed_bad
> 0 {
534 crate::task_log
!(worker
, "Removed bad files: {}", gc_status
.removed_bad
);
539 "Original data usage: {}",
540 HumanByte
::from(gc_status
.index_data_bytes
),
543 if gc_status
.index_data_bytes
> 0 {
544 let comp_per
= (gc_status
.disk_bytes
as f64 * 100.)/gc_status
.index_data_bytes
as f64;
547 "On-Disk usage: {} ({:.2}%)",
548 HumanByte
::from(gc_status
.disk_bytes
),
553 crate::task_log
!(worker
, "On-Disk chunks: {}", gc_status
.disk_chunks
);
555 if gc_status
.disk_chunks
> 0 {
556 let avg_chunk
= gc_status
.disk_bytes
/(gc_status
.disk_chunks
as u64);
557 crate::task_log
!(worker
, "Average chunk size: {}", HumanByte
::from(avg_chunk
));
560 *self.last_gc_status
.lock().unwrap() = gc_status
;
563 bail
!("Start GC failed - (already running/locked)");
569 pub fn try_shared_chunk_store_lock(&self) -> Result
<tools
::ProcessLockSharedGuard
, Error
> {
570 self.chunk_store
.try_shared_lock()
573 pub fn chunk_path(&self, digest
:&[u8; 32]) -> (PathBuf
, String
) {
574 self.chunk_store
.chunk_path(digest
)
577 pub fn cond_touch_chunk(&self, digest
: &[u8; 32], fail_if_not_exist
: bool
) -> Result
<bool
, Error
> {
578 self.chunk_store
.cond_touch_chunk(digest
, fail_if_not_exist
)
585 ) -> Result
<(bool
, u64), Error
> {
586 self.chunk_store
.insert_chunk(chunk
, digest
)
589 pub fn load_blob(&self, backup_dir
: &BackupDir
, filename
: &str) -> Result
<DataBlob
, Error
> {
590 let mut path
= self.base_path();
591 path
.push(backup_dir
.relative_path());
594 proxmox
::try_block
!({
595 let mut file
= std
::fs
::File
::open(&path
)?
;
596 DataBlob
::load_from_reader(&mut file
)
597 }).map_err(|err
| format_err
!("unable to load blob '{:?}' - {}", path
, err
))
601 pub fn load_chunk(&self, digest
: &[u8; 32]) -> Result
<DataBlob
, Error
> {
603 let (chunk_path
, digest_str
) = self.chunk_store
.chunk_path(digest
);
605 proxmox
::try_block
!({
606 let mut file
= std
::fs
::File
::open(&chunk_path
)?
;
607 DataBlob
::load_from_reader(&mut file
)
608 }).map_err(|err
| format_err
!(
609 "store '{}', unable to load chunk '{}' - {}",
616 pub fn load_manifest(
618 backup_dir
: &BackupDir
,
619 ) -> Result
<(BackupManifest
, u64), Error
> {
620 let blob
= self.load_blob(backup_dir
, MANIFEST_BLOB_NAME
)?
;
621 let raw_size
= blob
.raw_size();
622 let manifest
= BackupManifest
::try_from(blob
)?
;
623 Ok((manifest
, raw_size
))
626 pub fn load_manifest_json(
628 backup_dir
: &BackupDir
,
629 ) -> Result
<Value
, Error
> {
630 let blob
= self.load_blob(backup_dir
, MANIFEST_BLOB_NAME
)?
;
631 // no expected digest available
632 let manifest_data
= blob
.decode(None
, None
)?
;
633 let manifest
: Value
= serde_json
::from_slice(&manifest_data
[..])?
;
637 pub fn store_manifest(
639 backup_dir
: &BackupDir
,
641 ) -> Result
<(), Error
> {
642 let manifest
= serde_json
::to_string_pretty(&manifest
)?
;
643 let blob
= DataBlob
::encode(manifest
.as_bytes(), None
, true)?
;
644 let raw_data
= blob
.raw_data();
646 let mut path
= self.base_path();
647 path
.push(backup_dir
.relative_path());
648 path
.push(MANIFEST_BLOB_NAME
);
650 replace_file(&path
, raw_data
, CreateOptions
::new())?
;