]> git.proxmox.com Git - proxmox-backup.git/blobdiff - src/api2/admin/datastore.rs
src/backup/prune.rs: add new helper keeps_something()
[proxmox-backup.git] / src / api2 / admin / datastore.rs
index aa672009700a6ae62c1ea870be4b51ed57802c33..4264339b35181fde4c364259c8c20e73025ab2c9 100644 (file)
@@ -1,26 +1,24 @@
+use std::collections::{HashSet, HashMap};
+
+use chrono::{TimeZone, Local};
 use failure::*;
 use futures::*;
-
-use crate::tools;
-use crate::api2::types::*;
-use crate::api_schema::*;
-use crate::api_schema::router::*;
-//use crate::server::rest::*;
+use hyper::http::request::Parts;
+use hyper::{header, Body, Response, StatusCode};
 use serde_json::{json, Value};
-use std::collections::{HashSet, HashMap};
-use chrono::{DateTime, Datelike, TimeZone, Local};
-use std::path::PathBuf;
 
 use proxmox::{sortable, identity};
+use proxmox::api::{http_err, list_subdirs_api_method};
+use proxmox::api::{ApiFuture, ApiHandler, ApiMethod, Router, RpcEnvironment, RpcEnvironmentType};
+use proxmox::api::router::SubdirMap;
+use proxmox::api::schema::*;
 use proxmox::tools::{try_block, fs::file_get_contents, fs::file_set_contents};
 
-use crate::config::datastore;
-
+use crate::api2::types::*;
 use crate::backup::*;
+use crate::config::datastore;
 use crate::server::WorkerTask;
-
-use hyper::{header, Body, Response, StatusCode};
-use hyper::http::request::Parts;
+use crate::tools;
 
 fn read_backup_index(store: &DataStore, backup_dir: &BackupDir) -> Result<Value, Error> {
 
@@ -30,14 +28,20 @@ fn read_backup_index(store: &DataStore, backup_dir: &BackupDir) -> Result<Value,
 
     let raw_data = file_get_contents(&path)?;
     let data = DataBlob::from_raw(raw_data)?.decode(None)?;
+    let index_size = data.len();
     let mut result: Value = serde_json::from_reader(&mut &data[..])?;
 
-    let result = result["files"].take();
+    let mut result = result["files"].take();
 
     if result == Value::Null {
         bail!("missing 'files' property in backup index {:?}", path);
     }
 
+    result.as_array_mut().unwrap().push(json!({
+        "filename": "index.json.blob",
+        "size": index_size,
+    }));
+
     Ok(result)
 }
 
@@ -54,26 +58,6 @@ fn group_backups(backup_list: Vec<BackupInfo>) -> HashMap<String, Vec<BackupInfo
     group_hash
 }
 
-fn mark_selections<F: Fn(DateTime<Local>, &BackupInfo) -> String> (
-    mark: &mut HashSet<PathBuf>,
-    list: &Vec<BackupInfo>,
-    keep: usize,
-    select_id: F,
-){
-    let mut hash = HashSet::new();
-    for info in list {
-        let local_time = info.backup_dir.backup_time().with_timezone(&Local);
-        if hash.len() >= keep as usize { break; }
-        let backup_id = info.backup_dir.relative_path();
-        let sel_id: String = select_id(local_time, &info);
-        if !hash.contains(&sel_id) {
-            hash.insert(sel_id);
-            //println!(" KEEP ID {} {}", backup_id, local_time.format("%c"));
-            mark.insert(backup_id);
-        }
-    }
-}
-
 fn list_groups(
     param: Value,
     _info: &ApiMethod,
@@ -295,7 +279,6 @@ const API_METHOD_STATUS: ApiMethod = ApiMethod::new(
     )
 );
 
