5 use crate::api2
::types
::*;
6 use crate::api_schema
::*;
7 use crate::api_schema
::router
::*;
8 //use crate::server::rest::*;
9 use serde_json
::{json, Value}
;
10 use std
::collections
::{HashSet, HashMap}
;
11 use chrono
::{DateTime, Datelike, TimeZone, Local}
;
12 use std
::path
::PathBuf
;
14 use proxmox
::{sortable, identity}
;
15 use proxmox
::tools
::{try_block, fs::file_get_contents, fs::file_set_contents}
;
17 use crate::config
::datastore
;
20 use crate::server
::WorkerTask
;
22 use hyper
::{header, Body, Response, StatusCode}
;
23 use hyper
::http
::request
::Parts
;
25 fn read_backup_index(store
: &DataStore
, backup_dir
: &BackupDir
) -> Result
<Value
, Error
> {
27 let mut path
= store
.base_path();
28 path
.push(backup_dir
.relative_path());
29 path
.push("index.json.blob");
31 let raw_data
= file_get_contents(&path
)?
;
32 let data
= DataBlob
::from_raw(raw_data
)?
.decode(None
)?
;
33 let mut result
: Value
= serde_json
::from_reader(&mut &data
[..])?
;
35 let result
= result
["files"].take();
37 if result
== Value
::Null
{
38 bail
!("missing 'files' property in backup index {:?}", path
);
44 fn group_backups(backup_list
: Vec
<BackupInfo
>) -> HashMap
<String
, Vec
<BackupInfo
>> {
46 let mut group_hash
= HashMap
::new();
48 for info
in backup_list
{
49 let group_id
= info
.backup_dir
.group().group_path().to_str().unwrap().to_owned();
50 let time_list
= group_hash
.entry(group_id
).or_insert(vec
![]);
57 fn mark_selections
<F
: Fn(DateTime
<Local
>, &BackupInfo
) -> String
> (
58 mark
: &mut HashSet
<PathBuf
>,
59 list
: &Vec
<BackupInfo
>,
63 let mut hash
= HashSet
::new();
65 let local_time
= info
.backup_dir
.backup_time().with_timezone(&Local
);
66 if hash
.len() >= keep
as usize { break; }
67 let backup_id
= info
.backup_dir
.relative_path();
68 let sel_id
: String
= select_id(local_time
, &info
);
69 if !hash
.contains(&sel_id
) {
71 //println!(" KEEP ID {} {}", backup_id, local_time.format("%c"));
72 mark
.insert(backup_id
);
80 _rpcenv
: &mut dyn RpcEnvironment
,
81 ) -> Result
<Value
, Error
> {
83 let store
= param
["store"].as_str().unwrap();
85 let datastore
= DataStore
::lookup_datastore(store
)?
;
87 let backup_list
= BackupInfo
::list_backups(&datastore
.base_path())?
;
89 let group_hash
= group_backups(backup_list
);
91 let mut groups
= vec
![];
93 for (_group_id
, mut list
) in group_hash
{
95 BackupInfo
::sort_list(&mut list
, false);
98 let group
= info
.backup_dir
.group();
101 "backup-type": group
.backup_type(),
102 "backup-id": group
.backup_id(),
103 "last-backup": info
.backup_dir
.backup_time().timestamp(),
104 "backup-count": list
.len() as u64,
112 fn list_snapshot_files (
115 _rpcenv
: &mut dyn RpcEnvironment
,
116 ) -> Result
<Value
, Error
> {
118 let store
= tools
::required_string_param(¶m
, "store")?
;
119 let backup_type
= tools
::required_string_param(¶m
, "backup-type")?
;
120 let backup_id
= tools
::required_string_param(¶m
, "backup-id")?
;
121 let backup_time
= tools
::required_integer_param(¶m
, "backup-time")?
;
123 let datastore
= DataStore
::lookup_datastore(store
)?
;
124 let snapshot
= BackupDir
::new(backup_type
, backup_id
, backup_time
);
126 let mut files
= read_backup_index(&datastore
, &snapshot
)?
;
128 let info
= BackupInfo
::new(&datastore
.base_path(), snapshot
)?
;
130 let file_set
= files
.as_array().unwrap().iter().fold(HashSet
::new(), |mut acc
, item
| {
131 acc
.insert(item
["filename"].as_str().unwrap().to_owned());
135 for file
in info
.files
{
136 if file_set
.contains(&file
) { continue; }
137 files
.as_array_mut().unwrap().push(json
!({ "filename": file }
));
143 fn delete_snapshots (
146 _rpcenv
: &mut dyn RpcEnvironment
,
147 ) -> Result
<Value
, Error
> {
149 let store
= tools
::required_string_param(¶m
, "store")?
;
150 let backup_type
= tools
::required_string_param(¶m
, "backup-type")?
;
151 let backup_id
= tools
::required_string_param(¶m
, "backup-id")?
;
152 let backup_time
= tools
::required_integer_param(¶m
, "backup-time")?
;
154 let snapshot
= BackupDir
::new(backup_type
, backup_id
, backup_time
);
156 let datastore
= DataStore
::lookup_datastore(store
)?
;
158 datastore
.remove_backup_dir(&snapshot
)?
;
166 _rpcenv
: &mut dyn RpcEnvironment
,
167 ) -> Result
<Value
, Error
> {
169 let store
= tools
::required_string_param(¶m
, "store")?
;
170 let backup_type
= param
["backup-type"].as_str();
171 let backup_id
= param
["backup-id"].as_str();
173 let datastore
= DataStore
::lookup_datastore(store
)?
;
175 let base_path
= datastore
.base_path();
177 let backup_list
= BackupInfo
::list_backups(&base_path
)?
;
179 let mut snapshots
= vec
![];
181 for info
in backup_list
{
182 let group
= info
.backup_dir
.group();
183 if let Some(backup_type
) = backup_type
{
184 if backup_type
!= group
.backup_type() { continue; }
186 if let Some(backup_id
) = backup_id
{
187 if backup_id
!= group
.backup_id() { continue; }
190 let mut result_item
= json
!({
191 "backup-type": group
.backup_type(),
192 "backup-id": group
.backup_id(),
193 "backup-time": info
.backup_dir
.backup_time().timestamp(),
197 if let Ok(index
) = read_backup_index(&datastore
, &info
.backup_dir
) {
198 let mut backup_size
= 0;
199 for item
in index
.as_array().unwrap().iter() {
200 if let Some(item_size
) = item
["size"].as_u64() {
201 backup_size
+= item_size
;
204 result_item
["size"] = backup_size
.into();
207 snapshots
.push(result_item
);
216 _rpcenv
: &mut dyn RpcEnvironment
,
217 ) -> Result
<Value
, Error
> {
219 let store
= param
["store"].as_str().unwrap();
221 let datastore
= DataStore
::lookup_datastore(store
)?
;
223 let base_path
= datastore
.base_path();
225 let mut stat
: libc
::statfs64
= unsafe { std::mem::zeroed() }
;
229 let res
= base_path
.with_nix_path(|cstr
| unsafe { libc::statfs64(cstr.as_ptr(), &mut stat) }
)?
;
230 nix
::errno
::Errno
::result(res
)?
;
232 let bsize
= stat
.f_bsize
as u64;
234 "total": stat
.f_blocks
*bsize
,
235 "used": (stat
.f_blocks
-stat
.f_bfree
)*bsize
,
236 "avail": stat
.f_bavail
*bsize
,
241 macro_rules
! add_common_prune_prameters
{
242 ( [ $
( $list1
:tt
)* ] ) => {
243 add_common_prune_prameters
!([$
( $list1
)* ] , [])
245 ( [ $
( $list1
:tt
)* ] , [ $
( $list2
:tt
)* ] ) => {
251 &IntegerSchema
::new("Number of daily backups to keep.")
258 &IntegerSchema
::new("Number of backups to keep.")
265 &IntegerSchema
::new("Number of monthly backups to keep.")
272 &IntegerSchema
::new("Number of weekly backups to keep.")
279 &IntegerSchema
::new("Number of yearly backups to keep.")
288 const API_METHOD_STATUS
: ApiMethod
= ApiMethod
::new(
289 &ApiHandler
::Sync(&status
),
291 "Get datastore status.",
292 &add_common_prune_prameters
!([],[
293 ("store", false, &StringSchema
::new("Datastore name.").schema()),
302 _rpcenv
: &mut dyn RpcEnvironment
,
303 ) -> Result
<Value
, Error
> {
305 let store
= param
["store"].as_str().unwrap();
307 let backup_type
= tools
::required_string_param(¶m
, "backup-type")?
;
308 let backup_id
= tools
::required_string_param(¶m
, "backup-id")?
;
310 let group
= BackupGroup
::new(backup_type
, backup_id
);
312 let datastore
= DataStore
::lookup_datastore(store
)?
;
314 let mut keep_all
= true;
316 for opt
in &["keep-last", "keep-daily", "keep-weekly", "keep-weekly", "keep-yearly"] {
317 if !param
[opt
].is_null() {
323 let worker
= WorkerTask
::new("prune", Some(store
.to_owned()), "root@pam", true)?
;
324 let result
= try_block
! {
326 worker
.log("No prune selection - keeping all files.");
329 worker
.log(format
!("Starting prune on store {}", store
));
332 let mut list
= group
.list_backups(&datastore
.base_path())?
;
334 let mut mark
= HashSet
::new();
336 BackupInfo
::sort_list(&mut list
, false);
338 if let Some(keep_last
) = param
["keep-last"].as_u64() {
339 list
.iter().take(keep_last
as usize).for_each(|info
| {
340 mark
.insert(info
.backup_dir
.relative_path());
344 if let Some(keep_daily
) = param
["keep-daily"].as_u64() {
345 mark_selections(&mut mark
, &list
, keep_daily
as usize, |local_time
, _info
| {
346 format
!("{}/{}/{}", local_time
.year(), local_time
.month(), local_time
.day())
350 if let Some(keep_weekly
) = param
["keep-weekly"].as_u64() {
351 mark_selections(&mut mark
, &list
, keep_weekly
as usize, |local_time
, _info
| {
352 format
!("{}/{}", local_time
.year(), local_time
.iso_week().week())
356 if let Some(keep_monthly
) = param
["keep-monthly"].as_u64() {
357 mark_selections(&mut mark
, &list
, keep_monthly
as usize, |local_time
, _info
| {
358 format
!("{}/{}", local_time
.year(), local_time
.month())
362 if let Some(keep_yearly
) = param
["keep-yearly"].as_u64() {
363 mark_selections(&mut mark
, &list
, keep_yearly
as usize, |local_time
, _info
| {
364 format
!("{}/{}", local_time
.year(), local_time
.year())
368 let mut remove_list
: Vec
<BackupInfo
> = list
.into_iter()
369 .filter(|info
| !mark
.contains(&info
.backup_dir
.relative_path())).collect();
371 BackupInfo
::sort_list(&mut remove_list
, true);
373 for info
in remove_list
{
374 worker
.log(format
!("remove {:?}", info
.backup_dir
));
375 datastore
.remove_backup_dir(&info
.backup_dir
)?
;
381 worker
.log_result(&result
);
383 if let Err(err
) = result
{
384 bail
!("prune failed - {}", err
);
390 const API_METHOD_PRUNE
: ApiMethod
= ApiMethod
::new(
391 &ApiHandler
::Sync(&prune
),
393 "Prune the datastore.",
394 &add_common_prune_prameters
!([
395 ("backup-id", false, &BACKUP_ID_SCHEMA
),
396 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
398 ("store", false, &StringSchema
::new("Datastore name.").schema()),
403 fn start_garbage_collection(
406 rpcenv
: &mut dyn RpcEnvironment
,
407 ) -> Result
<Value
, Error
> {
409 let store
= param
["store"].as_str().unwrap().to_string();
411 let datastore
= DataStore
::lookup_datastore(&store
)?
;
413 println
!("Starting garbage collection on store {}", store
);
415 let to_stdout
= if rpcenv
.env_type() == RpcEnvironmentType
::CLI { true }
else { false }
;
417 let upid_str
= WorkerTask
::new_thread(
418 "garbage_collection", Some(store
.clone()), "root@pam", to_stdout
, move |worker
|
420 worker
.log(format
!("starting garbage collection on store {}", store
));
421 datastore
.garbage_collection(worker
)
428 pub const API_METHOD_START_GARBAGE_COLLECTION
: ApiMethod
= ApiMethod
::new(
429 &ApiHandler
::Sync(&start_garbage_collection
),
431 "Start garbage collection.",
433 ("store", false, &StringSchema
::new("Datastore name.").schema()),
438 fn garbage_collection_status(
441 _rpcenv
: &mut dyn RpcEnvironment
,
442 ) -> Result
<Value
, Error
> {
444 let store
= param
["store"].as_str().unwrap();
446 let datastore
= DataStore
::lookup_datastore(&store
)?
;
448 println
!("Garbage collection status on store {}", store
);
450 let status
= datastore
.last_gc_status();
452 Ok(serde_json
::to_value(&status
)?
)
456 pub const API_METHOD_GARBAGE_COLLECTION_STATUS
: ApiMethod
= ApiMethod
::new(
457 &ApiHandler
::Sync(&garbage_collection_status
),
459 "Garbage collection status.",
461 ("store", false, &StringSchema
::new("Datastore name.").schema()),
466 fn get_datastore_list(
469 _rpcenv
: &mut dyn RpcEnvironment
,
470 ) -> Result
<Value
, Error
> {
472 let config
= datastore
::config()?
;
474 Ok(config
.convert_to_array("store"))
483 _rpcenv
: Box
<dyn RpcEnvironment
>,
484 ) -> Result
<BoxFut
, Error
> {
486 let store
= tools
::required_string_param(¶m
, "store")?
;
488 let datastore
= DataStore
::lookup_datastore(store
)?
;
490 let file_name
= tools
::required_string_param(¶m
, "file-name")?
.to_owned();
492 let backup_type
= tools
::required_string_param(¶m
, "backup-type")?
;
493 let backup_id
= tools
::required_string_param(¶m
, "backup-id")?
;
494 let backup_time
= tools
::required_integer_param(¶m
, "backup-time")?
;
496 println
!("Download {} from {} ({}/{}/{}/{})", file_name
, store
,
497 backup_type
, backup_id
, Local
.timestamp(backup_time
, 0), file_name
);
499 let backup_dir
= BackupDir
::new(backup_type
, backup_id
, backup_time
);
501 let mut path
= datastore
.base_path();
502 path
.push(backup_dir
.relative_path());
503 path
.push(&file_name
);
505 let response_future
= tokio
::fs
::File
::open(path
)
506 .map_err(|err
| http_err
!(BAD_REQUEST
, format
!("File open failed: {}", err
)))
507 .and_then(move |file
| {
508 let payload
= tokio
::codec
::FramedRead
::new(file
, tokio
::codec
::BytesCodec
::new())
509 .map_ok(|bytes
| hyper
::Chunk
::from(bytes
.freeze()));
510 let body
= Body
::wrap_stream(payload
);
512 // fixme: set other headers ?
513 futures
::future
::ok(Response
::builder()
514 .status(StatusCode
::OK
)
515 .header(header
::CONTENT_TYPE
, "application/octet-stream")
520 Ok(Box
::new(response_future
))
524 pub const API_METHOD_DOWNLOAD_FILE
: ApiMethod
= ApiMethod
::new(
525 &ApiHandler
::Async(&download_file
),
527 "Download single raw file from backup snapshot.",
529 ("store", false, &StringSchema
::new("Datastore name.").schema()),
530 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
531 ("backup-id", false, &BACKUP_ID_SCHEMA
),
532 ("backup-time", false, &BACKUP_TIME_SCHEMA
),
533 ("file-name", false, &StringSchema
::new("Raw file name.")
534 .format(&FILENAME_FORMAT
)
541 fn upload_backup_log(
546 _rpcenv
: Box
<dyn RpcEnvironment
>,
547 ) -> Result
<BoxFut
, Error
> {
549 let store
= tools
::required_string_param(¶m
, "store")?
;
551 let datastore
= DataStore
::lookup_datastore(store
)?
;
553 let file_name
= "client.log.blob";
555 let backup_type
= tools
::required_string_param(¶m
, "backup-type")?
;
556 let backup_id
= tools
::required_string_param(¶m
, "backup-id")?
;
557 let backup_time
= tools
::required_integer_param(¶m
, "backup-time")?
;
559 let backup_dir
= BackupDir
::new(backup_type
, backup_id
, backup_time
);
561 let mut path
= datastore
.base_path();
562 path
.push(backup_dir
.relative_path());
563 path
.push(&file_name
);
566 bail
!("backup already contains a log.");
569 println
!("Upload backup log to {}/{}/{}/{}/{}", store
,
570 backup_type
, backup_id
, BackupDir
::backup_time_to_string(backup_dir
.backup_time()), file_name
);
573 .map_err(Error
::from
)
574 .try_fold(Vec
::new(), |mut acc
, chunk
| {
575 acc
.extend_from_slice(&*chunk
);
576 future
::ok
::<_
, Error
>(acc
)
578 .and_then(move |data
| async
move {
579 let blob
= DataBlob
::from_raw(data
)?
;
580 // always verify CRC at server side
582 let raw_data
= blob
.raw_data();
583 file_set_contents(&path
, raw_data
, None
)?
;
587 future
::ok(crate::server
::formatter
::json_response(Ok(Value
::Null
)))
595 pub const API_METHOD_UPLOAD_BACKUP_LOG
: ApiMethod
= ApiMethod
::new(
596 &ApiHandler
::Async(&upload_backup_log
),
598 "Download single raw file from backup snapshot.",
600 ("store", false, &StringSchema
::new("Datastore name.").schema()),
601 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
602 ("backup-id", false, &BACKUP_ID_SCHEMA
),
603 ("backup-time", false, &BACKUP_TIME_SCHEMA
),
608 const STORE_SCHEMA
: Schema
= StringSchema
::new("Datastore name.").schema();
611 const DATASTORE_INFO_SUBDIRS
: SubdirMap
= &[
615 .download(&API_METHOD_DOWNLOAD_FILE
)
622 &ApiHandler
::Sync(&list_snapshot_files
),
624 "List snapshot files.",
626 ("store", false, &STORE_SCHEMA
),
627 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
628 ("backup-id", false, &BACKUP_ID_SCHEMA
),
629 ("backup-time", false, &BACKUP_TIME_SCHEMA
),
638 .get(&API_METHOD_GARBAGE_COLLECTION_STATUS
)
639 .post(&API_METHOD_START_GARBAGE_COLLECTION
)
646 &ApiHandler
::Sync(&list_groups
),
648 "List backup groups.",
649 &sorted
!([ ("store", false, &STORE_SCHEMA
) ]),
657 .post(&API_METHOD_PRUNE
)
664 &ApiHandler
::Sync(&list_snapshots
),
666 "List backup groups.",
668 ("store", false, &STORE_SCHEMA
),
669 ("backup-type", true, &BACKUP_TYPE_SCHEMA
),
670 ("backup-id", true, &BACKUP_ID_SCHEMA
),
677 &ApiHandler
::Sync(&delete_snapshots
),
679 "Delete backup snapshot.",
681 ("store", false, &STORE_SCHEMA
),
682 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
683 ("backup-id", false, &BACKUP_ID_SCHEMA
),
684 ("backup-time", false, &BACKUP_TIME_SCHEMA
),
693 .get(&API_METHOD_STATUS
)
698 .upload(&API_METHOD_UPLOAD_BACKUP_LOG
)
702 const DATASTORE_INFO_ROUTER
: Router
= Router
::new()
703 .get(&list_subdirs_api_method
!(DATASTORE_INFO_SUBDIRS
))
704 .subdirs(DATASTORE_INFO_SUBDIRS
);
707 pub const ROUTER
: Router
= Router
::new()
710 &ApiHandler
::Sync(&get_datastore_list
),
711 &ObjectSchema
::new("Directory index.", &[])
714 .match_all("store", &DATASTORE_INFO_ROUTER
);