1 //! Datastore Management
3 use std
::collections
::HashSet
;
5 use std
::os
::unix
::ffi
::OsStrExt
;
6 use std
::path
::PathBuf
;
9 use anyhow
::{bail, format_err, Error}
;
11 use hyper
::http
::request
::Parts
;
12 use hyper
::{header, Body, Response, StatusCode}
;
13 use serde
::Deserialize
;
14 use serde_json
::{json, Value}
;
15 use tokio_stream
::wrappers
::ReceiverStream
;
17 use proxmox_async
::blocking
::WrappedReaderStream
;
18 use proxmox_async
::{io::AsyncChannelWriter, stream::AsyncReaderStream}
;
19 use proxmox_compression
::zstd
::ZstdEncoder
;
21 http_err
, list_subdirs_api_method
, ApiHandler
, ApiMethod
, ApiResponseFuture
, Permission
,
22 Router
, RpcEnvironment
, RpcEnvironmentType
, SubdirMap
,
24 use proxmox_schema
::*;
25 use proxmox_sortable_macro
::sortable
;
26 use proxmox_sys
::fs
::{
27 file_read_firstline
, file_read_optional_string
, replace_file
, CreateOptions
,
29 use proxmox_sys
::{task_log, task_warn}
;
30 use proxmox_time
::CalendarEvent
;
32 use pxar
::accessor
::aio
::Accessor
;
36 print_ns_and_snapshot
, print_store_and_ns
, Authid
, BackupContent
, BackupNamespace
, BackupType
,
37 Counts
, CryptMode
, DataStoreConfig
, DataStoreListItem
, DataStoreStatus
,
38 GarbageCollectionJobStatus
, GroupListItem
, JobScheduleStatus
, KeepOptions
, Operation
,
39 PruneJobOptions
, RRDMode
, RRDTimeFrame
, SnapshotListItem
, SnapshotVerifyState
,
40 BACKUP_ARCHIVE_NAME_SCHEMA
, BACKUP_ID_SCHEMA
, BACKUP_NAMESPACE_SCHEMA
, BACKUP_TIME_SCHEMA
,
41 BACKUP_TYPE_SCHEMA
, DATASTORE_SCHEMA
, IGNORE_VERIFIED_BACKUPS_SCHEMA
, MAX_NAMESPACE_DEPTH
,
42 NS_MAX_DEPTH_SCHEMA
, PRIV_DATASTORE_AUDIT
, PRIV_DATASTORE_BACKUP
, PRIV_DATASTORE_MODIFY
,
43 PRIV_DATASTORE_PRUNE
, PRIV_DATASTORE_READ
, PRIV_DATASTORE_VERIFY
, UPID
, UPID_SCHEMA
,
44 VERIFICATION_OUTDATED_AFTER_SCHEMA
,
46 use pbs_client
::pxar
::{create_tar, create_zip}
;
47 use pbs_config
::CachedUserInfo
;
48 use pbs_datastore
::backup_info
::BackupInfo
;
49 use pbs_datastore
::cached_chunk_reader
::CachedChunkReader
;
50 use pbs_datastore
::catalog
::{ArchiveEntry, CatalogReader}
;
51 use pbs_datastore
::data_blob
::DataBlob
;
52 use pbs_datastore
::data_blob_reader
::DataBlobReader
;
53 use pbs_datastore
::dynamic_index
::{BufferedDynamicReader, DynamicIndexReader, LocalDynamicReadAt}
;
54 use pbs_datastore
::fixed_index
::FixedIndexReader
;
55 use pbs_datastore
::index
::IndexFile
;
56 use pbs_datastore
::manifest
::{BackupManifest, CLIENT_LOG_BLOB_NAME, MANIFEST_BLOB_NAME}
;
57 use pbs_datastore
::prune
::compute_prune_info
;
59 check_backup_owner
, task_tracking
, BackupDir
, BackupGroup
, DataStore
, LocalChunkReader
,
60 StoreProgress
, CATALOG_NAME
,
62 use pbs_tools
::json
::required_string_param
;
63 use proxmox_rest_server
::{formatter, WorkerTask}
;
65 use crate::api2
::backup
::optional_ns_param
;
66 use crate::api2
::node
::rrd
::create_value_from_rrd
;
68 check_ns_privs_full
, verify_all_backups
, verify_backup_dir
, verify_backup_group
, verify_filter
,
69 ListAccessibleBackupGroups
, NS_PRIVS_OK
,
72 use crate::server
::jobstate
::{compute_schedule_status, Job, JobState}
;
74 const GROUP_NOTES_FILE_NAME
: &str = "notes";
76 fn get_group_note_path(
79 group
: &pbs_api_types
::BackupGroup
,
81 let mut note_path
= store
.group_path(ns
, group
);
82 note_path
.push(GROUP_NOTES_FILE_NAME
);
86 // helper to unify common sequence of checks:
87 // 1. check privs on NS (full or limited access)
89 // 3. if needed (only limited access), check owner of group
90 fn check_privs_and_load_store(
94 full_access_privs
: u64,
95 partial_access_privs
: u64,
96 operation
: Option
<Operation
>,
97 backup_group
: &pbs_api_types
::BackupGroup
,
98 ) -> Result
<Arc
<DataStore
>, Error
> {
99 let limited
= check_ns_privs_full(store
, ns
, auth_id
, full_access_privs
, partial_access_privs
)?
;
101 let datastore
= DataStore
::lookup_datastore(store
, operation
)?
;
104 let owner
= datastore
.get_owner(ns
, backup_group
)?
;
105 check_backup_owner(&owner
, auth_id
)?
;
111 fn read_backup_index(
112 backup_dir
: &BackupDir
,
113 ) -> Result
<(BackupManifest
, Vec
<BackupContent
>), Error
> {
114 let (manifest
, index_size
) = backup_dir
.load_manifest()?
;
116 let mut result
= Vec
::new();
117 for item
in manifest
.files() {
118 result
.push(BackupContent
{
119 filename
: item
.filename
.clone(),
120 crypt_mode
: Some(item
.crypt_mode
),
121 size
: Some(item
.size
),
125 result
.push(BackupContent
{
126 filename
: MANIFEST_BLOB_NAME
.to_string(),
127 crypt_mode
: match manifest
.signature
{
128 Some(_
) => Some(CryptMode
::SignOnly
),
129 None
=> Some(CryptMode
::None
),
131 size
: Some(index_size
),
134 Ok((manifest
, result
))
137 fn get_all_snapshot_files(
139 ) -> Result
<(BackupManifest
, Vec
<BackupContent
>), Error
> {
140 let (manifest
, mut files
) = read_backup_index(&info
.backup_dir
)?
;
142 let file_set
= files
.iter().fold(HashSet
::new(), |mut acc
, item
| {
143 acc
.insert(item
.filename
.clone());
147 for file
in &info
.files
{
148 if file_set
.contains(file
) {
151 files
.push(BackupContent
{
152 filename
: file
.to_string(),
158 Ok((manifest
, files
))
165 schema
: DATASTORE_SCHEMA
,
168 type: BackupNamespace
,
173 returns
: pbs_api_types
::ADMIN_DATASTORE_LIST_GROUPS_RETURN_TYPE
,
175 permission
: &Permission
::Anybody
,
176 description
: "Requires DATASTORE_AUDIT for all or DATASTORE_BACKUP for owned groups on \
177 /datastore/{store}[/{namespace}]",
180 /// List backup groups.
183 ns
: Option
<BackupNamespace
>,
184 rpcenv
: &mut dyn RpcEnvironment
,
185 ) -> Result
<Vec
<GroupListItem
>, Error
> {
186 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
187 let ns
= ns
.unwrap_or_default();
189 let list_all
= !check_ns_privs_full(
193 PRIV_DATASTORE_AUDIT
,
194 PRIV_DATASTORE_BACKUP
,
197 let datastore
= DataStore
::lookup_datastore(&store
, Some(Operation
::Read
))?
;
200 .iter_backup_groups(ns
.clone())?
// FIXME: Namespaces and recursion parameters!
201 .try_fold(Vec
::new(), |mut group_info
, group
| {
204 let owner
= match datastore
.get_owner(&ns
, group
.as_ref()) {
205 Ok(auth_id
) => auth_id
,
208 "Failed to get owner of group '{}' in {} - {}",
210 print_store_and_ns(&store
, &ns
),
213 return Ok(group_info
);
216 if !list_all
&& check_backup_owner(&owner
, &auth_id
).is_err() {
217 return Ok(group_info
);
220 let snapshots
= match group
.list_backups() {
221 Ok(snapshots
) => snapshots
,
222 Err(_
) => return Ok(group_info
),
225 let backup_count
: u64 = snapshots
.len() as u64;
226 if backup_count
== 0 {
227 return Ok(group_info
);
230 let last_backup
= snapshots
232 .fold(&snapshots
[0], |a
, b
| {
233 if a
.is_finished() && a
.backup_dir
.backup_time() > b
.backup_dir
.backup_time() {
241 let note_path
= get_group_note_path(&datastore
, &ns
, group
.as_ref());
242 let comment
= file_read_firstline(note_path
).ok();
244 group_info
.push(GroupListItem
{
245 backup
: group
.into(),
246 last_backup
: last_backup
.backup_dir
.backup_time(),
249 files
: last_backup
.files
,
260 store
: { schema: DATASTORE_SCHEMA }
,
262 type: BackupNamespace
,
266 type: pbs_api_types
::BackupGroup
,
272 permission
: &Permission
::Anybody
,
273 description
: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any\
274 or DATASTORE_PRUNE and being the owner of the group",
277 /// Delete backup group including all snapshots.
278 pub async
fn delete_group(
280 ns
: Option
<BackupNamespace
>,
281 group
: pbs_api_types
::BackupGroup
,
282 rpcenv
: &mut dyn RpcEnvironment
,
283 ) -> Result
<Value
, Error
> {
284 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
286 tokio
::task
::spawn_blocking(move || {
287 let ns
= ns
.unwrap_or_default();
289 let datastore
= check_privs_and_load_store(
293 PRIV_DATASTORE_MODIFY
,
294 PRIV_DATASTORE_PRUNE
,
295 Some(Operation
::Write
),
299 let delete_stats
= datastore
.remove_backup_group(&ns
, &group
)?
;
300 if !delete_stats
.all_removed() {
301 bail
!("group only partially deleted due to protected snapshots");
312 store
: { schema: DATASTORE_SCHEMA }
,
314 type: BackupNamespace
,
318 type: pbs_api_types
::BackupDir
,
323 returns
: pbs_api_types
::ADMIN_DATASTORE_LIST_SNAPSHOT_FILES_RETURN_TYPE
,
325 permission
: &Permission
::Anybody
,
326 description
: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_AUDIT or \
327 DATASTORE_READ for any or DATASTORE_BACKUP and being the owner of the group",
330 /// List snapshot files.
331 pub async
fn list_snapshot_files(
333 ns
: Option
<BackupNamespace
>,
334 backup_dir
: pbs_api_types
::BackupDir
,
336 rpcenv
: &mut dyn RpcEnvironment
,
337 ) -> Result
<Vec
<BackupContent
>, Error
> {
338 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
340 tokio
::task
::spawn_blocking(move || {
341 let ns
= ns
.unwrap_or_default();
343 let datastore
= check_privs_and_load_store(
347 PRIV_DATASTORE_AUDIT
| PRIV_DATASTORE_READ
,
348 PRIV_DATASTORE_BACKUP
,
349 Some(Operation
::Read
),
353 let snapshot
= datastore
.backup_dir(ns
, backup_dir
)?
;
355 let info
= BackupInfo
::new(snapshot
)?
;
357 let (_manifest
, files
) = get_all_snapshot_files(&info
)?
;
367 store
: { schema: DATASTORE_SCHEMA }
,
369 type: BackupNamespace
,
373 type: pbs_api_types
::BackupDir
,
379 permission
: &Permission
::Anybody
,
380 description
: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any\
381 or DATASTORE_PRUNE and being the owner of the group",
384 /// Delete backup snapshot.
385 pub async
fn delete_snapshot(
387 ns
: Option
<BackupNamespace
>,
388 backup_dir
: pbs_api_types
::BackupDir
,
390 rpcenv
: &mut dyn RpcEnvironment
,
391 ) -> Result
<Value
, Error
> {
392 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
394 tokio
::task
::spawn_blocking(move || {
395 let ns
= ns
.unwrap_or_default();
397 let datastore
= check_privs_and_load_store(
401 PRIV_DATASTORE_MODIFY
,
402 PRIV_DATASTORE_PRUNE
,
403 Some(Operation
::Write
),
407 let snapshot
= datastore
.backup_dir(ns
, backup_dir
)?
;
409 snapshot
.destroy(false)?
;
420 store
: { schema: DATASTORE_SCHEMA }
,
422 type: BackupNamespace
,
431 schema
: BACKUP_ID_SCHEMA
,
435 returns
: pbs_api_types
::ADMIN_DATASTORE_LIST_SNAPSHOTS_RETURN_TYPE
,
437 permission
: &Permission
::Anybody
,
438 description
: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_AUDIT for any \
439 or DATASTORE_BACKUP and being the owner of the group",
442 /// List backup snapshots.
443 pub async
fn list_snapshots(
445 ns
: Option
<BackupNamespace
>,
446 backup_type
: Option
<BackupType
>,
447 backup_id
: Option
<String
>,
450 rpcenv
: &mut dyn RpcEnvironment
,
451 ) -> Result
<Vec
<SnapshotListItem
>, Error
> {
452 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
454 tokio
::task
::spawn_blocking(move || unsafe {
455 list_snapshots_blocking(store
, ns
, backup_type
, backup_id
, auth_id
)
458 .map_err(|err
| format_err
!("failed to await blocking task: {err}"))?
461 /// This must not run in a main worker thread as it potentially does tons of I/O.
462 unsafe fn list_snapshots_blocking(
464 ns
: Option
<BackupNamespace
>,
465 backup_type
: Option
<BackupType
>,
466 backup_id
: Option
<String
>,
468 ) -> Result
<Vec
<SnapshotListItem
>, Error
> {
469 let ns
= ns
.unwrap_or_default();
471 let list_all
= !check_ns_privs_full(
475 PRIV_DATASTORE_AUDIT
,
476 PRIV_DATASTORE_BACKUP
,
479 let datastore
= DataStore
::lookup_datastore(&store
, Some(Operation
::Read
))?
;
481 // FIXME: filter also owner before collecting, for doing that nicely the owner should move into
482 // backup group and provide an error free (Err -> None) accessor
483 let groups
= match (backup_type
, backup_id
) {
484 (Some(backup_type
), Some(backup_id
)) => {
485 vec
![datastore
.backup_group_from_parts(ns
.clone(), backup_type
, backup_id
)]
488 (Some(backup_type
), None
) => datastore
489 .iter_backup_type_ok(ns
.clone(), backup_type
)?
492 (None
, Some(backup_id
)) => BackupType
::iter()
493 .filter_map(|backup_type
| {
495 datastore
.backup_group_from_parts(ns
.clone(), backup_type
, backup_id
.clone());
496 group
.exists().then_some(group
)
500 (None
, None
) => datastore
.list_backup_groups(ns
.clone())?
,
503 let info_to_snapshot_list_item
= |group
: &BackupGroup
, owner
, info
: BackupInfo
| {
504 let backup
= pbs_api_types
::BackupDir
{
506 time
: info
.backup_dir
.backup_time(),
508 let protected
= info
.backup_dir
.is_protected();
510 match get_all_snapshot_files(&info
) {
511 Ok((manifest
, files
)) => {
512 // extract the first line from notes
513 let comment
: Option
<String
> = manifest
.unprotected
["notes"]
515 .and_then(|notes
| notes
.lines().next())
518 let fingerprint
= match manifest
.fingerprint() {
521 eprintln
!("error parsing fingerprint: '{}'", err
);
526 let verification
= manifest
.unprotected
["verify_state"].clone();
527 let verification
: Option
<SnapshotVerifyState
> =
528 match serde_json
::from_value(verification
) {
529 Ok(verify
) => verify
,
531 eprintln
!("error parsing verification state : '{}'", err
);
536 let size
= Some(files
.iter().map(|x
| x
.size
.unwrap_or(0)).sum());
550 eprintln
!("error during snapshot file listing: '{}'", err
);
554 .map(|filename
| BackupContent
{
575 groups
.iter().try_fold(Vec
::new(), |mut snapshots
, group
| {
576 let owner
= match group
.get_owner() {
577 Ok(auth_id
) => auth_id
,
580 "Failed to get owner of group '{}' in {} - {}",
582 print_store_and_ns(&store
, &ns
),
585 return Ok(snapshots
);
589 if !list_all
&& check_backup_owner(&owner
, &auth_id
).is_err() {
590 return Ok(snapshots
);
593 let group_backups
= group
.list_backups()?
;
598 .map(|info
| info_to_snapshot_list_item(group
, Some(owner
.clone()), info
)),
605 async
fn get_snapshots_count(
606 store
: &Arc
<DataStore
>,
607 owner
: Option
<&Authid
>,
608 ) -> Result
<Counts
, Error
> {
609 let store
= Arc
::clone(store
);
610 let owner
= owner
.cloned();
611 tokio
::task
::spawn_blocking(move || {
612 let root_ns
= Default
::default();
613 ListAccessibleBackupGroups
::new_with_privs(
617 Some(PRIV_DATASTORE_AUDIT
| PRIV_DATASTORE_READ
),
621 .try_fold(Counts
::default(), |mut counts
, group
| {
622 let group
= match group
{
624 Err(_
) => return Ok(counts
), // TODO: add this as error counts?
626 let snapshot_count
= group
.list_backups()?
.len() as u64;
628 // only include groups with snapshots, counting/displaying empty groups can confuse
629 if snapshot_count
> 0 {
630 let type_count
= match group
.backup_type() {
631 BackupType
::Ct
=> counts
.ct
.get_or_insert(Default
::default()),
632 BackupType
::Vm
=> counts
.vm
.get_or_insert(Default
::default()),
633 BackupType
::Host
=> counts
.host
.get_or_insert(Default
::default()),
636 type_count
.groups
+= 1;
637 type_count
.snapshots
+= snapshot_count
;
650 schema
: DATASTORE_SCHEMA
,
656 description
: "Include additional information like snapshot counts and GC status.",
662 type: DataStoreStatus
,
665 permission
: &Permission
::Anybody
,
666 description
: "Requires on /datastore/{store} either DATASTORE_AUDIT or DATASTORE_BACKUP for \
667 the full statistics. Counts of accessible groups are always returned, if any",
670 /// Get datastore status.
675 rpcenv
: &mut dyn RpcEnvironment
,
676 ) -> Result
<DataStoreStatus
, Error
> {
677 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
678 let user_info
= CachedUserInfo
::new()?
;
679 let store_privs
= user_info
.lookup_privs(&auth_id
, &["datastore", &store
]);
681 let datastore
= DataStore
::lookup_datastore(&store
, Some(Operation
::Read
));
683 let store_stats
= if store_privs
& (PRIV_DATASTORE_AUDIT
| PRIV_DATASTORE_BACKUP
) != 0 {
685 } else if store_privs
& PRIV_DATASTORE_READ
!= 0 {
686 false // allow at least counts, user can read groups anyway..
688 match user_info
.any_privs_below(&auth_id
, &["datastore", &store
], NS_PRIVS_OK
) {
689 // avoid leaking existence info if users hasn't at least any priv. below
690 Ok(false) | Err(_
) => return Err(http_err
!(FORBIDDEN
, "permission check failed")),
694 let datastore
= datastore?
; // only unwrap no to avoid leaking existence info
696 let (counts
, gc_status
) = if verbose
{
697 let filter_owner
= if store_privs
& PRIV_DATASTORE_AUDIT
!= 0 {
703 let counts
= Some(get_snapshots_count(&datastore
, filter_owner
).await?
);
704 let gc_status
= if store_stats
{
705 Some(datastore
.last_gc_status())
716 let storage
= crate::tools
::fs
::fs_info(datastore
.base_path()).await?
;
718 total
: storage
.total
,
720 avail
: storage
.available
,
739 schema
: DATASTORE_SCHEMA
,
742 type: BackupNamespace
,
750 schema
: BACKUP_ID_SCHEMA
,
754 schema
: IGNORE_VERIFIED_BACKUPS_SCHEMA
,
758 schema
: VERIFICATION_OUTDATED_AFTER_SCHEMA
,
762 schema
: BACKUP_TIME_SCHEMA
,
766 schema
: NS_MAX_DEPTH_SCHEMA
,
775 permission
: &Permission
::Anybody
,
776 description
: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_VERIFY for any \
777 or DATASTORE_BACKUP and being the owner of the group",
782 /// This function can verify a single backup snapshot, all backup from a backup group,
783 /// or all backups in the datastore.
784 #[allow(clippy::too_many_arguments)]
787 ns
: Option
<BackupNamespace
>,
788 backup_type
: Option
<BackupType
>,
789 backup_id
: Option
<String
>,
790 backup_time
: Option
<i64>,
791 ignore_verified
: Option
<bool
>,
792 outdated_after
: Option
<i64>,
793 max_depth
: Option
<usize>,
794 rpcenv
: &mut dyn RpcEnvironment
,
795 ) -> Result
<Value
, Error
> {
796 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
797 let ns
= ns
.unwrap_or_default();
799 let owner_check_required
= check_ns_privs_full(
803 PRIV_DATASTORE_VERIFY
,
804 PRIV_DATASTORE_BACKUP
,
807 let datastore
= DataStore
::lookup_datastore(&store
, Some(Operation
::Read
))?
;
808 let ignore_verified
= ignore_verified
.unwrap_or(true);
812 let mut backup_dir
= None
;
813 let mut backup_group
= None
;
814 let mut worker_type
= "verify";
816 match (backup_type
, backup_id
, backup_time
) {
817 (Some(backup_type
), Some(backup_id
), Some(backup_time
)) => {
819 "{}:{}/{}/{}/{:08X}",
821 ns
.display_as_path(),
827 datastore
.backup_dir_from_parts(ns
.clone(), backup_type
, backup_id
, backup_time
)?
;
829 if owner_check_required
{
830 let owner
= datastore
.get_owner(dir
.backup_ns(), dir
.as_ref())?
;
831 check_backup_owner(&owner
, &auth_id
)?
;
834 backup_dir
= Some(dir
);
835 worker_type
= "verify_snapshot";
837 (Some(backup_type
), Some(backup_id
), None
) => {
841 ns
.display_as_path(),
845 let group
= pbs_api_types
::BackupGroup
::from((backup_type
, backup_id
));
847 if owner_check_required
{
848 let owner
= datastore
.get_owner(&ns
, &group
)?
;
849 check_backup_owner(&owner
, &auth_id
)?
;
852 backup_group
= Some(datastore
.backup_group(ns
.clone(), group
));
853 worker_type
= "verify_group";
855 (None
, None
, None
) => {
856 worker_id
= if ns
.is_root() {
859 format
!("{}:{}", store
, ns
.display_as_path())
862 _
=> bail
!("parameters do not specify a backup group or snapshot"),
865 let to_stdout
= rpcenv
.env_type() == RpcEnvironmentType
::CLI
;
867 let upid_str
= WorkerTask
::new_thread(
873 let verify_worker
= crate::backup
::VerifyWorker
::new(worker
.clone(), datastore
);
874 let failed_dirs
= if let Some(backup_dir
) = backup_dir
{
875 let mut res
= Vec
::new();
876 if !verify_backup_dir(
879 worker
.upid().clone(),
880 Some(&move |manifest
| verify_filter(ignore_verified
, outdated_after
, manifest
)),
882 res
.push(print_ns_and_snapshot(
883 backup_dir
.backup_ns(),
888 } else if let Some(backup_group
) = backup_group
{
892 &mut StoreProgress
::new(1),
894 Some(&move |manifest
| verify_filter(ignore_verified
, outdated_after
, manifest
)),
897 let owner
= if owner_check_required
{
909 Some(&move |manifest
| verify_filter(ignore_verified
, outdated_after
, manifest
)),
912 if !failed_dirs
.is_empty() {
913 task_log
!(worker
, "Failed to verify the following snapshots/groups:");
914 for dir
in failed_dirs
{
915 task_log
!(worker
, "\t{}", dir
);
917 bail
!("verification failed - please check the log for details");
930 type: pbs_api_types
::BackupGroup
,
937 description
: "Just show what prune would do, but do not delete anything.",
944 schema
: DATASTORE_SCHEMA
,
947 type: BackupNamespace
,
954 description
: "Spins up an asynchronous task that does the work.",
958 returns
: pbs_api_types
::ADMIN_DATASTORE_PRUNE_RETURN_TYPE
,
960 permission
: &Permission
::Anybody
,
961 description
: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any\
962 or DATASTORE_PRUNE and being the owner of the group",
965 /// Prune a group on the datastore
967 group
: pbs_api_types
::BackupGroup
,
969 keep_options
: KeepOptions
,
971 ns
: Option
<BackupNamespace
>,
973 rpcenv
: &mut dyn RpcEnvironment
,
974 ) -> Result
<Value
, Error
> {
975 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
976 let ns
= ns
.unwrap_or_default();
977 let datastore
= check_privs_and_load_store(
981 PRIV_DATASTORE_MODIFY
,
982 PRIV_DATASTORE_PRUNE
,
983 Some(Operation
::Write
),
987 let worker_id
= format
!("{}:{}:{}", store
, ns
, group
);
988 let group
= datastore
.backup_group(ns
.clone(), group
);
990 #[derive(Debug, serde::Serialize)]
992 #[serde(rename = "backup-type")]
993 backup_type
: BackupType
,
994 #[serde(rename = "backup-id")]
996 #[serde(rename = "backup-time")]
1000 #[serde(skip_serializing_if = "Option::is_none")]
1001 ns
: Option
<BackupNamespace
>,
1003 let mut prune_result
: Vec
<PruneResult
> = Vec
::new();
1005 let list
= group
.list_backups()?
;
1007 let mut prune_info
= compute_prune_info(list
, &keep_options
)?
;
1009 prune_info
.reverse(); // delete older snapshots first
1011 let keep_all
= !keep_options
.keeps_something();
1014 for (info
, mark
) in prune_info
{
1015 let keep
= keep_all
|| mark
.keep();
1016 let backup_dir
= &info
.backup_dir
;
1018 let mut result
= PruneResult
{
1019 backup_type
: backup_dir
.backup_type(),
1020 backup_id
: backup_dir
.backup_id().to_owned(),
1021 backup_time
: backup_dir
.backup_time(),
1023 protected
: mark
.protected(),
1026 let prune_ns
= backup_dir
.backup_ns();
1027 if !prune_ns
.is_root() {
1028 result
.ns
= Some(prune_ns
.to_owned());
1030 prune_result
.push(result
);
1032 return Ok(json
!(prune_result
));
1035 let prune_group
= move |worker
: Arc
<WorkerTask
>| {
1037 task_log
!(worker
, "No prune selection - keeping all files.");
1039 let mut opts
= Vec
::new();
1041 opts
.push(format
!("--ns {ns}"));
1043 crate::server
::cli_keep_options(&mut opts
, &keep_options
);
1045 task_log
!(worker
, "retention options: {}", opts
.join(" "));
1048 "Starting prune on {} group \"{}\"",
1049 print_store_and_ns(&store
, &ns
),
1054 for (info
, mark
) in prune_info
{
1055 let keep
= keep_all
|| mark
.keep();
1056 let backup_dir
= &info
.backup_dir
;
1058 let backup_time
= backup_dir
.backup_time();
1059 let timestamp
= backup_dir
.backup_time_string();
1060 let group
: &pbs_api_types
::BackupGroup
= backup_dir
.as_ref();
1062 let msg
= format
!("{}/{}/{timestamp} {mark}", group
.ty
, group
.id
);
1064 task_log
!(worker
, "{msg}");
1066 prune_result
.push(PruneResult
{
1067 backup_type
: group
.ty
,
1068 backup_id
: group
.id
.clone(),
1071 protected
: mark
.protected(),
1076 if let Err(err
) = backup_dir
.destroy(false) {
1079 "failed to remove dir {:?}: {}",
1080 backup_dir
.relative_path(),
1089 if param
["use-task"].as_bool().unwrap_or(false) {
1090 let upid
= WorkerTask
::spawn(
1093 auth_id
.to_string(),
1095 move |worker
| async
move {
1096 let _
= prune_group(worker
.clone());
1102 let worker
= WorkerTask
::new("prune", Some(worker_id
), auth_id
.to_string(), true)?
;
1103 let result
= prune_group(worker
.clone());
1104 worker
.log_result(&Ok(()));
1116 description
: "Just show what prune would do, but do not delete anything.",
1119 type: PruneJobOptions
,
1123 schema
: DATASTORE_SCHEMA
,
1128 schema
: UPID_SCHEMA
,
1131 permission
: &Permission
::Anybody
,
1132 description
: "Requires Datastore.Modify or Datastore.Prune on the datastore/namespace.",
1135 /// Prune the datastore
1136 pub fn prune_datastore(
1138 prune_options
: PruneJobOptions
,
1141 rpcenv
: &mut dyn RpcEnvironment
,
1142 ) -> Result
<String
, Error
> {
1143 let user_info
= CachedUserInfo
::new()?
;
1145 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
1147 user_info
.check_privs(
1149 &prune_options
.acl_path(&store
),
1150 PRIV_DATASTORE_MODIFY
| PRIV_DATASTORE_PRUNE
,
1154 let datastore
= DataStore
::lookup_datastore(&store
, Some(Operation
::Write
))?
;
1155 let ns
= prune_options
.ns
.clone().unwrap_or_default();
1156 let worker_id
= format
!("{}:{}", store
, ns
);
1158 let to_stdout
= rpcenv
.env_type() == RpcEnvironmentType
::CLI
;
1160 let upid_str
= WorkerTask
::new_thread(
1163 auth_id
.to_string(),
1166 crate::server
::prune_datastore(worker
, auth_id
, prune_options
, datastore
, dry_run
)
1177 schema
: DATASTORE_SCHEMA
,
1182 schema
: UPID_SCHEMA
,
1185 permission
: &Permission
::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_MODIFY
, false),
1188 /// Start garbage collection.
1189 pub fn start_garbage_collection(
1192 rpcenv
: &mut dyn RpcEnvironment
,
1193 ) -> Result
<Value
, Error
> {
1194 let datastore
= DataStore
::lookup_datastore(&store
, Some(Operation
::Write
))?
;
1195 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
1197 let job
= Job
::new("garbage_collection", &store
)
1198 .map_err(|_
| format_err
!("garbage collection already running"))?
;
1200 let to_stdout
= rpcenv
.env_type() == RpcEnvironmentType
::CLI
;
1203 crate::server
::do_garbage_collection_job(job
, datastore
, &auth_id
, None
, to_stdout
)
1206 "unable to start garbage collection job on datastore {} - {}",
1219 schema
: DATASTORE_SCHEMA
,
1224 type: GarbageCollectionJobStatus
,
1227 permission
: &Permission
::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_AUDIT
, false),
1230 /// Garbage collection status.
1231 pub fn garbage_collection_status(
1234 _rpcenv
: &mut dyn RpcEnvironment
,
1235 ) -> Result
<GarbageCollectionJobStatus
, Error
> {
1236 let (config
, _
) = pbs_config
::datastore
::config()?
;
1237 let store_config
: DataStoreConfig
= config
.lookup("datastore", &store
)?
;
1239 let mut info
= GarbageCollectionJobStatus
{
1240 store
: store
.clone(),
1241 schedule
: store_config
.gc_schedule
,
1242 ..Default
::default()
1245 let datastore
= DataStore
::lookup_datastore(&store
, Some(Operation
::Read
))?
;
1246 let status_in_memory
= datastore
.last_gc_status();
1247 let state_file
= JobState
::load("garbage_collection", &store
)
1248 .map_err(|err
| log
::error
!("could not open GC statefile for {store}: {err}"))
1251 let mut last
= proxmox_time
::epoch_i64();
1253 if let Some(ref upid
) = status_in_memory
.upid
{
1254 let mut computed_schedule
: JobScheduleStatus
= JobScheduleStatus
::default();
1255 if let Some(state
) = state_file
{
1256 if let Ok(cs
) = compute_schedule_status(&state
, Some(&upid
)) {
1257 computed_schedule
= cs
;
1261 if let Some(endtime
) = computed_schedule
.last_run_endtime
{
1263 if let Ok(parsed_upid
) = upid
.parse
::<UPID
>() {
1264 info
.duration
= Some(endtime
- parsed_upid
.starttime
);
1268 info
.next_run
= computed_schedule
.next_run
;
1269 info
.last_run_endtime
= computed_schedule
.last_run_endtime
;
1270 info
.last_run_state
= computed_schedule
.last_run_state
;
1273 info
.next_run
= info
1277 s
.parse
::<CalendarEvent
>()
1278 .map_err(|err
| log
::error
!("{err}"))
1282 e
.compute_next_event(last
)
1283 .map_err(|err
| log
::error
!("{err}"))
1288 info
.status
= status_in_memory
;
1295 description
: "List the accessible datastores.",
1297 items
: { type: DataStoreListItem }
,
1300 permission
: &Permission
::Anybody
,
1304 pub fn get_datastore_list(
1307 rpcenv
: &mut dyn RpcEnvironment
,
1308 ) -> Result
<Vec
<DataStoreListItem
>, Error
> {
1309 let (config
, _digest
) = pbs_config
::datastore
::config()?
;
1311 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
1312 let user_info
= CachedUserInfo
::new()?
;
1314 let mut list
= Vec
::new();
1316 for (store
, (_
, data
)) in &config
.sections
{
1317 let acl_path
= &["datastore", store
];
1318 let user_privs
= user_info
.lookup_privs(&auth_id
, acl_path
);
1319 let allowed
= (user_privs
& (PRIV_DATASTORE_AUDIT
| PRIV_DATASTORE_BACKUP
)) != 0;
1321 let mut allow_id
= false;
1323 if let Ok(any_privs
) = user_info
.any_privs_below(&auth_id
, acl_path
, NS_PRIVS_OK
) {
1324 allow_id
= any_privs
;
1328 if allowed
|| allow_id
{
1329 list
.push(DataStoreListItem
{
1330 store
: store
.clone(),
1331 comment
: if !allowed
{
1334 data
["comment"].as_str().map(String
::from
)
1336 maintenance
: data
["maintenance-mode"].as_str().map(String
::from
),
1345 pub const API_METHOD_DOWNLOAD_FILE
: ApiMethod
= ApiMethod
::new(
1346 &ApiHandler
::AsyncHttp(&download_file
),
1348 "Download single raw file from backup snapshot.",
1350 ("store", false, &DATASTORE_SCHEMA
),
1351 ("ns", true, &BACKUP_NAMESPACE_SCHEMA
),
1352 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
1353 ("backup-id", false, &BACKUP_ID_SCHEMA
),
1354 ("backup-time", false, &BACKUP_TIME_SCHEMA
),
1355 ("file-name", false, &BACKUP_ARCHIVE_NAME_SCHEMA
),
1361 "Requires on /datastore/{store}[/{namespace}] either DATASTORE_READ for any or \
1362 DATASTORE_BACKUP and being the owner of the group",
1364 &Permission
::Anybody
,
1367 pub fn download_file(
1372 rpcenv
: Box
<dyn RpcEnvironment
>,
1373 ) -> ApiResponseFuture
{
1375 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
1376 let store
= required_string_param(¶m
, "store")?
;
1377 let backup_ns
= optional_ns_param(¶m
)?
;
1379 let backup_dir
: pbs_api_types
::BackupDir
= Deserialize
::deserialize(¶m
)?
;
1380 let datastore
= check_privs_and_load_store(
1384 PRIV_DATASTORE_READ
,
1385 PRIV_DATASTORE_BACKUP
,
1386 Some(Operation
::Read
),
1390 let file_name
= required_string_param(¶m
, "file-name")?
.to_owned();
1393 "Download {} from {} ({}/{})",
1395 print_store_and_ns(store
, &backup_ns
),
1400 let backup_dir
= datastore
.backup_dir(backup_ns
, backup_dir
)?
;
1402 let mut path
= datastore
.base_path();
1403 path
.push(backup_dir
.relative_path());
1404 path
.push(&file_name
);
1406 let file
= tokio
::fs
::File
::open(&path
)
1408 .map_err(|err
| http_err
!(BAD_REQUEST
, "File open failed: {}", err
))?
;
1411 tokio_util
::codec
::FramedRead
::new(file
, tokio_util
::codec
::BytesCodec
::new())
1412 .map_ok(|bytes
| bytes
.freeze())
1413 .map_err(move |err
| {
1414 eprintln
!("error during streaming of '{:?}' - {}", &path
, err
);
1417 let body
= Body
::wrap_stream(payload
);
1419 // fixme: set other headers ?
1420 Ok(Response
::builder()
1421 .status(StatusCode
::OK
)
1422 .header(header
::CONTENT_TYPE
, "application/octet-stream")
1430 pub const API_METHOD_DOWNLOAD_FILE_DECODED
: ApiMethod
= ApiMethod
::new(
1431 &ApiHandler
::AsyncHttp(&download_file_decoded
),
1433 "Download single decoded file from backup snapshot. Only works if it's not encrypted.",
1435 ("store", false, &DATASTORE_SCHEMA
),
1436 ("ns", true, &BACKUP_NAMESPACE_SCHEMA
),
1437 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
1438 ("backup-id", false, &BACKUP_ID_SCHEMA
),
1439 ("backup-time", false, &BACKUP_TIME_SCHEMA
),
1440 ("file-name", false, &BACKUP_ARCHIVE_NAME_SCHEMA
),
1446 "Requires on /datastore/{store}[/{namespace}] either DATASTORE_READ for any or \
1447 DATASTORE_BACKUP and being the owner of the group",
1449 &Permission
::Anybody
,
1452 pub fn download_file_decoded(
1457 rpcenv
: Box
<dyn RpcEnvironment
>,
1458 ) -> ApiResponseFuture
{
1460 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
1461 let store
= required_string_param(¶m
, "store")?
;
1462 let backup_ns
= optional_ns_param(¶m
)?
;
1464 let backup_dir_api
: pbs_api_types
::BackupDir
= Deserialize
::deserialize(¶m
)?
;
1465 let datastore
= check_privs_and_load_store(
1469 PRIV_DATASTORE_READ
,
1470 PRIV_DATASTORE_BACKUP
,
1471 Some(Operation
::Read
),
1472 &backup_dir_api
.group
,
1475 let file_name
= required_string_param(¶m
, "file-name")?
.to_owned();
1476 let backup_dir
= datastore
.backup_dir(backup_ns
.clone(), backup_dir_api
.clone())?
;
1478 let (manifest
, files
) = read_backup_index(&backup_dir
)?
;
1480 if file
.filename
== file_name
&& file
.crypt_mode
== Some(CryptMode
::Encrypt
) {
1481 bail
!("cannot decode '{}' - is encrypted", file_name
);
1486 "Download {} from {} ({}/{})",
1488 print_store_and_ns(store
, &backup_ns
),
1493 let mut path
= datastore
.base_path();
1494 path
.push(backup_dir
.relative_path());
1495 path
.push(&file_name
);
1497 let (_
, extension
) = file_name
.rsplit_once('
.'
).unwrap();
1499 let body
= match extension
{
1501 let index
= DynamicIndexReader
::open(&path
).map_err(|err
| {
1502 format_err
!("unable to read dynamic index '{:?}' - {}", &path
, err
)
1504 let (csum
, size
) = index
.compute_csum();
1505 manifest
.verify_file(&file_name
, &csum
, size
)?
;
1507 let chunk_reader
= LocalChunkReader
::new(datastore
, None
, CryptMode
::None
);
1508 let reader
= CachedChunkReader
::new(chunk_reader
, index
, 1).seekable();
1509 Body
::wrap_stream(AsyncReaderStream
::new(reader
).map_err(move |err
| {
1510 eprintln
!("error during streaming of '{:?}' - {}", path
, err
);
1515 let index
= FixedIndexReader
::open(&path
).map_err(|err
| {
1516 format_err
!("unable to read fixed index '{:?}' - {}", &path
, err
)
1519 let (csum
, size
) = index
.compute_csum();
1520 manifest
.verify_file(&file_name
, &csum
, size
)?
;
1522 let chunk_reader
= LocalChunkReader
::new(datastore
, None
, CryptMode
::None
);
1523 let reader
= CachedChunkReader
::new(chunk_reader
, index
, 1).seekable();
1525 AsyncReaderStream
::with_buffer_size(reader
, 4 * 1024 * 1024).map_err(
1527 eprintln
!("error during streaming of '{:?}' - {}", path
, err
);
1534 let file
= std
::fs
::File
::open(&path
)
1535 .map_err(|err
| http_err
!(BAD_REQUEST
, "File open failed: {}", err
))?
;
1537 // FIXME: load full blob to verify index checksum?
1540 WrappedReaderStream
::new(DataBlobReader
::new(file
, None
)?
).map_err(
1542 eprintln
!("error during streaming of '{:?}' - {}", path
, err
);
1549 bail
!("cannot download '{}' files", extension
);
1553 // fixme: set other headers ?
1554 Ok(Response
::builder()
1555 .status(StatusCode
::OK
)
1556 .header(header
::CONTENT_TYPE
, "application/octet-stream")
1564 pub const API_METHOD_UPLOAD_BACKUP_LOG
: ApiMethod
= ApiMethod
::new(
1565 &ApiHandler
::AsyncHttp(&upload_backup_log
),
1567 "Upload the client backup log file into a backup snapshot ('client.log.blob').",
1569 ("store", false, &DATASTORE_SCHEMA
),
1570 ("ns", true, &BACKUP_NAMESPACE_SCHEMA
),
1571 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
1572 ("backup-id", false, &BACKUP_ID_SCHEMA
),
1573 ("backup-time", false, &BACKUP_TIME_SCHEMA
),
1578 Some("Only the backup creator/owner is allowed to do this."),
1579 &Permission
::Anybody
,
1582 pub fn upload_backup_log(
1587 rpcenv
: Box
<dyn RpcEnvironment
>,
1588 ) -> ApiResponseFuture
{
1590 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
1591 let store
= required_string_param(¶m
, "store")?
;
1592 let backup_ns
= optional_ns_param(¶m
)?
;
1594 let backup_dir_api
: pbs_api_types
::BackupDir
= Deserialize
::deserialize(¶m
)?
;
1596 let datastore
= check_privs_and_load_store(
1601 PRIV_DATASTORE_BACKUP
,
1602 Some(Operation
::Write
),
1603 &backup_dir_api
.group
,
1605 let backup_dir
= datastore
.backup_dir(backup_ns
.clone(), backup_dir_api
.clone())?
;
1607 let file_name
= CLIENT_LOG_BLOB_NAME
;
1609 let mut path
= backup_dir
.full_path();
1610 path
.push(file_name
);
1613 bail
!("backup already contains a log.");
1617 "Upload backup log to {} {backup_dir_api}/{file_name}",
1618 print_store_and_ns(store
, &backup_ns
),
1622 .map_err(Error
::from
)
1623 .try_fold(Vec
::new(), |mut acc
, chunk
| {
1624 acc
.extend_from_slice(&chunk
);
1625 future
::ok
::<_
, Error
>(acc
)
1629 // always verify blob/CRC at server side
1630 let blob
= DataBlob
::load_from_reader(&mut &data
[..])?
;
1632 replace_file(&path
, blob
.raw_data(), CreateOptions
::new(), false)?
;
1634 // fixme: use correct formatter
1635 Ok(formatter
::JSON_FORMATTER
.format_data(Value
::Null
, &*rpcenv
))
1643 store
: { schema: DATASTORE_SCHEMA }
,
1645 type: BackupNamespace
,
1649 type: pbs_api_types
::BackupDir
,
1653 description
: "Base64 encoded path.",
1659 description
: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_READ for any or \
1660 DATASTORE_BACKUP and being the owner of the group",
1661 permission
: &Permission
::Anybody
,
1664 /// Get the entries of the given path of the catalog
1665 pub async
fn catalog(
1667 ns
: Option
<BackupNamespace
>,
1668 backup_dir
: pbs_api_types
::BackupDir
,
1670 rpcenv
: &mut dyn RpcEnvironment
,
1671 ) -> Result
<Vec
<ArchiveEntry
>, Error
> {
1672 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
1674 tokio
::task
::spawn_blocking(move || {
1675 let ns
= ns
.unwrap_or_default();
1677 let datastore
= check_privs_and_load_store(
1681 PRIV_DATASTORE_READ
,
1682 PRIV_DATASTORE_BACKUP
,
1683 Some(Operation
::Read
),
1687 let backup_dir
= datastore
.backup_dir(ns
, backup_dir
)?
;
1689 let file_name
= CATALOG_NAME
;
1691 let (manifest
, files
) = read_backup_index(&backup_dir
)?
;
1693 if file
.filename
== file_name
&& file
.crypt_mode
== Some(CryptMode
::Encrypt
) {
1694 bail
!("cannot decode '{}' - is encrypted", file_name
);
1698 let mut path
= datastore
.base_path();
1699 path
.push(backup_dir
.relative_path());
1700 path
.push(file_name
);
1702 let index
= DynamicIndexReader
::open(&path
)
1703 .map_err(|err
| format_err
!("unable to read dynamic index '{:?}' - {}", &path
, err
))?
;
1705 let (csum
, size
) = index
.compute_csum();
1706 manifest
.verify_file(file_name
, &csum
, size
)?
;
1708 let chunk_reader
= LocalChunkReader
::new(datastore
, None
, CryptMode
::None
);
1709 let reader
= BufferedDynamicReader
::new(index
, chunk_reader
);
1711 let mut catalog_reader
= CatalogReader
::new(reader
);
1713 let path
= if filepath
!= "root" && filepath
!= "/" {
1714 base64
::decode(filepath
)?
1719 catalog_reader
.list_dir_contents(&path
)
1725 pub const API_METHOD_PXAR_FILE_DOWNLOAD
: ApiMethod
= ApiMethod
::new(
1726 &ApiHandler
::AsyncHttp(&pxar_file_download
),
1728 "Download single file from pxar file of a backup snapshot. Only works if it's not encrypted.",
1730 ("store", false, &DATASTORE_SCHEMA
),
1731 ("ns", true, &BACKUP_NAMESPACE_SCHEMA
),
1732 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
1733 ("backup-id", false, &BACKUP_ID_SCHEMA
),
1734 ("backup-time", false, &BACKUP_TIME_SCHEMA
),
1735 ("filepath", false, &StringSchema
::new("Base64 encoded path").schema()),
1736 ("tar", true, &BooleanSchema
::new("Download as .tar.zst").schema()),
1741 "Requires on /datastore/{store}[/{namespace}] either DATASTORE_READ for any or \
1742 DATASTORE_BACKUP and being the owner of the group",
1744 &Permission
::Anybody
,
1747 pub fn pxar_file_download(
1752 rpcenv
: Box
<dyn RpcEnvironment
>,
1753 ) -> ApiResponseFuture
{
1755 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
1756 let store
= required_string_param(¶m
, "store")?
;
1757 let ns
= optional_ns_param(¶m
)?
;
1759 let backup_dir
: pbs_api_types
::BackupDir
= Deserialize
::deserialize(¶m
)?
;
1760 let datastore
= check_privs_and_load_store(
1764 PRIV_DATASTORE_READ
,
1765 PRIV_DATASTORE_BACKUP
,
1766 Some(Operation
::Read
),
1770 let backup_dir
= datastore
.backup_dir(ns
, backup_dir
)?
;
1772 let filepath
= required_string_param(¶m
, "filepath")?
.to_owned();
1774 let tar
= param
["tar"].as_bool().unwrap_or(false);
1776 let mut components
= base64
::decode(&filepath
)?
;
1777 if !components
.is_empty() && components
[0] == b'
/'
{
1778 components
.remove(0);
1781 let mut split
= components
.splitn(2, |c
| *c
== b'
/'
);
1782 let pxar_name
= std
::str::from_utf8(split
.next().unwrap())?
;
1783 let file_path
= split
.next().unwrap_or(b
"/");
1784 let (manifest
, files
) = read_backup_index(&backup_dir
)?
;
1786 if file
.filename
== pxar_name
&& file
.crypt_mode
== Some(CryptMode
::Encrypt
) {
1787 bail
!("cannot decode '{}' - is encrypted", pxar_name
);
1791 let mut path
= datastore
.base_path();
1792 path
.push(backup_dir
.relative_path());
1793 path
.push(pxar_name
);
1795 let index
= DynamicIndexReader
::open(&path
)
1796 .map_err(|err
| format_err
!("unable to read dynamic index '{:?}' - {}", &path
, err
))?
;
1798 let (csum
, size
) = index
.compute_csum();
1799 manifest
.verify_file(pxar_name
, &csum
, size
)?
;
1801 let chunk_reader
= LocalChunkReader
::new(datastore
, None
, CryptMode
::None
);
1802 let reader
= BufferedDynamicReader
::new(index
, chunk_reader
);
1803 let archive_size
= reader
.archive_size();
1804 let reader
= LocalDynamicReadAt
::new(reader
);
1806 let decoder
= Accessor
::new(reader
, archive_size
).await?
;
1807 let root
= decoder
.open_root().await?
;
1808 let path
= OsStr
::from_bytes(file_path
).to_os_string();
1812 .ok_or_else(|| format_err
!("error opening '{:?}'", path
))?
;
1814 let body
= match file
.kind() {
1815 EntryKind
::File { .. }
=> Body
::wrap_stream(
1816 AsyncReaderStream
::new(file
.contents().await?
).map_err(move |err
| {
1817 eprintln
!("error during streaming of file '{:?}' - {}", filepath
, err
);
1821 EntryKind
::Hardlink(_
) => Body
::wrap_stream(
1822 AsyncReaderStream
::new(decoder
.follow_hardlink(&file
).await?
.contents().await?
)
1823 .map_err(move |err
| {
1824 eprintln
!("error during streaming of hardlink '{:?}' - {}", path
, err
);
1828 EntryKind
::Directory
=> {
1829 let (sender
, receiver
) = tokio
::sync
::mpsc
::channel
::<Result
<_
, Error
>>(100);
1830 let channelwriter
= AsyncChannelWriter
::new(sender
, 1024 * 1024);
1832 proxmox_rest_server
::spawn_internal_task(create_tar(
1837 let zstdstream
= ZstdEncoder
::new(ReceiverStream
::new(receiver
))?
;
1838 Body
::wrap_stream(zstdstream
.map_err(move |err
| {
1839 log
::error
!("error during streaming of tar.zst '{:?}' - {}", path
, err
);
1843 proxmox_rest_server
::spawn_internal_task(create_zip(
1848 Body
::wrap_stream(ReceiverStream
::new(receiver
).map_err(move |err
| {
1849 log
::error
!("error during streaming of zip '{:?}' - {}", path
, err
);
1854 other
=> bail
!("cannot download file of type {:?}", other
),
1857 // fixme: set other headers ?
1858 Ok(Response
::builder()
1859 .status(StatusCode
::OK
)
1860 .header(header
::CONTENT_TYPE
, "application/octet-stream")
1871 schema
: DATASTORE_SCHEMA
,
1882 permission
: &Permission
::Privilege(
1883 &["datastore", "{store}"], PRIV_DATASTORE_AUDIT
| PRIV_DATASTORE_BACKUP
, true),
1886 /// Read datastore stats
1887 pub fn get_rrd_stats(
1889 timeframe
: RRDTimeFrame
,
1892 ) -> Result
<Value
, Error
> {
1893 let datastore
= DataStore
::lookup_datastore(&store
, Some(Operation
::Read
))?
;
1894 let disk_manager
= crate::tools
::disks
::DiskManage
::new();
1896 let mut rrd_fields
= vec
![
1906 // we do not have io_ticks for zpools, so don't include them
1907 match disk_manager
.find_mounted_device(&datastore
.base_path()) {
1908 Ok(Some((fs_type
, _
, _
))) if fs_type
.as_str() == "zfs" => {}
1909 _
=> rrd_fields
.push("io_ticks"),
1912 create_value_from_rrd(&format
!("datastore/{}", store
), &rrd_fields
, timeframe
, cf
)
1919 schema
: DATASTORE_SCHEMA
,
1924 permission
: &Permission
::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_AUDIT
, true),
1927 /// Read datastore stats
1928 pub fn get_active_operations(store
: String
, _param
: Value
) -> Result
<Value
, Error
> {
1929 let active_operations
= task_tracking
::get_active_operations(&store
)?
;
1931 "read": active_operations
.read
,
1932 "write": active_operations
.write
,
1939 store
: { schema: DATASTORE_SCHEMA }
,
1941 type: BackupNamespace
,
1945 type: pbs_api_types
::BackupGroup
,
1951 permission
: &Permission
::Anybody
,
1952 description
: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_AUDIT for any \
1953 or DATASTORE_BACKUP and being the owner of the group",
1956 /// Get "notes" for a backup group
1957 pub fn get_group_notes(
1959 ns
: Option
<BackupNamespace
>,
1960 backup_group
: pbs_api_types
::BackupGroup
,
1961 rpcenv
: &mut dyn RpcEnvironment
,
1962 ) -> Result
<String
, Error
> {
1963 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
1964 let ns
= ns
.unwrap_or_default();
1966 let datastore
= check_privs_and_load_store(
1970 PRIV_DATASTORE_AUDIT
,
1971 PRIV_DATASTORE_BACKUP
,
1972 Some(Operation
::Read
),
1976 let note_path
= get_group_note_path(&datastore
, &ns
, &backup_group
);
1977 Ok(file_read_optional_string(note_path
)?
.unwrap_or_else(|| "".to_owned()))
1983 store
: { schema: DATASTORE_SCHEMA }
,
1985 type: BackupNamespace
,
1989 type: pbs_api_types
::BackupGroup
,
1993 description
: "A multiline text.",
1998 permission
: &Permission
::Anybody
,
1999 description
: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any \
2000 or DATASTORE_BACKUP and being the owner of the group",
2003 /// Set "notes" for a backup group
2004 pub fn set_group_notes(
2006 ns
: Option
<BackupNamespace
>,
2007 backup_group
: pbs_api_types
::BackupGroup
,
2009 rpcenv
: &mut dyn RpcEnvironment
,
2010 ) -> Result
<(), Error
> {
2011 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
2012 let ns
= ns
.unwrap_or_default();
2014 let datastore
= check_privs_and_load_store(
2018 PRIV_DATASTORE_MODIFY
,
2019 PRIV_DATASTORE_BACKUP
,
2020 Some(Operation
::Write
),
2024 let note_path
= get_group_note_path(&datastore
, &ns
, &backup_group
);
2025 replace_file(note_path
, notes
.as_bytes(), CreateOptions
::new(), false)?
;
2033 store
: { schema: DATASTORE_SCHEMA }
,
2035 type: BackupNamespace
,
2039 type: pbs_api_types
::BackupDir
,
2045 permission
: &Permission
::Anybody
,
2046 description
: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_AUDIT for any \
2047 or DATASTORE_BACKUP and being the owner of the group",
2050 /// Get "notes" for a specific backup
2053 ns
: Option
<BackupNamespace
>,
2054 backup_dir
: pbs_api_types
::BackupDir
,
2055 rpcenv
: &mut dyn RpcEnvironment
,
2056 ) -> Result
<String
, Error
> {
2057 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
2058 let ns
= ns
.unwrap_or_default();
2060 let datastore
= check_privs_and_load_store(
2064 PRIV_DATASTORE_AUDIT
,
2065 PRIV_DATASTORE_BACKUP
,
2066 Some(Operation
::Read
),
2070 let backup_dir
= datastore
.backup_dir(ns
, backup_dir
)?
;
2072 let (manifest
, _
) = backup_dir
.load_manifest()?
;
2074 let notes
= manifest
.unprotected
["notes"].as_str().unwrap_or("");
2076 Ok(String
::from(notes
))
2082 store
: { schema: DATASTORE_SCHEMA }
,
2084 type: BackupNamespace
,
2088 type: pbs_api_types
::BackupDir
,
2092 description
: "A multiline text.",
2097 permission
: &Permission
::Anybody
,
2098 description
: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any \
2099 or DATASTORE_BACKUP and being the owner of the group",
2102 /// Set "notes" for a specific backup
2105 ns
: Option
<BackupNamespace
>,
2106 backup_dir
: pbs_api_types
::BackupDir
,
2108 rpcenv
: &mut dyn RpcEnvironment
,
2109 ) -> Result
<(), Error
> {
2110 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
2111 let ns
= ns
.unwrap_or_default();
2113 let datastore
= check_privs_and_load_store(
2117 PRIV_DATASTORE_MODIFY
,
2118 PRIV_DATASTORE_BACKUP
,
2119 Some(Operation
::Write
),
2123 let backup_dir
= datastore
.backup_dir(ns
, backup_dir
)?
;
2126 .update_manifest(|manifest
| {
2127 manifest
.unprotected
["notes"] = notes
.into();
2129 .map_err(|err
| format_err
!("unable to update manifest blob - {}", err
))?
;
2137 store
: { schema: DATASTORE_SCHEMA }
,
2139 type: BackupNamespace
,
2143 type: pbs_api_types
::BackupDir
,
2149 permission
: &Permission
::Anybody
,
2150 description
: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_AUDIT for any \
2151 or DATASTORE_BACKUP and being the owner of the group",
2154 /// Query protection for a specific backup
2155 pub fn get_protection(
2157 ns
: Option
<BackupNamespace
>,
2158 backup_dir
: pbs_api_types
::BackupDir
,
2159 rpcenv
: &mut dyn RpcEnvironment
,
2160 ) -> Result
<bool
, Error
> {
2161 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
2162 let ns
= ns
.unwrap_or_default();
2163 let datastore
= check_privs_and_load_store(
2167 PRIV_DATASTORE_AUDIT
,
2168 PRIV_DATASTORE_BACKUP
,
2169 Some(Operation
::Read
),
2173 let backup_dir
= datastore
.backup_dir(ns
, backup_dir
)?
;
2175 Ok(backup_dir
.is_protected())
2181 store
: { schema: DATASTORE_SCHEMA }
,
2183 type: BackupNamespace
,
2187 type: pbs_api_types
::BackupDir
,
2191 description
: "Enable/disable protection.",
2196 permission
: &Permission
::Anybody
,
2197 description
: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any \
2198 or DATASTORE_BACKUP and being the owner of the group",
2201 /// En- or disable protection for a specific backup
2202 pub async
fn set_protection(
2204 ns
: Option
<BackupNamespace
>,
2205 backup_dir
: pbs_api_types
::BackupDir
,
2207 rpcenv
: &mut dyn RpcEnvironment
,
2208 ) -> Result
<(), Error
> {
2209 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
2211 tokio
::task
::spawn_blocking(move || {
2212 let ns
= ns
.unwrap_or_default();
2213 let datastore
= check_privs_and_load_store(
2217 PRIV_DATASTORE_MODIFY
,
2218 PRIV_DATASTORE_BACKUP
,
2219 Some(Operation
::Write
),
2223 let backup_dir
= datastore
.backup_dir(ns
, backup_dir
)?
;
2225 datastore
.update_protection(&backup_dir
, protected
)
2233 store
: { schema: DATASTORE_SCHEMA }
,
2235 type: BackupNamespace
,
2239 type: pbs_api_types
::BackupGroup
,
2248 permission
: &Permission
::Anybody
,
2249 description
: "Datastore.Modify on whole datastore, or changing ownership between user and \
2250 a user's token for owned backups with Datastore.Backup"
2253 /// Change owner of a backup group
2254 pub async
fn set_backup_owner(
2256 ns
: Option
<BackupNamespace
>,
2257 backup_group
: pbs_api_types
::BackupGroup
,
2259 rpcenv
: &mut dyn RpcEnvironment
,
2260 ) -> Result
<(), Error
> {
2261 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
2263 tokio
::task
::spawn_blocking(move || {
2264 let ns
= ns
.unwrap_or_default();
2265 let owner_check_required
= check_ns_privs_full(
2269 PRIV_DATASTORE_MODIFY
,
2270 PRIV_DATASTORE_BACKUP
,
2273 let datastore
= DataStore
::lookup_datastore(&store
, Some(Operation
::Write
))?
;
2275 let backup_group
= datastore
.backup_group(ns
, backup_group
);
2277 if owner_check_required
{
2278 let owner
= backup_group
.get_owner()?
;
2280 let allowed
= match (owner
.is_token(), new_owner
.is_token()) {
2282 // API token to API token, owned by same user
2283 let owner
= owner
.user();
2284 let new_owner
= new_owner
.user();
2285 owner
== new_owner
&& Authid
::from(owner
.clone()) == auth_id
2288 // API token to API token owner
2289 Authid
::from(owner
.user().clone()) == auth_id
&& new_owner
== auth_id
2292 // API token owner to API token
2293 owner
== auth_id
&& Authid
::from(new_owner
.user().clone()) == auth_id
2296 // User to User, not allowed for unprivileged users
2302 return Err(http_err
!(
2304 "{} does not have permission to change owner of backup group '{}' to {}",
2306 backup_group
.group(),
2312 let user_info
= CachedUserInfo
::new()?
;
2314 if !user_info
.is_active_auth_id(&new_owner
) {
2316 "{} '{}' is inactive or non-existent",
2317 if new_owner
.is_token() {
2318 "API token".to_string()
2326 backup_group
.set_owner(&new_owner
, true)?
;
2334 const DATASTORE_INFO_SUBDIRS
: SubdirMap
= &[
2336 "active-operations",
2337 &Router
::new().get(&API_METHOD_GET_ACTIVE_OPERATIONS
),
2339 ("catalog", &Router
::new().get(&API_METHOD_CATALOG
)),
2342 &Router
::new().post(&API_METHOD_SET_BACKUP_OWNER
),
2346 &Router
::new().download(&API_METHOD_DOWNLOAD_FILE
),
2350 &Router
::new().download(&API_METHOD_DOWNLOAD_FILE_DECODED
),
2352 ("files", &Router
::new().get(&API_METHOD_LIST_SNAPSHOT_FILES
)),
2356 .get(&API_METHOD_GARBAGE_COLLECTION_STATUS
)
2357 .post(&API_METHOD_START_GARBAGE_COLLECTION
),
2362 .get(&API_METHOD_GET_GROUP_NOTES
)
2363 .put(&API_METHOD_SET_GROUP_NOTES
),
2368 .get(&API_METHOD_LIST_GROUPS
)
2369 .delete(&API_METHOD_DELETE_GROUP
),
2373 // FIXME: move into datastore:: sub-module?!
2374 &crate::api2
::admin
::namespace
::ROUTER
,
2379 .get(&API_METHOD_GET_NOTES
)
2380 .put(&API_METHOD_SET_NOTES
),
2385 .get(&API_METHOD_GET_PROTECTION
)
2386 .put(&API_METHOD_SET_PROTECTION
),
2388 ("prune", &Router
::new().post(&API_METHOD_PRUNE
)),
2391 &Router
::new().post(&API_METHOD_PRUNE_DATASTORE
),
2394 "pxar-file-download",
2395 &Router
::new().download(&API_METHOD_PXAR_FILE_DOWNLOAD
),
2397 ("rrd", &Router
::new().get(&API_METHOD_GET_RRD_STATS
)),
2401 .get(&API_METHOD_LIST_SNAPSHOTS
)
2402 .delete(&API_METHOD_DELETE_SNAPSHOT
),
2404 ("status", &Router
::new().get(&API_METHOD_STATUS
)),
2406 "upload-backup-log",
2407 &Router
::new().upload(&API_METHOD_UPLOAD_BACKUP_LOG
),
2409 ("verify", &Router
::new().post(&API_METHOD_VERIFY
)),
2412 const DATASTORE_INFO_ROUTER
: Router
= Router
::new()
2413 .get(&list_subdirs_api_method
!(DATASTORE_INFO_SUBDIRS
))
2414 .subdirs(DATASTORE_INFO_SUBDIRS
);
2416 pub const ROUTER
: Router
= Router
::new()
2417 .get(&API_METHOD_GET_DATASTORE_LIST
)
2418 .match_all("store", &DATASTORE_INFO_ROUTER
);