-
 fn prune(
     param: Value,
     _info: &ApiMethod,
@@ -311,68 +294,36 @@ fn prune(
 
     let datastore = DataStore::lookup_datastore(store)?;
 
-    let mut keep_all = true;
-
-    for opt in &["keep-last", "keep-daily", "keep-weekly", "keep-weekly", "keep-yearly"] {
-        if !param[opt].is_null() {
-            keep_all = false;
-            break;
-        }
-    }
+    let prune_options = PruneOptions {
+        keep_last: param["keep-last"].as_u64(),
+        keep_daily: param["keep-daily"].as_u64(),
+        keep_weekly: param["keep-weekly"].as_u64(),
+        keep_monthly: param["keep-monthly"].as_u64(),
+        keep_yearly: param["keep-yearly"].as_u64(),
+    };
 
     let worker = WorkerTask::new("prune", Some(store.to_owned()), "root@pam", true)?;
     let result = try_block! {
-        if keep_all {
+        if !prune_options.keeps_something() {
             worker.log("No prune selection - keeping all files.");
             return Ok(());
         } else {
             worker.log(format!("Starting prune on store {}", store));
         }
 
-        let mut list = group.list_backups(&datastore.base_path())?;
+        let list = group.list_backups(&datastore.base_path())?;
 
-        let mut mark = HashSet::new();
+        let mut prune_info = compute_prune_info(list, &prune_options)?;
 
-        BackupInfo::sort_list(&mut list, false);
-
-        if let Some(keep_last) = param["keep-last"].as_u64() {
-            list.iter().take(keep_last as usize).for_each(|info| {
-                mark.insert(info.backup_dir.relative_path());
-            });
-        }
+        prune_info.reverse(); // delete older snapshots first
 
-        if let Some(keep_daily) = param["keep-daily"].as_u64() {
-            mark_selections(&mut mark, &list, keep_daily as usize, |local_time, _info| {
-                format!("{}/{}/{}", local_time.year(), local_time.month(), local_time.day())
-            });
-        }
-
-        if let Some(keep_weekly) = param["keep-weekly"].as_u64() {
-            mark_selections(&mut mark, &list, keep_weekly as usize, |local_time, _info| {
-                format!("{}/{}", local_time.year(), local_time.iso_week().week())
-            });
-        }
-
-        if let Some(keep_monthly) = param["keep-monthly"].as_u64() {
-            mark_selections(&mut mark, &list, keep_monthly as usize, |local_time, _info| {
-                format!("{}/{}", local_time.year(), local_time.month())
-            });
-        }
-
-        if let Some(keep_yearly) = param["keep-yearly"].as_u64() {
-            mark_selections(&mut mark, &list, keep_yearly as usize, |local_time, _info| {
-                format!("{}/{}", local_time.year(), local_time.year())
-            });
-        }
-
-        let mut remove_list: Vec<BackupInfo> = list.into_iter()
-            .filter(|info| !mark.contains(&info.backup_dir.relative_path())).collect();
-
-        BackupInfo::sort_list(&mut remove_list, true);
-
-        for info in remove_list {
-            worker.log(format!("remove {:?}", info.backup_dir));
-            datastore.remove_backup_dir(&info.backup_dir)?;
+        for (info, keep) in prune_info {
+            if keep {
+                worker.log(format!("keep {:?}", info.backup_dir.relative_path()));
+            } else {
+                worker.log(format!("remove {:?}", info.backup_dir.relative_path()));
+                datastore.remove_backup_dir(&info.backup_dir)?;
+            }
         }
 
         Ok(())
@@ -481,48 +432,48 @@ fn download_file(
     param: Value,
     _info: &ApiMethod,
     _rpcenv: Box<dyn RpcEnvironment>,
-) -> Result<BoxFut, Error> {
+) -> ApiFuture {
 
-    let store = tools::required_string_param(&param, "store")?;
+    async move {
+        let store = tools::required_string_param(&param, "store")?;
 
-    let datastore = DataStore::lookup_datastore(store)?;
+        let datastore = DataStore::lookup_datastore(store)?;
 
-    let file_name = tools::required_string_param(&param, "file-name")?.to_owned();
+        let file_name = tools::required_string_param(&param, "file-name")?.to_owned();
 
-    let backup_type = tools::required_string_param(&param, "backup-type")?;
-    let backup_id = tools::required_string_param(&param, "backup-id")?;
-    let backup_time = tools::required_integer_param(&param, "backup-time")?;
+        let backup_type = tools::required_string_param(&param, "backup-type")?;
+        let backup_id = tools::required_string_param(&param, "backup-id")?;
+        let backup_time = tools::required_integer_param(&param, "backup-time")?;
 
-    println!("Download {} from {} ({}/{}/{}/{})", file_name, store,
-             backup_type, backup_id, Local.timestamp(backup_time, 0), file_name);
+        println!("Download {} from {} ({}/{}/{}/{})", file_name, store,
+                 backup_type, backup_id, Local.timestamp(backup_time, 0), file_name);
 
-    let backup_dir = BackupDir::new(backup_type, backup_id, backup_time);
+        let backup_dir = BackupDir::new(backup_type, backup_id, backup_time);
 
-    let mut path = datastore.base_path();
-    path.push(backup_dir.relative_path());
-    path.push(&file_name);
-
-    let response_future = tokio::fs::File::open(path)
-        .map_err(|err| http_err!(BAD_REQUEST, format!("File open failed: {}", err)))
-        .and_then(move |file| {
-            let payload = tokio::codec::FramedRead::new(file, tokio::codec::BytesCodec::new())
-                .map_ok(|bytes| hyper::Chunk::from(bytes.freeze()));
-            let body = Body::wrap_stream(payload);
-
-            // fixme: set other headers ?
-            futures::future::ok(Response::builder()
-               .status(StatusCode::OK)
-               .header(header::CONTENT_TYPE, "application/octet-stream")
-               .body(body)
-               .unwrap())
-        });
+        let mut path = datastore.base_path();
+        path.push(backup_dir.relative_path());
+        path.push(&file_name);
 
-    Ok(Box::new(response_future))
+        let file = tokio::fs::File::open(path)
+            .map_err(|err| http_err!(BAD_REQUEST, format!("File open failed: {}", err)))
+            .await?;
+
+        let payload = tokio::codec::FramedRead::new(file, tokio::codec::BytesCodec::new())
+            .map_ok(|bytes| hyper::Chunk::from(bytes.freeze()));
+        let body = Body::wrap_stream(payload);
+
+        // fixme: set other headers ?
+        Ok(Response::builder()
+           .status(StatusCode::OK)
+           .header(header::CONTENT_TYPE, "application/octet-stream")
+           .body(body)
+           .unwrap())
+    }.boxed()
 }
 
 #[sortable]
 pub const API_METHOD_DOWNLOAD_FILE: ApiMethod = ApiMethod::new(
-    &ApiHandler::Async(&download_file),
+    &ApiHandler::AsyncHttp(&download_file),
     &ObjectSchema::new(
         "Download single raw file from backup snapshot.",
         &sorted!([
@@ -544,56 +495,54 @@ fn upload_backup_log(
     param: Value,
     _info: &ApiMethod,
     _rpcenv: Box<dyn RpcEnvironment>,
-) -> Result<BoxFut, Error> {
+) -> ApiFuture {
 
-    let store = tools::required_string_param(&param, "store")?;
+    async move {
+        let store = tools::required_string_param(&param, "store")?;
 
-    let datastore = DataStore::lookup_datastore(store)?;
+        let datastore = DataStore::lookup_datastore(store)?;
 
-    let file_name = "client.log.blob";
+        let file_name = "client.log.blob";
 
-    let backup_type = tools::required_string_param(&param, "backup-type")?;
-    let backup_id = tools::required_string_param(&param, "backup-id")?;
-    let backup_time = tools::required_integer_param(&param, "backup-time")?;
+        let backup_type = tools::required_string_param(&param, "backup-type")?;
+        let backup_id = tools::required_string_param(&param, "backup-id")?;
+        let backup_time = tools::required_integer_param(&param, "backup-time")?;
 
-    let backup_dir = BackupDir::new(backup_type, backup_id, backup_time);
+        let backup_dir = BackupDir::new(backup_type, backup_id, backup_time);
 
-    let mut path = datastore.base_path();
-    path.push(backup_dir.relative_path());
-    path.push(&file_name);
+        let mut path = datastore.base_path();
+        path.push(backup_dir.relative_path());
+        path.push(&file_name);
 
-    if path.exists() {
-        bail!("backup already contains a log.");
-    }
+        if path.exists() {
+            bail!("backup already contains a log.");
+        }
 
-    println!("Upload backup log to {}/{}/{}/{}/{}", store,
-             backup_type, backup_id, BackupDir::backup_time_to_string(backup_dir.backup_time()), file_name);
-
-    let resp = req_body
-        .map_err(Error::from)
-        .try_fold(Vec::new(), |mut acc, chunk| {
-            acc.extend_from_slice(&*chunk);
-            future::ok::<_, Error>(acc)
-        })
-        .and_then(move |data| async move {
-            let blob = DataBlob::from_raw(data)?;
-            // always verify CRC at server side
-            blob.verify_crc()?;
-            let raw_data = blob.raw_data();
-            file_set_contents(&path, raw_data, None)?;
-            Ok(())
-        })
-        .and_then(move |_| {
-            future::ok(crate::server::formatter::json_response(Ok(Value::Null)))
-        })
-        ;
-
-    Ok(Box::new(resp))
+        println!("Upload backup log to {}/{}/{}/{}/{}", store,
+                 backup_type, backup_id, BackupDir::backup_time_to_string(backup_dir.backup_time()), file_name);
+
+        let data = req_body
+            .map_err(Error::from)
+            .try_fold(Vec::new(), |mut acc, chunk| {
+                acc.extend_from_slice(&*chunk);
+                future::ok::<_, Error>(acc)
+            })
+            .await?;
+
+        let blob = DataBlob::from_raw(data)?;
+        // always verify CRC at server side
+        blob.verify_crc()?;
+        let raw_data = blob.raw_data();
+        file_set_contents(&path, raw_data, None)?;
+
+        // fixme: use correct formatter
+        Ok(crate::server::formatter::json_response(Ok(Value::Null)))
+    }.boxed()
 }
 
 #[sortable]
 pub const API_METHOD_UPLOAD_BACKUP_LOG: ApiMethod = ApiMethod::new(
-    &ApiHandler::Async(&upload_backup_log),
+    &ApiHandler::AsyncHttp(&upload_backup_log),
     &ObjectSchema::new(
         "Download single raw file from backup snapshot.",
         &sorted!([
@@ -699,7 +648,7 @@ const DATASTORE_INFO_SUBDIRS: SubdirMap = &[
     ),
 ];
 
-const DATASTORE_INFO_ROUTER: Router = Router::new()    
+const DATASTORE_INFO_ROUTER: Router = Router::new()
     .get(&list_subdirs_api_method!(DATASTORE_INFO_SUBDIRS))
     .subdirs(DATASTORE_INFO_SUBDIRS);