use anyhow::{bail, format_err, Error};
use lazy_static::lazy_static;
-use chrono::{DateTime, Utc};
use serde_json::Value;
use proxmox::tools::fs::{replace_file, CreateOptions};
-use super::backup_info::{BackupGroup, BackupGroupGuard, BackupDir, BackupInfo};
+use super::backup_info::{BackupGroup, BackupDir};
use super::chunk_store::ChunkStore;
use super::dynamic_index::{DynamicIndexReader, DynamicIndexWriter};
use super::fixed_index::{FixedIndexReader, FixedIndexWriter};
use super::manifest::{MANIFEST_BLOB_NAME, CLIENT_LOG_BLOB_NAME, BackupManifest};
use super::index::*;
use super::{DataBlob, ArchiveType, archive_type};
-use crate::backup::CryptMode;
use crate::config::datastore;
-use crate::server::WorkerTask;
+use crate::task::TaskState;
use crate::tools;
-use crate::api2::types::GarbageCollectionStatus;
+use crate::tools::format::HumanByte;
+use crate::tools::fs::{lock_dir_noblock, DirLockGuard};
+use crate::api2::types::{GarbageCollectionStatus, Userid};
+use crate::server::UPID;
lazy_static! {
static ref DATASTORE_MAP: Mutex<HashMap<String, Arc<DataStore>>> = Mutex::new(HashMap::new());
let path = store_config["path"].as_str().unwrap();
+ Self::open_with_path(store_name, Path::new(path))
+ }
+
+ pub fn open_with_path(store_name: &str, path: &Path) -> Result<Self, Error> {
let chunk_store = ChunkStore::open(store_name, path)?;
let gc_status = GarbageCollectionStatus::default();
pub fn get_chunk_iterator(
&self,
) -> Result<
- impl Iterator<Item = (Result<tools::fs::ReadDirEntry, Error>, usize)>,
+ impl Iterator<Item = (Result<tools::fs::ReadDirEntry, Error>, usize, bool)>,
Error
> {
self.chunk_store.get_chunk_iterator()
let full_path = self.group_path(backup_group);
- let mut snap_list = backup_group.list_backups(&self.base_path())?;
- BackupInfo::sort_list(&mut snap_list, false);
- for snap in snap_list {
- if snap.is_finished() {
- break;
- } else {
- bail!(
- "cannot remove backup group {:?}, contains potentially running backup: {}",
- full_path,
- snap.backup_dir
- );
- }
- }
+ let _guard = tools::fs::lock_dir_noblock(&full_path, "backup group", "possible running backup")?;
log::info!("removing backup group {:?}", full_path);
std::fs::remove_dir_all(&full_path)
let full_path = self.snapshot_path(backup_dir);
+ let _guard;
if !force {
- let mut snap_list = backup_dir.group().list_backups(&self.base_path())?;
- BackupInfo::sort_list(&mut snap_list, false);
- let mut prev_snap_finished = true;
- for snap in snap_list {
- let cur_snap_finished = snap.is_finished();
- if &snap.backup_dir == backup_dir {
- if !cur_snap_finished {
- bail!(
- "cannot remove currently running snapshot: {:?}",
- backup_dir
- );
- }
- if !prev_snap_finished {
- bail!(
- "cannot remove snapshot {:?}, successor is currently running and potentially based on it",
- backup_dir
- );
- }
- break;
- }
- prev_snap_finished = cur_snap_finished;
- }
+ _guard = lock_dir_noblock(&full_path, "snapshot", "possibly running or used as base")?;
}
log::info!("removing backup snapshot {:?}", full_path);
/// Returns the time of the last successful backup
///
/// Or None if there is no backup in the group (or the group dir does not exist).
- pub fn last_successful_backup(&self, backup_group: &BackupGroup) -> Result<Option<DateTime<Utc>>, Error> {
+ pub fn last_successful_backup(&self, backup_group: &BackupGroup) -> Result<Option<i64>, Error> {
let base_path = self.base_path();
let mut group_path = base_path.clone();
group_path.push(backup_group.group_path());
/// Returns the backup owner.
///
/// The backup owner is the user who first created the backup group.
- pub fn get_owner(&self, backup_group: &BackupGroup) -> Result<String, Error> {
+ pub fn get_owner(&self, backup_group: &BackupGroup) -> Result<Userid, Error> {
let mut full_path = self.base_path();
full_path.push(backup_group.group_path());
full_path.push("owner");
let owner = proxmox::tools::fs::file_read_firstline(full_path)?;
- Ok(owner.trim_end().to_string()) // remove trailing newline
+ Ok(owner.trim_end().parse()?) // remove trailing newline
}
/// Set the backup owner.
- pub fn set_owner(&self, backup_group: &BackupGroup, userid: &str, force: bool) -> Result<(), Error> {
+ pub fn set_owner(
+ &self,
+ backup_group: &BackupGroup,
+ userid: &Userid,
+ force: bool,
+ ) -> Result<(), Error> {
let mut path = self.base_path();
path.push(backup_group.group_path());
path.push("owner");
let mut file = open_options.open(&path)
.map_err(|err| format_err!("unable to create owner file {:?} - {}", path, err))?;
- write!(file, "{}\n", userid)
+ writeln!(file, "{}", userid)
.map_err(|err| format_err!("unable to write owner file {:?} - {}", path, err))?;
Ok(())
/// And set the owner to 'userid'. If the group already exists, it returns the
/// current owner (instead of setting the owner).
///
- /// This also aquires an exclusive lock on the directory and returns the lock guard.
- pub fn create_locked_backup_group(&self, backup_group: &BackupGroup, userid: &str) -> Result<(String, BackupGroupGuard), Error> {
-
+ /// This also acquires an exclusive lock on the directory and returns the lock guard.
+ pub fn create_locked_backup_group(
+ &self,
+ backup_group: &BackupGroup,
+ userid: &Userid,
+ ) -> Result<(Userid, DirLockGuard), Error> {
// create intermediate path first:
let base_path = self.base_path();
// create the last component now
match std::fs::create_dir(&full_path) {
Ok(_) => {
- let guard = backup_group.lock(&base_path)?;
+ let guard = lock_dir_noblock(&full_path, "backup group", "another backup is already running")?;
self.set_owner(backup_group, userid, false)?;
let owner = self.get_owner(backup_group)?; // just to be sure
Ok((owner, guard))
}
Err(ref err) if err.kind() == io::ErrorKind::AlreadyExists => {
- let guard = backup_group.lock(&base_path)?;
+ let guard = lock_dir_noblock(&full_path, "backup group", "another backup is already running")?;
let owner = self.get_owner(backup_group)?; // just to be sure
Ok((owner, guard))
}
/// Creates a new backup snapshot inside a BackupGroup
///
/// The BackupGroup directory needs to exist.
- pub fn create_backup_dir(&self, backup_dir: &BackupDir) -> Result<(PathBuf, bool), io::Error> {
+ pub fn create_locked_backup_dir(&self, backup_dir: &BackupDir)
+ -> Result<(PathBuf, bool, DirLockGuard), Error>
+ {
let relative_path = backup_dir.relative_path();
let mut full_path = self.base_path();
full_path.push(&relative_path);
+ let lock = ||
+ lock_dir_noblock(&full_path, "snapshot", "internal error - tried creating snapshot that's already in use");
+
match std::fs::create_dir(&full_path) {
- Ok(_) => Ok((relative_path, true)),
- Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => Ok((relative_path, false)),
- Err(e) => Err(e)
+ Ok(_) => Ok((relative_path, true, lock()?)),
+ Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => Ok((relative_path, false, lock()?)),
+ Err(e) => Err(e.into())
}
}
index: I,
file_name: &Path, // only used for error reporting
status: &mut GarbageCollectionStatus,
- worker: &WorkerTask,
+ worker: &dyn TaskState,
) -> Result<(), Error> {
status.index_file_count += 1;
status.index_data_bytes += index.index_bytes();
for pos in 0..index.index_count() {
- worker.fail_on_abort()?;
+ worker.check_abort()?;
tools::fail_on_shutdown()?;
let digest = index.index_digest(pos).unwrap();
if let Err(err) = self.chunk_store.touch_chunk(digest) {
- bail!("unable to access chunk {}, required by {:?} - {}",
- proxmox::tools::digest_to_hex(digest), file_name, err);
+ crate::task_warn!(
+ worker,
+ "warning: unable to access chunk {}, required by {:?} - {}",
+ proxmox::tools::digest_to_hex(digest),
+ file_name,
+ err,
+ );
}
}
Ok(())
}
- fn mark_used_chunks(&self, status: &mut GarbageCollectionStatus, worker: &WorkerTask) -> Result<(), Error> {
+ fn mark_used_chunks(
+ &self,
+ status: &mut GarbageCollectionStatus,
+ worker: &dyn TaskState,
+ ) -> Result<(), Error> {
let image_list = self.list_images()?;
+ let image_count = image_list.len();
+
+ let mut done = 0;
+
+ let mut last_percentage: usize = 0;
+
for path in image_list {
- worker.fail_on_abort()?;
+ worker.check_abort()?;
tools::fail_on_shutdown()?;
if let Ok(archive_type) = archive_type(&path) {
self.index_mark_used_chunks(index, &path, status, worker)?;
}
}
+ done += 1;
+
+ let percentage = done*100/image_count;
+ if percentage > last_percentage {
+ crate::task_log!(
+ worker,
+ "percentage done: phase1 {}% ({} of {} index files)",
+ percentage,
+ done,
+ image_count,
+ );
+ last_percentage = percentage;
+ }
}
Ok(())
if let Ok(_) = self.gc_mutex.try_lock() { false } else { true }
}
- pub fn garbage_collection(&self, worker: &WorkerTask) -> Result<(), Error> {
+ pub fn garbage_collection(&self, worker: &dyn TaskState, upid: &UPID) -> Result<(), Error> {
if let Ok(ref mut _mutex) = self.gc_mutex.try_lock() {
+ // avoids that we run GC if an old daemon process has still a
+ // running backup writer, which is not save as we have no "oldest
+ // writer" information and thus no safe atime cutoff
let _exclusive_lock = self.chunk_store.try_exclusive_lock()?;
- let now = unsafe { libc::time(std::ptr::null_mut()) };
-
- let oldest_writer = self.chunk_store.oldest_writer().unwrap_or(now);
+ let phase1_start_time = proxmox::tools::time::epoch_i64();
+ let oldest_writer = self.chunk_store.oldest_writer().unwrap_or(phase1_start_time);
let mut gc_status = GarbageCollectionStatus::default();
- gc_status.upid = Some(worker.to_string());
-
- worker.log("Start GC phase1 (mark used chunks)");
-
- self.mark_used_chunks(&mut gc_status, &worker)?;
-
- worker.log("Start GC phase2 (sweep unused chunks)");
- self.chunk_store.sweep_unused_chunks(oldest_writer, &mut gc_status, &worker)?;
-
- worker.log(&format!("Removed bytes: {}", gc_status.removed_bytes));
- worker.log(&format!("Removed chunks: {}", gc_status.removed_chunks));
+ gc_status.upid = Some(upid.to_string());
+
+ crate::task_log!(worker, "Start GC phase1 (mark used chunks)");
+
+ self.mark_used_chunks(&mut gc_status, worker)?;
+
+ crate::task_log!(worker, "Start GC phase2 (sweep unused chunks)");
+ self.chunk_store.sweep_unused_chunks(
+ oldest_writer,
+ phase1_start_time,
+ &mut gc_status,
+ worker,
+ )?;
+
+ crate::task_log!(
+ worker,
+ "Removed garbage: {}",
+ HumanByte::from(gc_status.removed_bytes),
+ );
+ crate::task_log!(worker, "Removed chunks: {}", gc_status.removed_chunks);
if gc_status.pending_bytes > 0 {
- worker.log(&format!("Pending removals: {} bytes ({} chunks)", gc_status.pending_bytes, gc_status.pending_chunks));
+ crate::task_log!(
+ worker,
+ "Pending removals: {} (in {} chunks)",
+ HumanByte::from(gc_status.pending_bytes),
+ gc_status.pending_chunks,
+ );
+ }
+ if gc_status.removed_bad > 0 {
+ crate::task_log!(worker, "Removed bad files: {}", gc_status.removed_bad);
}
- worker.log(&format!("Original data bytes: {}", gc_status.index_data_bytes));
+ crate::task_log!(
+ worker,
+ "Original data usage: {}",
+ HumanByte::from(gc_status.index_data_bytes),
+ );
if gc_status.index_data_bytes > 0 {
- let comp_per = (gc_status.disk_bytes*100)/gc_status.index_data_bytes;
- worker.log(&format!("Disk bytes: {} ({} %)", gc_status.disk_bytes, comp_per));
+ let comp_per = (gc_status.disk_bytes as f64 * 100.)/gc_status.index_data_bytes as f64;
+ crate::task_log!(
+ worker,
+ "On-Disk usage: {} ({:.2}%)",
+ HumanByte::from(gc_status.disk_bytes),
+ comp_per,
+ );
}
- worker.log(&format!("Disk chunks: {}", gc_status.disk_chunks));
+ crate::task_log!(worker, "On-Disk chunks: {}", gc_status.disk_chunks);
if gc_status.disk_chunks > 0 {
let avg_chunk = gc_status.disk_bytes/(gc_status.disk_chunks as u64);
- worker.log(&format!("Average chunk size: {}", avg_chunk));
+ crate::task_log!(worker, "Average chunk size: {}", HumanByte::from(avg_chunk));
}
*self.last_gc_status.lock().unwrap() = gc_status;
self.chunk_store.insert_chunk(chunk, digest)
}
- pub fn verify_stored_chunk(&self, digest: &[u8; 32], expected_chunk_size: u64) -> Result<(), Error> {
- let blob = self.load_chunk(digest)?;
- blob.verify_unencrypted(expected_chunk_size as usize, digest)?;
- Ok(())
- }
-
pub fn load_blob(&self, backup_dir: &BackupDir, filename: &str) -> Result<DataBlob, Error> {
let mut path = self.base_path();
path.push(backup_dir.relative_path());
pub fn load_manifest(
&self,
backup_dir: &BackupDir,
- ) -> Result<(BackupManifest, CryptMode, u64), Error> {
+ ) -> Result<(BackupManifest, u64), Error> {
let blob = self.load_blob(backup_dir, MANIFEST_BLOB_NAME)?;
let raw_size = blob.raw_size();
- let crypt_mode = blob.crypt_mode()?;
let manifest = BackupManifest::try_from(blob)?;
- Ok((manifest, crypt_mode, raw_size))
+ Ok((manifest, raw_size))
}
pub fn load_manifest_json(
backup_dir: &BackupDir,
) -> Result<Value, Error> {
let blob = self.load_blob(backup_dir, MANIFEST_BLOB_NAME)?;
- let manifest_data = blob.decode(None)?;
+ // no expected digest available
+ let manifest_data = blob.decode(None, None)?;
let manifest: Value = serde_json::from_slice(&manifest_data[..])?;
Ok(manifest)
}