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
;
9 use chrono
::{DateTime, Utc}
;
10 use serde_json
::Value
;
12 use proxmox
::tools
::fs
::{replace_file, CreateOptions}
;
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, CLIENT_LOG_BLOB_NAME, BackupManifest}
;
20 use super::{DataBlob, ArchiveType, archive_type}
;
21 use crate::config
::datastore
;
22 use crate::server
::WorkerTask
;
24 use crate::tools
::format
::HumanByte
;
25 use crate::tools
::fs
::{lock_dir_noblock, DirLockGuard}
;
26 use crate::api2
::types
::{GarbageCollectionStatus, Userid}
;
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 let chunk_store
= ChunkStore
::open(store_name
, path
)?
;
76 let gc_status
= GarbageCollectionStatus
::default();
79 chunk_store
: Arc
::new(chunk_store
),
80 gc_mutex
: Mutex
::new(false),
81 last_gc_status
: Mutex
::new(gc_status
),
85 pub fn get_chunk_iterator(
88 impl Iterator
<Item
= (Result
<tools
::fs
::ReadDirEntry
, Error
>, usize, bool
)>,
91 self.chunk_store
.get_chunk_iterator()
94 pub fn create_fixed_writer
<P
: AsRef
<Path
>>(&self, filename
: P
, size
: usize, chunk_size
: usize) -> Result
<FixedIndexWriter
, Error
> {
96 let index
= FixedIndexWriter
::create(self.chunk_store
.clone(), filename
.as_ref(), size
, chunk_size
)?
;
101 pub fn open_fixed_reader
<P
: AsRef
<Path
>>(&self, filename
: P
) -> Result
<FixedIndexReader
, Error
> {
103 let full_path
= self.chunk_store
.relative_path(filename
.as_ref());
105 let index
= FixedIndexReader
::open(&full_path
)?
;
110 pub fn create_dynamic_writer
<P
: AsRef
<Path
>>(
112 ) -> Result
<DynamicIndexWriter
, Error
> {
114 let index
= DynamicIndexWriter
::create(
115 self.chunk_store
.clone(), filename
.as_ref())?
;
120 pub fn open_dynamic_reader
<P
: AsRef
<Path
>>(&self, filename
: P
) -> Result
<DynamicIndexReader
, Error
> {
122 let full_path
= self.chunk_store
.relative_path(filename
.as_ref());
124 let index
= DynamicIndexReader
::open(&full_path
)?
;
129 pub fn open_index
<P
>(&self, filename
: P
) -> Result
<Box
<dyn IndexFile
+ Send
>, Error
>
133 let filename
= filename
.as_ref();
134 let out
: Box
<dyn IndexFile
+ Send
> =
135 match archive_type(filename
)?
{
136 ArchiveType
::DynamicIndex
=> Box
::new(self.open_dynamic_reader(filename
)?
),
137 ArchiveType
::FixedIndex
=> Box
::new(self.open_fixed_reader(filename
)?
),
138 _
=> bail
!("cannot open index file of unknown type: {:?}", filename
),
143 pub fn name(&self) -> &str {
144 self.chunk_store
.name()
147 pub fn base_path(&self) -> PathBuf
{
148 self.chunk_store
.base_path()
151 /// Cleanup a backup directory
153 /// Removes all files not mentioned in the manifest.
154 pub fn cleanup_backup_dir(&self, backup_dir
: &BackupDir
, manifest
: &BackupManifest
155 ) -> Result
<(), Error
> {
157 let mut full_path
= self.base_path();
158 full_path
.push(backup_dir
.relative_path());
160 let mut wanted_files
= HashSet
::new();
161 wanted_files
.insert(MANIFEST_BLOB_NAME
.to_string());
162 wanted_files
.insert(CLIENT_LOG_BLOB_NAME
.to_string());
163 manifest
.files().iter().for_each(|item
| { wanted_files.insert(item.filename.clone()); }
);
165 for item
in tools
::fs
::read_subdir(libc
::AT_FDCWD
, &full_path
)?
{
166 if let Ok(item
) = item
{
167 if let Some(file_type
) = item
.file_type() {
168 if file_type
!= nix
::dir
::Type
::File { continue; }
170 let file_name
= item
.file_name().to_bytes();
171 if file_name
== b
"." || file_name
== b
".." { continue; }
;
173 if let Ok(name
) = std
::str::from_utf8(file_name
) {
174 if wanted_files
.contains(name
) { continue; }
176 println
!("remove unused file {:?}", item
.file_name());
177 let dirfd
= item
.parent_fd();
178 let _res
= unsafe { libc::unlinkat(dirfd, item.file_name().as_ptr(), 0) }
;
185 /// Returns the absolute path for a backup_group
186 pub fn group_path(&self, backup_group
: &BackupGroup
) -> PathBuf
{
187 let mut full_path
= self.base_path();
188 full_path
.push(backup_group
.group_path());
192 /// Returns the absolute path for backup_dir
193 pub fn snapshot_path(&self, backup_dir
: &BackupDir
) -> PathBuf
{
194 let mut full_path
= self.base_path();
195 full_path
.push(backup_dir
.relative_path());
199 /// Remove a complete backup group including all snapshots
200 pub fn remove_backup_group(&self, backup_group
: &BackupGroup
) -> Result
<(), Error
> {
202 let full_path
= self.group_path(backup_group
);
204 let _guard
= tools
::fs
::lock_dir_noblock(&full_path
, "backup group", "possible running backup")?
;
206 log
::info
!("removing backup group {:?}", full_path
);
207 std
::fs
::remove_dir_all(&full_path
)
210 "removing backup group {:?} failed - {}",
219 /// Remove a backup directory including all content
220 pub fn remove_backup_dir(&self, backup_dir
: &BackupDir
, force
: bool
) -> Result
<(), Error
> {
222 let full_path
= self.snapshot_path(backup_dir
);
226 _guard
= lock_dir_noblock(&full_path
, "snapshot", "possibly running or used as base")?
;
229 log
::info
!("removing backup snapshot {:?}", full_path
);
230 std
::fs
::remove_dir_all(&full_path
)
233 "removing backup snapshot {:?} failed - {}",
242 /// Returns the time of the last successful backup
244 /// Or None if there is no backup in the group (or the group dir does not exist).
245 pub fn last_successful_backup(&self, backup_group
: &BackupGroup
) -> Result
<Option
<DateTime
<Utc
>>, Error
> {
246 let base_path
= self.base_path();
247 let mut group_path
= base_path
.clone();
248 group_path
.push(backup_group
.group_path());
250 if group_path
.exists() {
251 backup_group
.last_successful_backup(&base_path
)
257 /// Returns the backup owner.
259 /// The backup owner is the user who first created the backup group.
260 pub fn get_owner(&self, backup_group
: &BackupGroup
) -> Result
<Userid
, Error
> {
261 let mut full_path
= self.base_path();
262 full_path
.push(backup_group
.group_path());
263 full_path
.push("owner");
264 let owner
= proxmox
::tools
::fs
::file_read_firstline(full_path
)?
;
265 Ok(owner
.trim_end().parse()?
) // remove trailing newline
268 /// Set the backup owner.
271 backup_group
: &BackupGroup
,
274 ) -> Result
<(), Error
> {
275 let mut path
= self.base_path();
276 path
.push(backup_group
.group_path());
279 let mut open_options
= std
::fs
::OpenOptions
::new();
280 open_options
.write(true);
281 open_options
.truncate(true);
284 open_options
.create(true);
286 open_options
.create_new(true);
289 let mut file
= open_options
.open(&path
)
290 .map_err(|err
| format_err
!("unable to create owner file {:?} - {}", path
, err
))?
;
292 write
!(file
, "{}\n", userid
)
293 .map_err(|err
| format_err
!("unable to write owner file {:?} - {}", path
, err
))?
;
298 /// Create (if it does not already exists) and lock a backup group
300 /// And set the owner to 'userid'. If the group already exists, it returns the
301 /// current owner (instead of setting the owner).
303 /// This also acquires an exclusive lock on the directory and returns the lock guard.
304 pub fn create_locked_backup_group(
306 backup_group
: &BackupGroup
,
308 ) -> Result
<(Userid
, DirLockGuard
), Error
> {
309 // create intermediate path first:
310 let base_path
= self.base_path();
312 let mut full_path
= base_path
.clone();
313 full_path
.push(backup_group
.backup_type());
314 std
::fs
::create_dir_all(&full_path
)?
;
316 full_path
.push(backup_group
.backup_id());
318 // create the last component now
319 match std
::fs
::create_dir(&full_path
) {
321 let guard
= lock_dir_noblock(&full_path
, "backup group", "another backup is already running")?
;
322 self.set_owner(backup_group
, userid
, false)?
;
323 let owner
= self.get_owner(backup_group
)?
; // just to be sure
326 Err(ref err
) if err
.kind() == io
::ErrorKind
::AlreadyExists
=> {
327 let guard
= lock_dir_noblock(&full_path
, "backup group", "another backup is already running")?
;
328 let owner
= self.get_owner(backup_group
)?
; // just to be sure
331 Err(err
) => bail
!("unable to create backup group {:?} - {}", full_path
, err
),
335 /// Creates a new backup snapshot inside a BackupGroup
337 /// The BackupGroup directory needs to exist.
338 pub fn create_locked_backup_dir(&self, backup_dir
: &BackupDir
)
339 -> Result
<(PathBuf
, bool
, DirLockGuard
), Error
>
341 let relative_path
= backup_dir
.relative_path();
342 let mut full_path
= self.base_path();
343 full_path
.push(&relative_path
);
346 lock_dir_noblock(&full_path
, "snapshot", "internal error - tried creating snapshot that's already in use");
348 match std
::fs
::create_dir(&full_path
) {
349 Ok(_
) => Ok((relative_path
, true, lock()?
)),
350 Err(ref e
) if e
.kind() == io
::ErrorKind
::AlreadyExists
=> Ok((relative_path
, false, lock()?
)),
351 Err(e
) => Err(e
.into())
355 pub fn list_images(&self) -> Result
<Vec
<PathBuf
>, Error
> {
356 let base
= self.base_path();
358 let mut list
= vec
![];
360 use walkdir
::WalkDir
;
362 let walker
= WalkDir
::new(&base
).same_file_system(true).into_iter();
364 // make sure we skip .chunks (and other hidden files to keep it simple)
365 fn is_hidden(entry
: &walkdir
::DirEntry
) -> bool
{
368 .map(|s
| s
.starts_with("."))
371 let handle_entry_err
= |err
: walkdir
::Error
| {
372 if let Some(inner
) = err
.io_error() {
373 let path
= err
.path().unwrap_or(Path
::new(""));
375 io
::ErrorKind
::PermissionDenied
=> {
376 // only allow to skip ext4 fsck directory, avoid GC if, for example,
377 // a user got file permissions wrong on datastore rsync to new server
378 if err
.depth() > 1 || !path
.ends_with("lost+found") {
379 bail
!("cannot continue garbage-collection safely, permission denied on: {}", path
.display())
382 _
=> bail
!("unexpected error on datastore traversal: {} - {}", inner
, path
.display()),
387 for entry
in walker
.filter_entry(|e
| !is_hidden(e
)) {
388 let path
= match entry
{
389 Ok(entry
) => entry
.into_path(),
391 handle_entry_err(err
)?
;
395 if let Ok(archive_type
) = archive_type(&path
) {
396 if archive_type
== ArchiveType
::FixedIndex
|| archive_type
== ArchiveType
::DynamicIndex
{
405 // mark chunks used by ``index`` as used
406 fn index_mark_used_chunks
<I
: IndexFile
>(
409 file_name
: &Path
, // only used for error reporting
410 status
: &mut GarbageCollectionStatus
,
412 ) -> Result
<(), Error
> {
414 status
.index_file_count
+= 1;
415 status
.index_data_bytes
+= index
.index_bytes();
417 for pos
in 0..index
.index_count() {
418 worker
.fail_on_abort()?
;
419 tools
::fail_on_shutdown()?
;
420 let digest
= index
.index_digest(pos
).unwrap();
421 if let Err(err
) = self.chunk_store
.touch_chunk(digest
) {
422 worker
.warn(&format
!("warning: unable to access chunk {}, required by {:?} - {}",
423 proxmox
::tools
::digest_to_hex(digest
), file_name
, err
));
429 fn mark_used_chunks(&self, status
: &mut GarbageCollectionStatus
, worker
: &WorkerTask
) -> Result
<(), Error
> {
431 let image_list
= self.list_images()?
;
433 let image_count
= image_list
.len();
437 let mut last_percentage
: usize = 0;
439 for path
in image_list
{
441 worker
.fail_on_abort()?
;
442 tools
::fail_on_shutdown()?
;
444 if let Ok(archive_type
) = archive_type(&path
) {
445 if archive_type
== ArchiveType
::FixedIndex
{
446 let index
= self.open_fixed_reader(&path
)?
;
447 self.index_mark_used_chunks(index
, &path
, status
, worker
)?
;
448 } else if archive_type
== ArchiveType
::DynamicIndex
{
449 let index
= self.open_dynamic_reader(&path
)?
;
450 self.index_mark_used_chunks(index
, &path
, status
, worker
)?
;
455 let percentage
= done
*100/image_count
;
456 if percentage
> last_percentage
{
457 worker
.log(format
!("percentage done: phase1 {}% ({} of {} index files)",
458 percentage
, done
, image_count
));
459 last_percentage
= percentage
;
466 pub fn last_gc_status(&self) -> GarbageCollectionStatus
{
467 self.last_gc_status
.lock().unwrap().clone()
470 pub fn garbage_collection_running(&self) -> bool
{
471 if let Ok(_
) = self.gc_mutex
.try_lock() { false }
else { true }
474 pub fn garbage_collection(&self, worker
: &WorkerTask
) -> Result
<(), Error
> {
476 if let Ok(ref mut _mutex
) = self.gc_mutex
.try_lock() {
478 let _exclusive_lock
= self.chunk_store
.try_exclusive_lock()?
;
480 let phase1_start_time
= unsafe { libc::time(std::ptr::null_mut()) }
;
481 let oldest_writer
= self.chunk_store
.oldest_writer().unwrap_or(phase1_start_time
);
483 let mut gc_status
= GarbageCollectionStatus
::default();
484 gc_status
.upid
= Some(worker
.to_string());
486 worker
.log("Start GC phase1 (mark used chunks)");
488 self.mark_used_chunks(&mut gc_status
, &worker
)?
;
490 worker
.log("Start GC phase2 (sweep unused chunks)");
491 self.chunk_store
.sweep_unused_chunks(oldest_writer
, phase1_start_time
, &mut gc_status
, &worker
)?
;
493 worker
.log(&format
!("Removed garbage: {}", HumanByte
::from(gc_status
.removed_bytes
)));
494 worker
.log(&format
!("Removed chunks: {}", gc_status
.removed_chunks
));
495 if gc_status
.pending_bytes
> 0 {
496 worker
.log(&format
!("Pending removals: {} (in {} chunks)", HumanByte
::from(gc_status
.pending_bytes
), gc_status
.pending_chunks
));
498 if gc_status
.removed_bad
> 0 {
499 worker
.log(&format
!("Removed bad files: {}", gc_status
.removed_bad
));
502 worker
.log(&format
!("Original data usage: {}", HumanByte
::from(gc_status
.index_data_bytes
)));
504 if gc_status
.index_data_bytes
> 0 {
505 let comp_per
= (gc_status
.disk_bytes
as f64 * 100.)/gc_status
.index_data_bytes
as f64;
506 worker
.log(&format
!("On-Disk usage: {} ({:.2}%)", HumanByte
::from(gc_status
.disk_bytes
), comp_per
));
509 worker
.log(&format
!("On-Disk chunks: {}", gc_status
.disk_chunks
));
511 if gc_status
.disk_chunks
> 0 {
512 let avg_chunk
= gc_status
.disk_bytes
/(gc_status
.disk_chunks
as u64);
513 worker
.log(&format
!("Average chunk size: {}", HumanByte
::from(avg_chunk
)));
516 *self.last_gc_status
.lock().unwrap() = gc_status
;
519 bail
!("Start GC failed - (already running/locked)");
525 pub fn try_shared_chunk_store_lock(&self) -> Result
<tools
::ProcessLockSharedGuard
, Error
> {
526 self.chunk_store
.try_shared_lock()
529 pub fn chunk_path(&self, digest
:&[u8; 32]) -> (PathBuf
, String
) {
530 self.chunk_store
.chunk_path(digest
)
533 pub fn cond_touch_chunk(&self, digest
: &[u8; 32], fail_if_not_exist
: bool
) -> Result
<bool
, Error
> {
534 self.chunk_store
.cond_touch_chunk(digest
, fail_if_not_exist
)
541 ) -> Result
<(bool
, u64), Error
> {
542 self.chunk_store
.insert_chunk(chunk
, digest
)
545 pub fn load_blob(&self, backup_dir
: &BackupDir
, filename
: &str) -> Result
<DataBlob
, Error
> {
546 let mut path
= self.base_path();
547 path
.push(backup_dir
.relative_path());
550 proxmox
::try_block
!({
551 let mut file
= std
::fs
::File
::open(&path
)?
;
552 DataBlob
::load_from_reader(&mut file
)
553 }).map_err(|err
| format_err
!("unable to load blob '{:?}' - {}", path
, err
))
557 pub fn load_chunk(&self, digest
: &[u8; 32]) -> Result
<DataBlob
, Error
> {
559 let (chunk_path
, digest_str
) = self.chunk_store
.chunk_path(digest
);
561 proxmox
::try_block
!({
562 let mut file
= std
::fs
::File
::open(&chunk_path
)?
;
563 DataBlob
::load_from_reader(&mut file
)
564 }).map_err(|err
| format_err
!(
565 "store '{}', unable to load chunk '{}' - {}",
572 pub fn load_manifest(
574 backup_dir
: &BackupDir
,
575 ) -> Result
<(BackupManifest
, u64), Error
> {
576 let blob
= self.load_blob(backup_dir
, MANIFEST_BLOB_NAME
)?
;
577 let raw_size
= blob
.raw_size();
578 let manifest
= BackupManifest
::try_from(blob
)?
;
579 Ok((manifest
, raw_size
))
582 pub fn load_manifest_json(
584 backup_dir
: &BackupDir
,
585 ) -> Result
<Value
, Error
> {
586 let blob
= self.load_blob(backup_dir
, MANIFEST_BLOB_NAME
)?
;
587 // no expected digest available
588 let manifest_data
= blob
.decode(None
, None
)?
;
589 let manifest
: Value
= serde_json
::from_slice(&manifest_data
[..])?
;
593 pub fn store_manifest(
595 backup_dir
: &BackupDir
,
597 ) -> Result
<(), Error
> {
598 let manifest
= serde_json
::to_string_pretty(&manifest
)?
;
599 let blob
= DataBlob
::encode(manifest
.as_bytes(), None
, true)?
;
600 let raw_data
= blob
.raw_data();
602 let mut path
= self.base_path();
603 path
.push(backup_dir
.relative_path());
604 path
.push(MANIFEST_BLOB_NAME
);
606 replace_file(&path
, raw_data
, CreateOptions
::new())?
;