]> git.proxmox.com Git - proxmox-backup.git/blame - src/api2/admin/datastore.rs
api: datastore: unify access checks
[proxmox-backup.git] / src / api2 / admin / datastore.rs
CommitLineData
bf78f708
DM
1//! Datastore Management
2
0d08fcee 3use std::collections::HashSet;
d33d8f4e
DC
4use std::ffi::OsStr;
5use std::os::unix::ffi::OsStrExt;
d6688884 6use std::path::PathBuf;
6da20161 7use std::sync::Arc;
cad540e9 8
6ef9bb59 9use anyhow::{bail, format_err, Error};
9e47c0a5 10use futures::*;
cad540e9
WB
11use hyper::http::request::Parts;
12use hyper::{header, Body, Response, StatusCode};
8c74349b 13use serde::Deserialize;
15e9b4ed 14use serde_json::{json, Value};
7c667013 15use tokio_stream::wrappers::ReceiverStream;
15e9b4ed 16
dc7a5b34
TL
17use proxmox_async::blocking::WrappedReaderStream;
18use proxmox_async::{io::AsyncChannelWriter, stream::AsyncReaderStream};
984ddb2f 19use proxmox_compression::zstd::ZstdEncoder;
6ef1b649 20use proxmox_router::{
dc7a5b34
TL
21 http_err, list_subdirs_api_method, ApiHandler, ApiMethod, ApiResponseFuture, Permission,
22 Router, RpcEnvironment, RpcEnvironmentType, SubdirMap,
6ef1b649
WB
23};
24use proxmox_schema::*;
dc7a5b34
TL
25use proxmox_sys::fs::{
26 file_read_firstline, file_read_optional_string, replace_file, CreateOptions,
27};
28use proxmox_sys::sortable;
d5790a9f 29use proxmox_sys::{task_log, task_warn};
e18a6c9e 30
2e219481 31use pxar::accessor::aio::Accessor;
d33d8f4e
DC
32use pxar::EntryKind;
33
dc7a5b34 34use pbs_api_types::{
8c74349b
WB
35 Authid, BackupContent, BackupNamespace, BackupType, Counts, CryptMode, DataStoreListItem,
36 DataStoreStatus, GarbageCollectionStatus, GroupListItem, Operation, PruneOptions, RRDMode,
37 RRDTimeFrame, SnapshotListItem, SnapshotVerifyState, BACKUP_ARCHIVE_NAME_SCHEMA,
33f2c2a1
WB
38 BACKUP_ID_SCHEMA, BACKUP_NAMESPACE_SCHEMA, BACKUP_TIME_SCHEMA, BACKUP_TYPE_SCHEMA,
39 DATASTORE_SCHEMA, IGNORE_VERIFIED_BACKUPS_SCHEMA, PRIV_DATASTORE_AUDIT, PRIV_DATASTORE_BACKUP,
8c74349b
WB
40 PRIV_DATASTORE_MODIFY, PRIV_DATASTORE_PRUNE, PRIV_DATASTORE_READ, PRIV_DATASTORE_VERIFY,
41 UPID_SCHEMA, VERIFICATION_OUTDATED_AFTER_SCHEMA,
b2065dc7 42};
984ddb2f 43use pbs_client::pxar::{create_tar, create_zip};
dc7a5b34 44use pbs_config::CachedUserInfo;
b2065dc7
WB
45use pbs_datastore::backup_info::BackupInfo;
46use pbs_datastore::cached_chunk_reader::CachedChunkReader;
013b1e8b 47use pbs_datastore::catalog::{ArchiveEntry, CatalogReader};
b2065dc7
WB
48use pbs_datastore::data_blob::DataBlob;
49use pbs_datastore::data_blob_reader::DataBlobReader;
50use pbs_datastore::dynamic_index::{BufferedDynamicReader, DynamicIndexReader, LocalDynamicReadAt};
dc7a5b34 51use pbs_datastore::fixed_index::FixedIndexReader;
b2065dc7
WB
52use pbs_datastore::index::IndexFile;
53use pbs_datastore::manifest::{BackupManifest, CLIENT_LOG_BLOB_NAME, MANIFEST_BLOB_NAME};
89725197 54use pbs_datastore::prune::compute_prune_info;
dc7a5b34
TL
55use pbs_datastore::{
56 check_backup_owner, task_tracking, BackupDir, BackupGroup, DataStore, LocalChunkReader,
57 StoreProgress, CATALOG_NAME,
58};
8c74349b 59use pbs_tools::json::required_string_param;
dc7a5b34 60use proxmox_rest_server::{formatter, WorkerTask};
2b7f8dd5 61
133d718f 62use crate::api2::backup::optional_ns_param;
431cc7b1 63use crate::api2::node::rrd::create_value_from_rrd;
dc7a5b34 64use crate::backup::{verify_all_backups, verify_backup_dir, verify_backup_group, verify_filter};
54552dda 65
b9700a9f 66use crate::server::jobstate::Job;
804f6143 67
d6688884
SR
68const GROUP_NOTES_FILE_NAME: &str = "notes";
69
133d718f
WB
70fn get_group_note_path(
71 store: &DataStore,
72 ns: &BackupNamespace,
73 group: &pbs_api_types::BackupGroup,
74) -> PathBuf {
75 let mut note_path = store.group_path(ns, group);
d6688884
SR
76 note_path.push(GROUP_NOTES_FILE_NAME);
77 note_path
78}
79
7d6fc15b
TL
80// TODO: move somewhere we can reuse it from (namespace has its own copy atm.)
81fn get_ns_privs(store: &str, ns: &BackupNamespace, auth_id: &Authid) -> Result<u64, Error> {
82 let user_info = CachedUserInfo::new()?;
83
84 Ok(if ns.is_root() {
85 user_info.lookup_privs(auth_id, &["datastore", store])
86 } else {
87 user_info.lookup_privs(auth_id, &["datastore", store, &ns.to_string()])
88 })
89}
90
a724f5fd 91// for asserting a base priv existence but also returning the privs for more fine grained checking
7d6fc15b
TL
92// locally
93fn get_ns_privs_checked(
94 store: &str,
95 ns: &BackupNamespace,
96 auth_id: &Authid,
97 required_privs: u64,
98) -> Result<u64, Error> {
99 let privs = get_ns_privs(store, ns, auth_id)?;
100
101 if privs & required_privs == 0 {
102 proxmox_router::http_bail!(FORBIDDEN, "permission check failed");
103 }
104 Ok(privs)
105}
106
e7cb4dc5
WB
107fn read_backup_index(
108 store: &DataStore,
109 backup_dir: &BackupDir,
110) -> Result<(BackupManifest, Vec<BackupContent>), Error> {
ff86ef00 111 let (manifest, index_size) = store.load_manifest(backup_dir)?;
8c70e3eb 112
09b1f7b2
DM
113 let mut result = Vec::new();
114 for item in manifest.files() {
115 result.push(BackupContent {
116 filename: item.filename.clone(),
f28d9088 117 crypt_mode: Some(item.crypt_mode),
09b1f7b2
DM
118 size: Some(item.size),
119 });
8c70e3eb
DM
120 }
121
09b1f7b2 122 result.push(BackupContent {
96d65fbc 123 filename: MANIFEST_BLOB_NAME.to_string(),
882c0823
FG
124 crypt_mode: match manifest.signature {
125 Some(_) => Some(CryptMode::SignOnly),
126 None => Some(CryptMode::None),
127 },
09b1f7b2
DM
128 size: Some(index_size),
129 });
4f1e40a2 130
70030b43 131 Ok((manifest, result))
8c70e3eb
DM
132}
133
1c090810
DC
134fn get_all_snapshot_files(
135 store: &DataStore,
136 info: &BackupInfo,
70030b43 137) -> Result<(BackupManifest, Vec<BackupContent>), Error> {
9a37bd6c 138 let (manifest, mut files) = read_backup_index(store, &info.backup_dir)?;
1c090810
DC
139
140 let file_set = files.iter().fold(HashSet::new(), |mut acc, item| {
141 acc.insert(item.filename.clone());
142 acc
143 });
144
145 for file in &info.files {
dc7a5b34
TL
146 if file_set.contains(file) {
147 continue;
148 }
f28d9088
WB
149 files.push(BackupContent {
150 filename: file.to_string(),
151 size: None,
152 crypt_mode: None,
153 });
1c090810
DC
154 }
155
70030b43 156 Ok((manifest, files))
1c090810
DC
157}
158
b31c8019
DM
159#[api(
160 input: {
161 properties: {
162 store: {
163 schema: DATASTORE_SCHEMA,
164 },
89ae3c32
WB
165 "backup-ns": {
166 type: BackupNamespace,
167 optional: true,
168 },
b31c8019
DM
169 },
170 },
7b570c17 171 returns: pbs_api_types::ADMIN_DATASTORE_LIST_GROUPS_RETURN_TYPE,
bb34b589 172 access: {
7d6fc15b
TL
173 permission: &Permission::Anybody,
174 description: "Requires DATASTORE_AUDIT for all or DATASTORE_BACKUP for owned groups on \
175 /datastore/{store}[/{namespace}]",
bb34b589 176 },
b31c8019
DM
177)]
178/// List backup groups.
b2362a12 179pub fn list_groups(
b31c8019 180 store: String,
89ae3c32 181 backup_ns: Option<BackupNamespace>,
54552dda 182 rpcenv: &mut dyn RpcEnvironment,
b31c8019 183) -> Result<Vec<GroupListItem>, Error> {
e6dc35ac 184 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
7d6fc15b
TL
185
186 let backup_ns = backup_ns.unwrap_or_default();
187 let user_privs = get_ns_privs_checked(
188 &store,
189 &backup_ns,
190 &auth_id,
191 PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP,
192 )?;
54552dda 193
e9d2fc93 194 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Read))?;
0d08fcee
FG
195 let list_all = (user_privs & PRIV_DATASTORE_AUDIT) != 0;
196
249dde8b 197 datastore
133d718f 198 .iter_backup_groups(backup_ns.clone())? // FIXME: Namespaces and recursion parameters!
249dde8b
TL
199 .try_fold(Vec::new(), |mut group_info, group| {
200 let group = group?;
133d718f 201 let owner = match datastore.get_owner(&backup_ns, group.as_ref()) {
249dde8b
TL
202 Ok(auth_id) => auth_id,
203 Err(err) => {
204 let id = &store;
205 eprintln!("Failed to get owner of group '{}/{}' - {}", id, group, err);
206 return Ok(group_info);
dc7a5b34 207 }
249dde8b
TL
208 };
209 if !list_all && check_backup_owner(&owner, &auth_id).is_err() {
210 return Ok(group_info);
211 }
0d08fcee 212
6da20161 213 let snapshots = match group.list_backups() {
249dde8b
TL
214 Ok(snapshots) => snapshots,
215 Err(_) => return Ok(group_info),
216 };
0d08fcee 217
249dde8b
TL
218 let backup_count: u64 = snapshots.len() as u64;
219 if backup_count == 0 {
220 return Ok(group_info);
221 }
0d08fcee 222
249dde8b
TL
223 let last_backup = snapshots
224 .iter()
225 .fold(&snapshots[0], |a, b| {
226 if a.is_finished() && a.backup_dir.backup_time() > b.backup_dir.backup_time() {
227 a
228 } else {
229 b
230 }
231 })
232 .to_owned();
233
133d718f 234 let note_path = get_group_note_path(&datastore, &backup_ns, group.as_ref());
249dde8b
TL
235 let comment = file_read_firstline(&note_path).ok();
236
237 group_info.push(GroupListItem {
988d575d 238 backup: group.into(),
249dde8b
TL
239 last_backup: last_backup.backup_dir.backup_time(),
240 owner: Some(owner),
241 backup_count,
242 files: last_backup.files,
243 comment,
0d08fcee
FG
244 });
245
249dde8b
TL
246 Ok(group_info)
247 })
812c6f87 248}
8f579717 249
f32791b4
DC
250#[api(
251 input: {
252 properties: {
988d575d 253 store: { schema: DATASTORE_SCHEMA },
133d718f
WB
254 "backup-ns": {
255 type: BackupNamespace,
256 optional: true,
257 },
8c74349b
WB
258 group: {
259 type: pbs_api_types::BackupGroup,
260 flatten: true,
261 },
f32791b4
DC
262 },
263 },
264 access: {
7d6fc15b
TL
265 permission: &Permission::Anybody,
266 description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any\
267 or DATASTORE_PRUNE and being the owner of the group",
f32791b4
DC
268 },
269)]
270/// Delete backup group including all snapshots.
271pub fn delete_group(
272 store: String,
133d718f 273 backup_ns: Option<BackupNamespace>,
8c74349b 274 group: pbs_api_types::BackupGroup,
f32791b4
DC
275 _info: &ApiMethod,
276 rpcenv: &mut dyn RpcEnvironment,
277) -> Result<Value, Error> {
f32791b4
DC
278 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
279
133d718f
WB
280 let backup_ns = backup_ns.unwrap_or_default();
281
a724f5fd 282 let user_privs = get_ns_privs_checked(
7d6fc15b 283 &store,
133d718f 284 &backup_ns,
7d6fc15b
TL
285 &auth_id,
286 PRIV_DATASTORE_MODIFY | PRIV_DATASTORE_PRUNE,
287 )?;
288
e9d2fc93 289 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Write))?;
f32791b4 290
a724f5fd
FG
291 if user_privs & PRIV_DATASTORE_MODIFY == 0 {
292 let owner = datastore.get_owner(&backup_ns, &group)?;
293 check_backup_owner(&owner, &auth_id)?;
294 }
f32791b4 295
133d718f 296 if !datastore.remove_backup_group(&backup_ns, &group)? {
171a00ca 297 bail!("group only partially deleted due to protected snapshots");
5cc7d891 298 }
f32791b4
DC
299
300 Ok(Value::Null)
301}
302
09b1f7b2
DM
303#[api(
304 input: {
305 properties: {
988d575d 306 store: { schema: DATASTORE_SCHEMA },
133d718f
WB
307 "backup-ns": {
308 type: BackupNamespace,
309 optional: true,
310 },
8c74349b
WB
311 backup_dir: {
312 type: pbs_api_types::BackupDir,
313 flatten: true,
314 },
09b1f7b2
DM
315 },
316 },
7b570c17 317 returns: pbs_api_types::ADMIN_DATASTORE_LIST_SNAPSHOT_FILES_RETURN_TYPE,
bb34b589 318 access: {
7d6fc15b
TL
319 permission: &Permission::Anybody,
320 description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_AUDIT or \
321 DATASTORE_READ for any or DATASTORE_BACKUP and being the owner of the group",
bb34b589 322 },
09b1f7b2
DM
323)]
324/// List snapshot files.
ea5f547f 325pub fn list_snapshot_files(
09b1f7b2 326 store: String,
133d718f 327 backup_ns: Option<BackupNamespace>,
8c74349b 328 backup_dir: pbs_api_types::BackupDir,
01a13423 329 _info: &ApiMethod,
54552dda 330 rpcenv: &mut dyn RpcEnvironment,
09b1f7b2 331) -> Result<Vec<BackupContent>, Error> {
e6dc35ac 332 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
7d6fc15b 333
133d718f
WB
334 let backup_ns = backup_ns.unwrap_or_default();
335
a724f5fd 336 let user_privs = get_ns_privs_checked(
7d6fc15b 337 &store,
133d718f 338 &backup_ns,
7d6fc15b
TL
339 &auth_id,
340 PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP,
341 )?;
342
e9d2fc93 343 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Read))?;
54552dda 344
a724f5fd
FG
345 if user_privs & (PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_READ) == 0 {
346 let owner = datastore.get_owner(&backup_ns, &backup_dir.group)?;
347 check_backup_owner(&owner, &auth_id)?;
348 }
01a13423 349
a724f5fd 350 let snapshot = datastore.backup_dir(backup_ns, backup_dir)?;
54552dda 351
6da20161 352 let info = BackupInfo::new(snapshot)?;
01a13423 353
70030b43
DM
354 let (_manifest, files) = get_all_snapshot_files(&datastore, &info)?;
355
356 Ok(files)
01a13423
DM
357}
358
68a6a0ee
DM
359#[api(
360 input: {
361 properties: {
988d575d 362 store: { schema: DATASTORE_SCHEMA },
133d718f
WB
363 "backup-ns": {
364 type: BackupNamespace,
365 optional: true,
366 },
8c74349b
WB
367 backup_dir: {
368 type: pbs_api_types::BackupDir,
369 flatten: true,
370 },
68a6a0ee
DM
371 },
372 },
bb34b589 373 access: {
7d6fc15b
TL
374 permission: &Permission::Anybody,
375 description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any\
376 or DATASTORE_PRUNE and being the owner of the group",
bb34b589 377 },
68a6a0ee
DM
378)]
379/// Delete backup snapshot.
bf78f708 380pub fn delete_snapshot(
68a6a0ee 381 store: String,
133d718f 382 backup_ns: Option<BackupNamespace>,
8c74349b 383 backup_dir: pbs_api_types::BackupDir,
6f62c924 384 _info: &ApiMethod,
54552dda 385 rpcenv: &mut dyn RpcEnvironment,
6f62c924 386) -> Result<Value, Error> {
e6dc35ac 387 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
54552dda 388
133d718f
WB
389 let backup_ns = backup_ns.unwrap_or_default();
390
a724f5fd 391 let user_privs = get_ns_privs_checked(
7d6fc15b 392 &store,
133d718f 393 &backup_ns,
7d6fc15b
TL
394 &auth_id,
395 PRIV_DATASTORE_MODIFY | PRIV_DATASTORE_PRUNE,
396 )?;
397
e9d2fc93 398 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Write))?;
6f62c924 399
a724f5fd
FG
400 if user_privs & PRIV_DATASTORE_MODIFY == 0 {
401 let owner = datastore.get_owner(&backup_ns, &backup_dir.group)?;
402 check_backup_owner(&owner, &auth_id)?;
403 }
404
405 let snapshot = datastore.backup_dir(backup_ns, backup_dir)?;
54552dda 406
133d718f 407 snapshot.destroy(false)?;
6f62c924
DM
408
409 Ok(Value::Null)
410}
411
fc189b19 412#[api(
b7c3eaa9 413 streaming: true,
fc189b19
DM
414 input: {
415 properties: {
988d575d 416 store: { schema: DATASTORE_SCHEMA },
8c74349b
WB
417 "backup-ns": {
418 type: BackupNamespace,
419 optional: true,
420 },
fc189b19
DM
421 "backup-type": {
422 optional: true,
988d575d 423 type: BackupType,
fc189b19
DM
424 },
425 "backup-id": {
426 optional: true,
427 schema: BACKUP_ID_SCHEMA,
428 },
429 },
430 },
7b570c17 431 returns: pbs_api_types::ADMIN_DATASTORE_LIST_SNAPSHOTS_RETURN_TYPE,
bb34b589 432 access: {
7d6fc15b
TL
433 permission: &Permission::Anybody,
434 description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_AUDIT for any \
435 or DATASTORE_BACKUP and being the owner of the group",
bb34b589 436 },
fc189b19
DM
437)]
438/// List backup snapshots.
dc7a5b34 439pub fn list_snapshots(
54552dda 440 store: String,
8c74349b 441 backup_ns: Option<BackupNamespace>,
988d575d 442 backup_type: Option<BackupType>,
54552dda
DM
443 backup_id: Option<String>,
444 _param: Value,
184f17af 445 _info: &ApiMethod,
54552dda 446 rpcenv: &mut dyn RpcEnvironment,
fc189b19 447) -> Result<Vec<SnapshotListItem>, Error> {
e6dc35ac 448 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
7d6fc15b
TL
449
450 let backup_ns = backup_ns.unwrap_or_default();
451
452 let user_privs = get_ns_privs_checked(
453 &store,
454 &backup_ns,
455 &auth_id,
456 PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP,
457 )?;
184f17af 458
0d08fcee
FG
459 let list_all = (user_privs & PRIV_DATASTORE_AUDIT) != 0;
460
e9d2fc93 461 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Read))?;
184f17af 462
249dde8b
TL
463 // FIXME: filter also owner before collecting, for doing that nicely the owner should move into
464 // backup group and provide an error free (Err -> None) accessor
0d08fcee 465 let groups = match (backup_type, backup_id) {
db87d93e 466 (Some(backup_type), Some(backup_id)) => {
8c74349b 467 vec![datastore.backup_group_from_parts(backup_ns, backup_type, backup_id)]
db87d93e 468 }
8c74349b 469 // FIXME: Recursion
7d9cb8c4 470 (Some(backup_type), None) => datastore
8c74349b 471 .iter_backup_groups_ok(backup_ns)?
dc7a5b34
TL
472 .filter(|group| group.backup_type() == backup_type)
473 .collect(),
8c74349b 474 // FIXME: Recursion
7d9cb8c4 475 (None, Some(backup_id)) => datastore
8c74349b 476 .iter_backup_groups_ok(backup_ns)?
dc7a5b34
TL
477 .filter(|group| group.backup_id() == backup_id)
478 .collect(),
8c74349b
WB
479 // FIXME: Recursion
480 (None, None) => datastore.list_backup_groups(backup_ns)?,
0d08fcee 481 };
54552dda 482
0d08fcee 483 let info_to_snapshot_list_item = |group: &BackupGroup, owner, info: BackupInfo| {
988d575d
WB
484 let backup = pbs_api_types::BackupDir {
485 group: group.into(),
486 time: info.backup_dir.backup_time(),
487 };
6da20161 488 let protected = info.backup_dir.is_protected();
1c090810 489
79c53595 490 match get_all_snapshot_files(&datastore, &info) {
70030b43 491 Ok((manifest, files)) => {
70030b43
DM
492 // extract the first line from notes
493 let comment: Option<String> = manifest.unprotected["notes"]
494 .as_str()
495 .and_then(|notes| notes.lines().next())
496 .map(String::from);
497
035c40e6
FG
498 let fingerprint = match manifest.fingerprint() {
499 Ok(fp) => fp,
500 Err(err) => {
501 eprintln!("error parsing fingerprint: '{}'", err);
502 None
dc7a5b34 503 }
035c40e6
FG
504 };
505
79c53595 506 let verification = manifest.unprotected["verify_state"].clone();
dc7a5b34
TL
507 let verification: Option<SnapshotVerifyState> =
508 match serde_json::from_value(verification) {
509 Ok(verify) => verify,
510 Err(err) => {
511 eprintln!("error parsing verification state : '{}'", err);
512 None
513 }
514 };
3b2046d2 515
0d08fcee
FG
516 let size = Some(files.iter().map(|x| x.size.unwrap_or(0)).sum());
517
79c53595 518 SnapshotListItem {
988d575d 519 backup,
79c53595
FG
520 comment,
521 verification,
035c40e6 522 fingerprint,
79c53595
FG
523 files,
524 size,
525 owner,
02db7267 526 protected,
79c53595 527 }
dc7a5b34 528 }
1c090810
DC
529 Err(err) => {
530 eprintln!("error during snapshot file listing: '{}'", err);
79c53595 531 let files = info
dc7a5b34
TL
532 .files
533 .into_iter()
534 .map(|filename| BackupContent {
535 filename,
536 size: None,
537 crypt_mode: None,
538 })
539 .collect();
79c53595
FG
540
541 SnapshotListItem {
988d575d 542 backup,
79c53595
FG
543 comment: None,
544 verification: None,
035c40e6 545 fingerprint: None,
79c53595
FG
546 files,
547 size: None,
548 owner,
02db7267 549 protected,
79c53595 550 }
dc7a5b34 551 }
0d08fcee
FG
552 }
553 };
184f17af 554
dc7a5b34 555 groups.iter().try_fold(Vec::new(), |mut snapshots, group| {
133d718f 556 let owner = match group.get_owner() {
dc7a5b34
TL
557 Ok(auth_id) => auth_id,
558 Err(err) => {
559 eprintln!(
560 "Failed to get owner of group '{}/{}' - {}",
561 &store, group, err
562 );
0d08fcee
FG
563 return Ok(snapshots);
564 }
dc7a5b34 565 };
0d08fcee 566
dc7a5b34
TL
567 if !list_all && check_backup_owner(&owner, &auth_id).is_err() {
568 return Ok(snapshots);
569 }
0d08fcee 570
6da20161 571 let group_backups = group.list_backups()?;
0d08fcee 572
dc7a5b34
TL
573 snapshots.extend(
574 group_backups
575 .into_iter()
576 .map(|info| info_to_snapshot_list_item(group, Some(owner.clone()), info)),
577 );
578
579 Ok(snapshots)
580 })
184f17af
DM
581}
582
6da20161
WB
583fn get_snapshots_count(
584 store: &Arc<DataStore>,
585 filter_owner: Option<&Authid>,
586) -> Result<Counts, Error> {
7d9cb8c4 587 store
8c74349b 588 .iter_backup_groups_ok(Default::default())? // FIXME: Recurse!
fdfcb74d 589 .filter(|group| {
133d718f
WB
590 // FIXME: namespace:
591 let owner = match store.get_owner(&BackupNamespace::root(), group.as_ref()) {
fdfcb74d
FG
592 Ok(owner) => owner,
593 Err(err) => {
72f81545
TL
594 let id = store.name();
595 eprintln!("Failed to get owner of group '{}/{}' - {}", id, group, err);
fdfcb74d 596 return false;
dc7a5b34 597 }
fdfcb74d 598 };
14e08625 599
fdfcb74d
FG
600 match filter_owner {
601 Some(filter) => check_backup_owner(&owner, filter).is_ok(),
602 None => true,
603 }
604 })
605 .try_fold(Counts::default(), |mut counts, group| {
6da20161 606 let snapshot_count = group.list_backups()?.len() as u64;
fdfcb74d 607
72f81545 608 // only include groups with snapshots, counting/displaying emtpy groups can confuse
b44483a8
DM
609 if snapshot_count > 0 {
610 let type_count = match group.backup_type() {
988d575d
WB
611 BackupType::Ct => counts.ct.get_or_insert(Default::default()),
612 BackupType::Vm => counts.vm.get_or_insert(Default::default()),
613 BackupType::Host => counts.host.get_or_insert(Default::default()),
b44483a8 614 };
14e08625 615
b44483a8
DM
616 type_count.groups += 1;
617 type_count.snapshots += snapshot_count;
618 }
16f9f244 619
fdfcb74d
FG
620 Ok(counts)
621 })
16f9f244
DC
622}
623
1dc117bb
DM
624#[api(
625 input: {
626 properties: {
627 store: {
628 schema: DATASTORE_SCHEMA,
629 },
98afc7b1
FG
630 verbose: {
631 type: bool,
632 default: false,
633 optional: true,
634 description: "Include additional information like snapshot counts and GC status.",
635 },
1dc117bb 636 },
98afc7b1 637
1dc117bb
DM
638 },
639 returns: {
14e08625 640 type: DataStoreStatus,
1dc117bb 641 },
bb34b589 642 access: {
7d6fc15b
TL
643 permission: &Permission::Privilege(
644 &["datastore", "{store}"], PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP, true),
bb34b589 645 },
1dc117bb
DM
646)]
647/// Get datastore status.
ea5f547f 648pub fn status(
1dc117bb 649 store: String,
98afc7b1 650 verbose: bool,
0eecf38f 651 _info: &ApiMethod,
fdfcb74d 652 rpcenv: &mut dyn RpcEnvironment,
14e08625 653) -> Result<DataStoreStatus, Error> {
e9d2fc93 654 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Read))?;
14e08625 655 let storage = crate::tools::disks::disk_usage(&datastore.base_path())?;
fdfcb74d
FG
656 let (counts, gc_status) = if verbose {
657 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
658 let user_info = CachedUserInfo::new()?;
659
660 let store_privs = user_info.lookup_privs(&auth_id, &["datastore", &store]);
661 let filter_owner = if store_privs & PRIV_DATASTORE_AUDIT != 0 {
662 None
663 } else {
664 Some(&auth_id)
665 };
666
667 let counts = Some(get_snapshots_count(&datastore, filter_owner)?);
668 let gc_status = Some(datastore.last_gc_status());
669
670 (counts, gc_status)
671 } else {
672 (None, None)
98afc7b1 673 };
16f9f244 674
14e08625
DC
675 Ok(DataStoreStatus {
676 total: storage.total,
677 used: storage.used,
678 avail: storage.avail,
679 gc_status,
680 counts,
681 })
0eecf38f
DM
682}
683
c2009e53
DM
684#[api(
685 input: {
686 properties: {
687 store: {
688 schema: DATASTORE_SCHEMA,
689 },
8c74349b
WB
690 "backup-ns": {
691 type: BackupNamespace,
692 optional: true,
693 },
c2009e53 694 "backup-type": {
988d575d 695 type: BackupType,
c2009e53
DM
696 optional: true,
697 },
698 "backup-id": {
699 schema: BACKUP_ID_SCHEMA,
700 optional: true,
701 },
dcbf29e7
HL
702 "ignore-verified": {
703 schema: IGNORE_VERIFIED_BACKUPS_SCHEMA,
704 optional: true,
705 },
706 "outdated-after": {
707 schema: VERIFICATION_OUTDATED_AFTER_SCHEMA,
708 optional: true,
709 },
c2009e53
DM
710 "backup-time": {
711 schema: BACKUP_TIME_SCHEMA,
712 optional: true,
713 },
714 },
715 },
716 returns: {
717 schema: UPID_SCHEMA,
718 },
719 access: {
7d6fc15b
TL
720 permission: &Permission::Anybody,
721 description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_VERIFY for any \
722 or DATASTORE_BACKUP and being the owner of the group",
c2009e53
DM
723 },
724)]
725/// Verify backups.
726///
727/// This function can verify a single backup snapshot, all backup from a backup group,
728/// or all backups in the datastore.
729pub fn verify(
730 store: String,
8c74349b 731 backup_ns: Option<BackupNamespace>,
988d575d 732 backup_type: Option<BackupType>,
c2009e53
DM
733 backup_id: Option<String>,
734 backup_time: Option<i64>,
dcbf29e7
HL
735 ignore_verified: Option<bool>,
736 outdated_after: Option<i64>,
c2009e53
DM
737 rpcenv: &mut dyn RpcEnvironment,
738) -> Result<Value, Error> {
7d6fc15b
TL
739 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
740 let backup_ns = backup_ns.unwrap_or_default();
a724f5fd 741 let user_privs = get_ns_privs_checked(
7d6fc15b
TL
742 &store,
743 &backup_ns,
744 &auth_id,
745 PRIV_DATASTORE_VERIFY | PRIV_DATASTORE_BACKUP,
746 )?;
a724f5fd
FG
747 let owner_check_required = user_privs & PRIV_DATASTORE_VERIFY == 0;
748
e9d2fc93 749 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Read))?;
dcbf29e7 750 let ignore_verified = ignore_verified.unwrap_or(true);
c2009e53 751
8ea00f6e 752 let worker_id;
c2009e53
DM
753
754 let mut backup_dir = None;
755 let mut backup_group = None;
133042b5 756 let mut worker_type = "verify";
c2009e53 757
8c74349b
WB
758 // FIXME: Recursion
759 // FIXME: Namespaces and worker ID, could this be an issue?
c2009e53
DM
760 match (backup_type, backup_id, backup_time) {
761 (Some(backup_type), Some(backup_id), Some(backup_time)) => {
dc7a5b34 762 worker_id = format!(
8c74349b
WB
763 "{}:{}/{}/{}/{:08X}",
764 store,
765 backup_ns.display_as_path(),
766 backup_type,
767 backup_id,
768 backup_time
dc7a5b34 769 );
8c74349b
WB
770 let dir =
771 datastore.backup_dir_from_parts(backup_ns, backup_type, backup_id, backup_time)?;
09f6a240 772
a724f5fd
FG
773 if owner_check_required {
774 let owner = datastore.get_owner(dir.backup_ns(), dir.as_ref())?;
775 check_backup_owner(&owner, &auth_id)?;
776 }
09f6a240 777
c2009e53 778 backup_dir = Some(dir);
133042b5 779 worker_type = "verify_snapshot";
c2009e53
DM
780 }
781 (Some(backup_type), Some(backup_id), None) => {
8c74349b
WB
782 worker_id = format!(
783 "{}:{}/{}/{}",
784 store,
785 backup_ns.display_as_path(),
786 backup_type,
787 backup_id
788 );
133d718f 789 let group = pbs_api_types::BackupGroup::from((backup_type, backup_id));
09f6a240 790
a724f5fd
FG
791 if owner_check_required {
792 let owner = datastore.get_owner(&backup_ns, &group)?;
793 check_backup_owner(&owner, &auth_id)?;
794 }
09f6a240 795
133d718f 796 backup_group = Some(datastore.backup_group(backup_ns, group));
133042b5 797 worker_type = "verify_group";
c2009e53
DM
798 }
799 (None, None, None) => {
8ea00f6e 800 worker_id = store.clone();
c2009e53 801 }
5a718dce 802 _ => bail!("parameters do not specify a backup group or snapshot"),
c2009e53
DM
803 }
804
39735609 805 let to_stdout = rpcenv.env_type() == RpcEnvironmentType::CLI;
c2009e53
DM
806
807 let upid_str = WorkerTask::new_thread(
133042b5 808 worker_type,
44288184 809 Some(worker_id),
049a22a3 810 auth_id.to_string(),
e7cb4dc5
WB
811 to_stdout,
812 move |worker| {
9c26a3d6 813 let verify_worker = crate::backup::VerifyWorker::new(worker.clone(), datastore);
adfdc369 814 let failed_dirs = if let Some(backup_dir) = backup_dir {
adfdc369 815 let mut res = Vec::new();
f6b1d1cc 816 if !verify_backup_dir(
9c26a3d6 817 &verify_worker,
f6b1d1cc 818 &backup_dir,
f6b1d1cc 819 worker.upid().clone(),
dc7a5b34 820 Some(&move |manifest| verify_filter(ignore_verified, outdated_after, manifest)),
f6b1d1cc 821 )? {
adfdc369
DC
822 res.push(backup_dir.to_string());
823 }
824 res
c2009e53 825 } else if let Some(backup_group) = backup_group {
7e25b9aa 826 let failed_dirs = verify_backup_group(
9c26a3d6 827 &verify_worker,
63d9aca9 828 &backup_group,
7e25b9aa 829 &mut StoreProgress::new(1),
f6b1d1cc 830 worker.upid(),
dc7a5b34 831 Some(&move |manifest| verify_filter(ignore_verified, outdated_after, manifest)),
63d9aca9
DM
832 )?;
833 failed_dirs
c2009e53 834 } else {
a724f5fd 835 let owner = if owner_check_required {
09f6a240
FG
836 Some(auth_id)
837 } else {
838 None
839 };
840
a724f5fd
FG
841 // FIXME namespace missing here..
842
dcbf29e7
HL
843 verify_all_backups(
844 &verify_worker,
845 worker.upid(),
846 owner,
dc7a5b34 847 Some(&move |manifest| verify_filter(ignore_verified, outdated_after, manifest)),
dcbf29e7 848 )?
c2009e53 849 };
3984a5fd 850 if !failed_dirs.is_empty() {
1ec0d70d 851 task_log!(worker, "Failed to verify the following snapshots/groups:");
adfdc369 852 for dir in failed_dirs {
1ec0d70d 853 task_log!(worker, "\t{}", dir);
adfdc369 854 }
1ffe0301 855 bail!("verification failed - please check the log for details");
c2009e53
DM
856 }
857 Ok(())
e7cb4dc5
WB
858 },
859 )?;
c2009e53
DM
860
861 Ok(json!(upid_str))
862}
863
0a240aaa
DC
864#[api(
865 input: {
866 properties: {
133d718f
WB
867 "backup-ns": {
868 type: BackupNamespace,
869 optional: true,
870 },
8c74349b
WB
871 group: {
872 type: pbs_api_types::BackupGroup,
873 flatten: true,
874 },
0a240aaa
DC
875 "dry-run": {
876 optional: true,
877 type: bool,
878 default: false,
879 description: "Just show what prune would do, but do not delete anything.",
880 },
881 "prune-options": {
882 type: PruneOptions,
883 flatten: true,
884 },
885 store: {
886 schema: DATASTORE_SCHEMA,
887 },
888 },
889 },
7b570c17 890 returns: pbs_api_types::ADMIN_DATASTORE_PRUNE_RETURN_TYPE,
0a240aaa 891 access: {
7d6fc15b
TL
892 permission: &Permission::Anybody,
893 description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any\
894 or DATASTORE_PRUNE and being the owner of the group",
0a240aaa
DC
895 },
896)]
9805207a 897/// Prune a group on the datastore
bf78f708 898pub fn prune(
133d718f 899 backup_ns: Option<BackupNamespace>,
8c74349b 900 group: pbs_api_types::BackupGroup,
0a240aaa
DC
901 dry_run: bool,
902 prune_options: PruneOptions,
903 store: String,
904 _param: Value,
54552dda 905 rpcenv: &mut dyn RpcEnvironment,
83b7db02 906) -> Result<Value, Error> {
e6dc35ac 907 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
133d718f
WB
908
909 let backup_ns = backup_ns.unwrap_or_default();
910
a724f5fd 911 let user_privs = get_ns_privs_checked(
7d6fc15b 912 &store,
133d718f 913 &backup_ns,
7d6fc15b
TL
914 &auth_id,
915 PRIV_DATASTORE_MODIFY | PRIV_DATASTORE_PRUNE,
916 )?;
54552dda 917
e9d2fc93 918 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Write))?;
54552dda 919
a724f5fd
FG
920 if user_privs & PRIV_DATASTORE_MODIFY == 0 {
921 let owner = datastore.get_owner(&backup_ns, &group)?;
922 check_backup_owner(&owner, &auth_id)?;
923 }
db87d93e 924
a724f5fd 925 let group = datastore.backup_group(backup_ns, group);
83b7db02 926
8c74349b 927 let worker_id = format!("{}:{}", store, group);
503995c7 928
dda70154
DM
929 let mut prune_result = Vec::new();
930
6da20161 931 let list = group.list_backups()?;
dda70154
DM
932
933 let mut prune_info = compute_prune_info(list, &prune_options)?;
934
935 prune_info.reverse(); // delete older snapshots first
936
89725197 937 let keep_all = !pbs_datastore::prune::keeps_something(&prune_options);
dda70154
DM
938
939 if dry_run {
02db7267
DC
940 for (info, mark) in prune_info {
941 let keep = keep_all || mark.keep();
dda70154 942
33f2c2a1 943 let mut result = json!({
db87d93e
WB
944 "backup-type": info.backup_dir.backup_type(),
945 "backup-id": info.backup_dir.backup_id(),
946 "backup-time": info.backup_dir.backup_time(),
dda70154 947 "keep": keep,
02db7267 948 "protected": mark.protected(),
33f2c2a1
WB
949 });
950 let ns = info.backup_dir.backup_ns();
951 if !ns.is_root() {
952 result["backup-ns"] = serde_json::to_value(ns)?;
953 }
954 prune_result.push(result);
dda70154
DM
955 }
956 return Ok(json!(prune_result));
957 }
958
163e9bbe 959 // We use a WorkerTask just to have a task log, but run synchrounously
049a22a3 960 let worker = WorkerTask::new("prune", Some(worker_id), auth_id.to_string(), true)?;
dda70154 961
f1539300 962 if keep_all {
1ec0d70d 963 task_log!(worker, "No prune selection - keeping all files.");
f1539300 964 } else {
dc7a5b34
TL
965 task_log!(
966 worker,
967 "retention options: {}",
968 pbs_datastore::prune::cli_options_string(&prune_options)
969 );
970 task_log!(
971 worker,
8c74349b 972 "Starting prune on store \"{}\" group \"{}\"",
dc7a5b34 973 store,
8c74349b 974 group,
dc7a5b34 975 );
f1539300 976 }
3b03abfe 977
02db7267
DC
978 for (info, mark) in prune_info {
979 let keep = keep_all || mark.keep();
dda70154 980
f1539300
SR
981 let backup_time = info.backup_dir.backup_time();
982 let timestamp = info.backup_dir.backup_time_string();
db87d93e
WB
983 let group: &pbs_api_types::BackupGroup = info.backup_dir.as_ref();
984
985 let msg = format!("{}/{}/{} {}", group.ty, group.id, timestamp, mark,);
f1539300 986
1ec0d70d 987 task_log!(worker, "{}", msg);
f1539300 988
133d718f 989 prune_result.push(json!({
db87d93e
WB
990 "backup-type": group.ty,
991 "backup-id": group.id,
f1539300
SR
992 "backup-time": backup_time,
993 "keep": keep,
02db7267 994 "protected": mark.protected(),
133d718f 995 }));
f1539300
SR
996
997 if !(dry_run || keep) {
133d718f 998 if let Err(err) = info.backup_dir.destroy(false) {
1ec0d70d
DM
999 task_warn!(
1000 worker,
1001 "failed to remove dir {:?}: {}",
1002 info.backup_dir.relative_path(),
1003 err,
f1539300 1004 );
8f0b4c1f 1005 }
8f579717 1006 }
f1539300 1007 }
dd8e744f 1008
f1539300 1009 worker.log_result(&Ok(()));
83b7db02 1010
dda70154 1011 Ok(json!(prune_result))
83b7db02
DM
1012}
1013
9805207a
DC
1014#[api(
1015 input: {
1016 properties: {
1017 "dry-run": {
1018 optional: true,
1019 type: bool,
1020 default: false,
1021 description: "Just show what prune would do, but do not delete anything.",
1022 },
1023 "prune-options": {
1024 type: PruneOptions,
1025 flatten: true,
1026 },
1027 store: {
1028 schema: DATASTORE_SCHEMA,
1029 },
2f5417f8
TL
1030 ns: {
1031 type: BackupNamespace,
1032 optional: true,
1033 },
9805207a
DC
1034 },
1035 },
1036 returns: {
1037 schema: UPID_SCHEMA,
1038 },
1039 access: {
7d6fc15b
TL
1040 permission: &Permission::Privilege(
1041 &["datastore", "{store}"], PRIV_DATASTORE_MODIFY | PRIV_DATASTORE_PRUNE, true),
9805207a
DC
1042 },
1043)]
1044/// Prune the datastore
1045pub fn prune_datastore(
1046 dry_run: bool,
1047 prune_options: PruneOptions,
1048 store: String,
2f5417f8 1049 ns: Option<BackupNamespace>,
9805207a
DC
1050 _param: Value,
1051 rpcenv: &mut dyn RpcEnvironment,
1052) -> Result<String, Error> {
9805207a
DC
1053 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
1054
e9d2fc93 1055 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Write))?;
9805207a 1056
bfa942c0
DC
1057 let to_stdout = rpcenv.env_type() == RpcEnvironmentType::CLI;
1058
7d6fc15b
TL
1059 // FIXME: also allow a per-namespace pruning with max-depth
1060
9805207a
DC
1061 let upid_str = WorkerTask::new_thread(
1062 "prune",
1063 Some(store.clone()),
049a22a3 1064 auth_id.to_string(),
bfa942c0 1065 to_stdout,
dc7a5b34
TL
1066 move |worker| {
1067 crate::server::prune_datastore(
1068 worker,
1069 auth_id,
1070 prune_options,
dc7a5b34 1071 datastore,
2f5417f8 1072 ns.unwrap_or_default(),
dc7a5b34
TL
1073 dry_run,
1074 )
1075 },
9805207a
DC
1076 )?;
1077
1078 Ok(upid_str)
1079}
1080
dfc58d47
DM
1081#[api(
1082 input: {
1083 properties: {
1084 store: {
1085 schema: DATASTORE_SCHEMA,
1086 },
1087 },
1088 },
1089 returns: {
1090 schema: UPID_SCHEMA,
1091 },
bb34b589 1092 access: {
54552dda 1093 permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_MODIFY, false),
bb34b589 1094 },
dfc58d47
DM
1095)]
1096/// Start garbage collection.
bf78f708 1097pub fn start_garbage_collection(
dfc58d47 1098 store: String,
6049b71f 1099 _info: &ApiMethod,
dd5495d6 1100 rpcenv: &mut dyn RpcEnvironment,
6049b71f 1101) -> Result<Value, Error> {
e9d2fc93 1102 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Write))?;
e6dc35ac 1103 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
15e9b4ed 1104
dc7a5b34 1105 let job = Job::new("garbage_collection", &store)
4fdf5ddf 1106 .map_err(|_| format_err!("garbage collection already running"))?;
15e9b4ed 1107
39735609 1108 let to_stdout = rpcenv.env_type() == RpcEnvironmentType::CLI;
15e9b4ed 1109
dc7a5b34
TL
1110 let upid_str =
1111 crate::server::do_garbage_collection_job(job, datastore, &auth_id, None, to_stdout)
1112 .map_err(|err| {
1113 format_err!(
1114 "unable to start garbage collection job on datastore {} - {}",
1115 store,
1116 err
1117 )
1118 })?;
0f778e06
DM
1119
1120 Ok(json!(upid_str))
15e9b4ed
DM
1121}
1122
a92830dc
DM
1123#[api(
1124 input: {
1125 properties: {
1126 store: {
1127 schema: DATASTORE_SCHEMA,
1128 },
1129 },
1130 },
1131 returns: {
1132 type: GarbageCollectionStatus,
bb34b589
DM
1133 },
1134 access: {
1135 permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_AUDIT, false),
1136 },
a92830dc
DM
1137)]
1138/// Garbage collection status.
5eeea607 1139pub fn garbage_collection_status(
a92830dc 1140 store: String,
6049b71f 1141 _info: &ApiMethod,
dd5495d6 1142 _rpcenv: &mut dyn RpcEnvironment,
a92830dc 1143) -> Result<GarbageCollectionStatus, Error> {
e9d2fc93 1144 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Read))?;
f2b99c34 1145
f2b99c34 1146 let status = datastore.last_gc_status();
691c89a0 1147
a92830dc 1148 Ok(status)
691c89a0
DM
1149}
1150
7d6fc15b
TL
1151fn can_access_any_ns(store: Arc<DataStore>, auth_id: &Authid, user_info: &CachedUserInfo) -> bool {
1152 // NOTE: traversing the datastore could be avoided if we had an "ACL tree: is there any priv
1153 // below /datastore/{store}" helper
1154 let mut iter =
1155 if let Ok(iter) = store.recursive_iter_backup_ns_ok(BackupNamespace::root(), None) {
1156 iter
1157 } else {
1158 return false;
1159 };
1160 let wanted =
1161 PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_MODIFY | PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP;
1162 let name = store.name();
1163 iter.any(|ns| -> bool {
1164 let user_privs = user_info.lookup_privs(&auth_id, &["datastore", name, &ns.to_string()]);
1165 user_privs & wanted != 0
1166 })
1167}
1168
bb34b589 1169#[api(
30fb6025
DM
1170 returns: {
1171 description: "List the accessible datastores.",
1172 type: Array,
9b93c620 1173 items: { type: DataStoreListItem },
30fb6025 1174 },
bb34b589 1175 access: {
54552dda 1176 permission: &Permission::Anybody,
bb34b589
DM
1177 },
1178)]
1179/// Datastore list
bf78f708 1180pub fn get_datastore_list(
6049b71f
DM
1181 _param: Value,
1182 _info: &ApiMethod,
54552dda 1183 rpcenv: &mut dyn RpcEnvironment,
455e5f71 1184) -> Result<Vec<DataStoreListItem>, Error> {
e7d4be9d 1185 let (config, _digest) = pbs_config::datastore::config()?;
15e9b4ed 1186
e6dc35ac 1187 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
54552dda
DM
1188 let user_info = CachedUserInfo::new()?;
1189
30fb6025 1190 let mut list = Vec::new();
54552dda 1191
30fb6025 1192 for (store, (_, data)) in &config.sections {
9a37bd6c 1193 let user_privs = user_info.lookup_privs(&auth_id, &["datastore", store]);
dc7a5b34 1194 let allowed = (user_privs & (PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP)) != 0;
7d6fc15b
TL
1195
1196 let mut allow_id = false;
1197 if !allowed {
1198 let scfg: pbs_api_types::DataStoreConfig = serde_json::from_value(data.to_owned())?;
1199 // safety: we just cannot go through lookup as we must avoid an operation check
1200 if let Ok(datastore) = unsafe { DataStore::open_from_config(scfg, None) } {
1201 allow_id = can_access_any_ns(datastore, &auth_id, &user_info);
1202 }
1203 }
1204
1205 if allowed || allow_id {
dc7a5b34
TL
1206 list.push(DataStoreListItem {
1207 store: store.clone(),
7d6fc15b
TL
1208 comment: if !allowed {
1209 None
1210 } else {
1211 data["comment"].as_str().map(String::from)
1212 },
e022d13c 1213 maintenance: data["maintenance-mode"].as_str().map(String::from),
dc7a5b34 1214 });
30fb6025 1215 }
54552dda
DM
1216 }
1217
44288184 1218 Ok(list)
15e9b4ed
DM
1219}
1220
0ab08ac9
DM
1221#[sortable]
1222pub const API_METHOD_DOWNLOAD_FILE: ApiMethod = ApiMethod::new(
1223 &ApiHandler::AsyncHttp(&download_file),
1224 &ObjectSchema::new(
1225 "Download single raw file from backup snapshot.",
1226 &sorted!([
66c49c21 1227 ("store", false, &DATASTORE_SCHEMA),
33f2c2a1 1228 ("backup-ns", true, &BACKUP_NAMESPACE_SCHEMA),
0ab08ac9 1229 ("backup-type", false, &BACKUP_TYPE_SCHEMA),
dc7a5b34 1230 ("backup-id", false, &BACKUP_ID_SCHEMA),
0ab08ac9 1231 ("backup-time", false, &BACKUP_TIME_SCHEMA),
4191018c 1232 ("file-name", false, &BACKUP_ARCHIVE_NAME_SCHEMA),
0ab08ac9 1233 ]),
dc7a5b34
TL
1234 ),
1235)
1236.access(
7d6fc15b
TL
1237 Some(
1238 "Requires on /datastore/{store}[/{namespace}] either DATASTORE_READ for any or \
1239 DATASTORE_BACKUP and being the owner of the group",
dc7a5b34 1240 ),
7d6fc15b 1241 &Permission::Anybody,
54552dda 1242);
691c89a0 1243
bf78f708 1244pub fn download_file(
9e47c0a5
DM
1245 _parts: Parts,
1246 _req_body: Body,
1247 param: Value,
255f378a 1248 _info: &ApiMethod,
54552dda 1249 rpcenv: Box<dyn RpcEnvironment>,
bb084b9c 1250) -> ApiResponseFuture {
ad51d02a 1251 async move {
7d6fc15b 1252 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
3c8c2827 1253 let store = required_string_param(&param, "store")?;
133d718f 1254 let backup_ns = optional_ns_param(&param)?;
7d6fc15b 1255 let backup_dir: pbs_api_types::BackupDir = Deserialize::deserialize(&param)?;
a724f5fd 1256 let user_privs = get_ns_privs_checked(
7d6fc15b 1257 &store,
133d718f 1258 &backup_ns,
7d6fc15b
TL
1259 &auth_id,
1260 PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP,
1261 )?;
e9d2fc93 1262 let datastore = DataStore::lookup_datastore(store, Some(Operation::Read))?;
a724f5fd
FG
1263
1264 if user_privs & PRIV_DATASTORE_READ == 0 {
1265 let owner = datastore.get_owner(&backup_ns, &backup_dir.group)?;
1266 check_backup_owner(&owner, &auth_id)?;
1267 }
133d718f 1268 let backup_dir = datastore.backup_dir(backup_ns, backup_dir)?;
54552dda 1269
3c8c2827 1270 let file_name = required_string_param(&param, "file-name")?.to_owned();
9e47c0a5 1271
dc7a5b34
TL
1272 println!(
1273 "Download {} from {} ({}/{})",
1274 file_name, store, backup_dir, file_name
1275 );
9e47c0a5 1276
ad51d02a
DM
1277 let mut path = datastore.base_path();
1278 path.push(backup_dir.relative_path());
1279 path.push(&file_name);
1280
ba694720 1281 let file = tokio::fs::File::open(&path)
8aa67ee7
WB
1282 .await
1283 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
ad51d02a 1284
dc7a5b34
TL
1285 let payload =
1286 tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new())
1287 .map_ok(|bytes| bytes.freeze())
1288 .map_err(move |err| {
1289 eprintln!("error during streaming of '{:?}' - {}", &path, err);
1290 err
1291 });
ad51d02a 1292 let body = Body::wrap_stream(payload);
9e47c0a5 1293
ad51d02a
DM
1294 // fixme: set other headers ?
1295 Ok(Response::builder()
dc7a5b34
TL
1296 .status(StatusCode::OK)
1297 .header(header::CONTENT_TYPE, "application/octet-stream")
1298 .body(body)
1299 .unwrap())
1300 }
1301 .boxed()
9e47c0a5
DM
1302}
1303
6ef9bb59
DC
1304#[sortable]
1305pub const API_METHOD_DOWNLOAD_FILE_DECODED: ApiMethod = ApiMethod::new(
1306 &ApiHandler::AsyncHttp(&download_file_decoded),
1307 &ObjectSchema::new(
1308 "Download single decoded file from backup snapshot. Only works if it's not encrypted.",
1309 &sorted!([
1310 ("store", false, &DATASTORE_SCHEMA),
33f2c2a1 1311 ("backup-ns", true, &BACKUP_NAMESPACE_SCHEMA),
6ef9bb59 1312 ("backup-type", false, &BACKUP_TYPE_SCHEMA),
dc7a5b34 1313 ("backup-id", false, &BACKUP_ID_SCHEMA),
6ef9bb59
DC
1314 ("backup-time", false, &BACKUP_TIME_SCHEMA),
1315 ("file-name", false, &BACKUP_ARCHIVE_NAME_SCHEMA),
1316 ]),
dc7a5b34
TL
1317 ),
1318)
1319.access(
7d6fc15b
TL
1320 Some(
1321 "Requires on /datastore/{store}[/{namespace}] either DATASTORE_READ for any or \
1322 DATASTORE_BACKUP and being the owner of the group",
dc7a5b34 1323 ),
7d6fc15b 1324 &Permission::Anybody,
6ef9bb59
DC
1325);
1326
bf78f708 1327pub fn download_file_decoded(
6ef9bb59
DC
1328 _parts: Parts,
1329 _req_body: Body,
1330 param: Value,
1331 _info: &ApiMethod,
1332 rpcenv: Box<dyn RpcEnvironment>,
1333) -> ApiResponseFuture {
6ef9bb59 1334 async move {
7d6fc15b 1335 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
3c8c2827 1336 let store = required_string_param(&param, "store")?;
133d718f 1337 let backup_ns = optional_ns_param(&param)?;
7d6fc15b 1338 let backup_dir: pbs_api_types::BackupDir = Deserialize::deserialize(&param)?;
a724f5fd 1339 let user_privs = get_ns_privs_checked(
7d6fc15b 1340 &store,
133d718f 1341 &backup_ns,
7d6fc15b
TL
1342 &auth_id,
1343 PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP,
1344 )?;
e9d2fc93 1345 let datastore = DataStore::lookup_datastore(store, Some(Operation::Read))?;
a724f5fd
FG
1346
1347 if user_privs & PRIV_DATASTORE_READ == 0 {
1348 let owner = datastore.get_owner(&backup_ns, &backup_dir.group)?;
1349 check_backup_owner(&owner, &auth_id)?;
1350 }
1351
133d718f 1352 let backup_dir = datastore.backup_dir(backup_ns, backup_dir)?;
6ef9bb59 1353
3c8c2827 1354 let file_name = required_string_param(&param, "file-name")?.to_owned();
6ef9bb59 1355
2d55beec 1356 let (manifest, files) = read_backup_index(&datastore, &backup_dir)?;
6ef9bb59 1357 for file in files {
f28d9088 1358 if file.filename == file_name && file.crypt_mode == Some(CryptMode::Encrypt) {
6ef9bb59
DC
1359 bail!("cannot decode '{}' - is encrypted", file_name);
1360 }
1361 }
1362
dc7a5b34
TL
1363 println!(
1364 "Download {} from {} ({}/{})",
1365 file_name, store, backup_dir, file_name
1366 );
6ef9bb59
DC
1367
1368 let mut path = datastore.base_path();
1369 path.push(backup_dir.relative_path());
1370 path.push(&file_name);
1371
1372 let extension = file_name.rsplitn(2, '.').next().unwrap();
1373
1374 let body = match extension {
1375 "didx" => {
dc7a5b34
TL
1376 let index = DynamicIndexReader::open(&path).map_err(|err| {
1377 format_err!("unable to read dynamic index '{:?}' - {}", &path, err)
1378 })?;
2d55beec
FG
1379 let (csum, size) = index.compute_csum();
1380 manifest.verify_file(&file_name, &csum, size)?;
6ef9bb59 1381
14f6c9cb 1382 let chunk_reader = LocalChunkReader::new(datastore, None, CryptMode::None);
1ef6e8b6 1383 let reader = CachedChunkReader::new(chunk_reader, index, 1).seekable();
dc7a5b34
TL
1384 Body::wrap_stream(AsyncReaderStream::new(reader).map_err(move |err| {
1385 eprintln!("error during streaming of '{:?}' - {}", path, err);
1386 err
1387 }))
1388 }
6ef9bb59 1389 "fidx" => {
dc7a5b34
TL
1390 let index = FixedIndexReader::open(&path).map_err(|err| {
1391 format_err!("unable to read fixed index '{:?}' - {}", &path, err)
1392 })?;
6ef9bb59 1393
2d55beec
FG
1394 let (csum, size) = index.compute_csum();
1395 manifest.verify_file(&file_name, &csum, size)?;
1396
14f6c9cb 1397 let chunk_reader = LocalChunkReader::new(datastore, None, CryptMode::None);
1ef6e8b6 1398 let reader = CachedChunkReader::new(chunk_reader, index, 1).seekable();
dc7a5b34
TL
1399 Body::wrap_stream(
1400 AsyncReaderStream::with_buffer_size(reader, 4 * 1024 * 1024).map_err(
1401 move |err| {
1402 eprintln!("error during streaming of '{:?}' - {}", path, err);
1403 err
1404 },
1405 ),
1406 )
1407 }
6ef9bb59
DC
1408 "blob" => {
1409 let file = std::fs::File::open(&path)
8aa67ee7 1410 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
6ef9bb59 1411
2d55beec
FG
1412 // FIXME: load full blob to verify index checksum?
1413
6ef9bb59 1414 Body::wrap_stream(
dc7a5b34
TL
1415 WrappedReaderStream::new(DataBlobReader::new(file, None)?).map_err(
1416 move |err| {
6ef9bb59
DC
1417 eprintln!("error during streaming of '{:?}' - {}", path, err);
1418 err
dc7a5b34
TL
1419 },
1420 ),
6ef9bb59 1421 )
dc7a5b34 1422 }
6ef9bb59
DC
1423 extension => {
1424 bail!("cannot download '{}' files", extension);
dc7a5b34 1425 }
6ef9bb59
DC
1426 };
1427
1428 // fixme: set other headers ?
1429 Ok(Response::builder()
dc7a5b34
TL
1430 .status(StatusCode::OK)
1431 .header(header::CONTENT_TYPE, "application/octet-stream")
1432 .body(body)
1433 .unwrap())
1434 }
1435 .boxed()
6ef9bb59
DC
1436}
1437
552c2259 1438#[sortable]
0ab08ac9
DM
1439pub const API_METHOD_UPLOAD_BACKUP_LOG: ApiMethod = ApiMethod::new(
1440 &ApiHandler::AsyncHttp(&upload_backup_log),
255f378a 1441 &ObjectSchema::new(
54552dda 1442 "Upload the client backup log file into a backup snapshot ('client.log.blob').",
552c2259 1443 &sorted!([
66c49c21 1444 ("store", false, &DATASTORE_SCHEMA),
33f2c2a1 1445 ("backup-ns", true, &BACKUP_NAMESPACE_SCHEMA),
255f378a 1446 ("backup-type", false, &BACKUP_TYPE_SCHEMA),
0ab08ac9 1447 ("backup-id", false, &BACKUP_ID_SCHEMA),
255f378a 1448 ("backup-time", false, &BACKUP_TIME_SCHEMA),
552c2259 1449 ]),
dc7a5b34
TL
1450 ),
1451)
1452.access(
54552dda 1453 Some("Only the backup creator/owner is allowed to do this."),
7d6fc15b 1454 &Permission::Anybody,
54552dda 1455);
9e47c0a5 1456
bf78f708 1457pub fn upload_backup_log(
07ee2235
DM
1458 _parts: Parts,
1459 req_body: Body,
1460 param: Value,
255f378a 1461 _info: &ApiMethod,
54552dda 1462 rpcenv: Box<dyn RpcEnvironment>,
bb084b9c 1463) -> ApiResponseFuture {
ad51d02a 1464 async move {
7d6fc15b 1465 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
3c8c2827 1466 let store = required_string_param(&param, "store")?;
133d718f 1467 let backup_ns = optional_ns_param(&param)?;
7d6fc15b 1468 let backup_dir: pbs_api_types::BackupDir = Deserialize::deserialize(&param)?;
133d718f 1469 get_ns_privs_checked(&store, &backup_ns, &auth_id, PRIV_DATASTORE_BACKUP)?;
e9d2fc93 1470 let datastore = DataStore::lookup_datastore(store, Some(Operation::Write))?;
133d718f 1471 let backup_dir = datastore.backup_dir(backup_ns, backup_dir)?;
07ee2235 1472
dc7a5b34 1473 let file_name = CLIENT_LOG_BLOB_NAME;
07ee2235 1474
133d718f 1475 let owner = backup_dir.get_owner()?;
bff85572 1476 check_backup_owner(&owner, &auth_id)?;
54552dda 1477
133d718f 1478 let mut path = backup_dir.full_path();
ad51d02a 1479 path.push(&file_name);
07ee2235 1480
ad51d02a
DM
1481 if path.exists() {
1482 bail!("backup already contains a log.");
1483 }
e128d4e8 1484
8c74349b 1485 println!("Upload backup log to {store}/{backup_dir}/{file_name}");
ad51d02a
DM
1486
1487 let data = req_body
1488 .map_err(Error::from)
1489 .try_fold(Vec::new(), |mut acc, chunk| {
1490 acc.extend_from_slice(&*chunk);
1491 future::ok::<_, Error>(acc)
1492 })
1493 .await?;
1494
39f18b30
DM
1495 // always verify blob/CRC at server side
1496 let blob = DataBlob::load_from_reader(&mut &data[..])?;
1497
e0a19d33 1498 replace_file(&path, blob.raw_data(), CreateOptions::new(), false)?;
ad51d02a
DM
1499
1500 // fixme: use correct formatter
53daae8e 1501 Ok(formatter::JSON_FORMATTER.format_data(Value::Null, &*rpcenv))
dc7a5b34
TL
1502 }
1503 .boxed()
07ee2235
DM
1504}
1505
5b1cfa01
DC
1506#[api(
1507 input: {
1508 properties: {
988d575d 1509 store: { schema: DATASTORE_SCHEMA },
133d718f
WB
1510 "backup-ns": {
1511 type: BackupNamespace,
1512 optional: true,
1513 },
8c74349b
WB
1514 backup_dir: {
1515 type: pbs_api_types::BackupDir,
1516 flatten: true,
1517 },
5b1cfa01
DC
1518 "filepath": {
1519 description: "Base64 encoded path.",
1520 type: String,
1521 }
1522 },
1523 },
1524 access: {
7d6fc15b
TL
1525 description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_READ for any or \
1526 DATASTORE_BACKUP and being the owner of the group",
1527 permission: &Permission::Anybody,
5b1cfa01
DC
1528 },
1529)]
1530/// Get the entries of the given path of the catalog
bf78f708 1531pub fn catalog(
5b1cfa01 1532 store: String,
133d718f 1533 backup_ns: Option<BackupNamespace>,
8c74349b 1534 backup_dir: pbs_api_types::BackupDir,
5b1cfa01 1535 filepath: String,
5b1cfa01 1536 rpcenv: &mut dyn RpcEnvironment,
227501c0 1537) -> Result<Vec<ArchiveEntry>, Error> {
e6dc35ac 1538 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
133d718f 1539 let backup_ns = backup_ns.unwrap_or_default();
a724f5fd 1540 let user_privs = get_ns_privs_checked(
7d6fc15b 1541 &store,
133d718f 1542 &backup_ns,
7d6fc15b
TL
1543 &auth_id,
1544 PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP,
1545 )?;
5b1cfa01 1546
7d6fc15b 1547 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Read))?;
5b1cfa01 1548
a724f5fd
FG
1549 if user_privs & PRIV_DATASTORE_READ == 0 {
1550 let owner = datastore.get_owner(&backup_ns, &backup_dir.group)?;
1551 check_backup_owner(&owner, &auth_id)?;
1552 }
1553
1554 let backup_dir = datastore.backup_dir(backup_ns, backup_dir)?;
5b1cfa01 1555
9238cdf5
FG
1556 let file_name = CATALOG_NAME;
1557
2d55beec 1558 let (manifest, files) = read_backup_index(&datastore, &backup_dir)?;
9238cdf5
FG
1559 for file in files {
1560 if file.filename == file_name && file.crypt_mode == Some(CryptMode::Encrypt) {
1561 bail!("cannot decode '{}' - is encrypted", file_name);
1562 }
1563 }
1564
5b1cfa01
DC
1565 let mut path = datastore.base_path();
1566 path.push(backup_dir.relative_path());
9238cdf5 1567 path.push(file_name);
5b1cfa01
DC
1568
1569 let index = DynamicIndexReader::open(&path)
1570 .map_err(|err| format_err!("unable to read dynamic index '{:?}' - {}", &path, err))?;
1571
2d55beec 1572 let (csum, size) = index.compute_csum();
9a37bd6c 1573 manifest.verify_file(file_name, &csum, size)?;
2d55beec 1574
14f6c9cb 1575 let chunk_reader = LocalChunkReader::new(datastore, None, CryptMode::None);
5b1cfa01
DC
1576 let reader = BufferedDynamicReader::new(index, chunk_reader);
1577
1578 let mut catalog_reader = CatalogReader::new(reader);
5b1cfa01 1579
5279ee74 1580 let path = if filepath != "root" && filepath != "/" {
227501c0
DC
1581 base64::decode(filepath)?
1582 } else {
1583 vec![b'/']
1584 };
5b1cfa01 1585
86582454 1586 catalog_reader.list_dir_contents(&path)
5b1cfa01
DC
1587}
1588
d33d8f4e
DC
1589#[sortable]
1590pub const API_METHOD_PXAR_FILE_DOWNLOAD: ApiMethod = ApiMethod::new(
1591 &ApiHandler::AsyncHttp(&pxar_file_download),
1592 &ObjectSchema::new(
1ffe0301 1593 "Download single file from pxar file of a backup snapshot. Only works if it's not encrypted.",
d33d8f4e
DC
1594 &sorted!([
1595 ("store", false, &DATASTORE_SCHEMA),
33f2c2a1 1596 ("backup-ns", true, &BACKUP_NAMESPACE_SCHEMA),
d33d8f4e
DC
1597 ("backup-type", false, &BACKUP_TYPE_SCHEMA),
1598 ("backup-id", false, &BACKUP_ID_SCHEMA),
1599 ("backup-time", false, &BACKUP_TIME_SCHEMA),
1600 ("filepath", false, &StringSchema::new("Base64 encoded path").schema()),
984ddb2f 1601 ("tar", true, &BooleanSchema::new("Download as .tar.zst").schema()),
d33d8f4e
DC
1602 ]),
1603 )
7d6fc15b
TL
1604).access(
1605 Some(
1606 "Requires on /datastore/{store}[/{namespace}] either DATASTORE_READ for any or \
1607 DATASTORE_BACKUP and being the owner of the group",
1608 ),
1609 &Permission::Anybody,
d33d8f4e
DC
1610);
1611
bf78f708 1612pub fn pxar_file_download(
d33d8f4e
DC
1613 _parts: Parts,
1614 _req_body: Body,
1615 param: Value,
1616 _info: &ApiMethod,
1617 rpcenv: Box<dyn RpcEnvironment>,
1618) -> ApiResponseFuture {
d33d8f4e 1619 async move {
7d6fc15b 1620 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
3c8c2827 1621 let store = required_string_param(&param, "store")?;
133d718f 1622 let backup_ns = optional_ns_param(&param)?;
7d6fc15b 1623 let backup_dir: pbs_api_types::BackupDir = Deserialize::deserialize(&param)?;
a724f5fd 1624 let user_privs = get_ns_privs_checked(
7d6fc15b 1625 &store,
133d718f 1626 &backup_ns,
7d6fc15b
TL
1627 &auth_id,
1628 PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP,
1629 )?;
e9d2fc93 1630 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Read))?;
a724f5fd
FG
1631
1632 if user_privs & PRIV_DATASTORE_READ == 0 {
1633 let owner = datastore.get_owner(&backup_ns, &backup_dir.group)?;
1634 check_backup_owner(&owner, &auth_id)?;
1635 }
1636
133d718f 1637 let backup_dir = datastore.backup_dir(backup_ns, backup_dir)?;
d33d8f4e 1638
3c8c2827 1639 let filepath = required_string_param(&param, "filepath")?.to_owned();
d33d8f4e 1640
984ddb2f
DC
1641 let tar = param["tar"].as_bool().unwrap_or(false);
1642
d33d8f4e 1643 let mut components = base64::decode(&filepath)?;
3984a5fd 1644 if !components.is_empty() && components[0] == b'/' {
d33d8f4e
DC
1645 components.remove(0);
1646 }
1647
d8d8af98 1648 let mut split = components.splitn(2, |c| *c == b'/');
9238cdf5 1649 let pxar_name = std::str::from_utf8(split.next().unwrap())?;
0dfce17a 1650 let file_path = split.next().unwrap_or(b"/");
2d55beec 1651 let (manifest, files) = read_backup_index(&datastore, &backup_dir)?;
9238cdf5
FG
1652 for file in files {
1653 if file.filename == pxar_name && file.crypt_mode == Some(CryptMode::Encrypt) {
1654 bail!("cannot decode '{}' - is encrypted", pxar_name);
1655 }
1656 }
d33d8f4e 1657
9238cdf5
FG
1658 let mut path = datastore.base_path();
1659 path.push(backup_dir.relative_path());
1660 path.push(pxar_name);
d33d8f4e
DC
1661
1662 let index = DynamicIndexReader::open(&path)
1663 .map_err(|err| format_err!("unable to read dynamic index '{:?}' - {}", &path, err))?;
1664
2d55beec 1665 let (csum, size) = index.compute_csum();
9a37bd6c 1666 manifest.verify_file(pxar_name, &csum, size)?;
2d55beec 1667
14f6c9cb 1668 let chunk_reader = LocalChunkReader::new(datastore, None, CryptMode::None);
d33d8f4e
DC
1669 let reader = BufferedDynamicReader::new(index, chunk_reader);
1670 let archive_size = reader.archive_size();
1671 let reader = LocalDynamicReadAt::new(reader);
1672
1673 let decoder = Accessor::new(reader, archive_size).await?;
1674 let root = decoder.open_root().await?;
2e219481 1675 let path = OsStr::from_bytes(file_path).to_os_string();
d33d8f4e 1676 let file = root
dc7a5b34
TL
1677 .lookup(&path)
1678 .await?
2e219481 1679 .ok_or_else(|| format_err!("error opening '{:?}'", path))?;
d33d8f4e 1680
804f6143
DC
1681 let body = match file.kind() {
1682 EntryKind::File { .. } => Body::wrap_stream(
1683 AsyncReaderStream::new(file.contents().await?).map_err(move |err| {
1684 eprintln!("error during streaming of file '{:?}' - {}", filepath, err);
1685 err
1686 }),
1687 ),
1688 EntryKind::Hardlink(_) => Body::wrap_stream(
1689 AsyncReaderStream::new(decoder.follow_hardlink(&file).await?.contents().await?)
1690 .map_err(move |err| {
dc7a5b34 1691 eprintln!("error during streaming of hardlink '{:?}' - {}", path, err);
804f6143
DC
1692 err
1693 }),
1694 ),
1695 EntryKind::Directory => {
984ddb2f 1696 let (sender, receiver) = tokio::sync::mpsc::channel::<Result<_, Error>>(100);
804f6143 1697 let channelwriter = AsyncChannelWriter::new(sender, 1024 * 1024);
984ddb2f 1698 if tar {
dc7a5b34
TL
1699 proxmox_rest_server::spawn_internal_task(create_tar(
1700 channelwriter,
1701 decoder,
1702 path.clone(),
1703 false,
1704 ));
984ddb2f
DC
1705 let zstdstream = ZstdEncoder::new(ReceiverStream::new(receiver))?;
1706 Body::wrap_stream(zstdstream.map_err(move |err| {
1707 eprintln!("error during streaming of tar.zst '{:?}' - {}", path, err);
1708 err
1709 }))
1710 } else {
dc7a5b34
TL
1711 proxmox_rest_server::spawn_internal_task(create_zip(
1712 channelwriter,
1713 decoder,
1714 path.clone(),
1715 false,
1716 ));
984ddb2f
DC
1717 Body::wrap_stream(ReceiverStream::new(receiver).map_err(move |err| {
1718 eprintln!("error during streaming of zip '{:?}' - {}", path, err);
1719 err
1720 }))
1721 }
804f6143
DC
1722 }
1723 other => bail!("cannot download file of type {:?}", other),
1724 };
d33d8f4e
DC
1725
1726 // fixme: set other headers ?
1727 Ok(Response::builder()
dc7a5b34
TL
1728 .status(StatusCode::OK)
1729 .header(header::CONTENT_TYPE, "application/octet-stream")
1730 .body(body)
1731 .unwrap())
1732 }
1733 .boxed()
d33d8f4e
DC
1734}
1735
1a0d3d11
DM
1736#[api(
1737 input: {
1738 properties: {
1739 store: {
1740 schema: DATASTORE_SCHEMA,
1741 },
1742 timeframe: {
c68fa58a 1743 type: RRDTimeFrame,
1a0d3d11
DM
1744 },
1745 cf: {
1746 type: RRDMode,
1747 },
1748 },
1749 },
1750 access: {
7d6fc15b
TL
1751 permission: &Permission::Privilege(
1752 &["datastore", "{store}"], PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP, true),
1a0d3d11
DM
1753 },
1754)]
1755/// Read datastore stats
bf78f708 1756pub fn get_rrd_stats(
1a0d3d11 1757 store: String,
c68fa58a 1758 timeframe: RRDTimeFrame,
1a0d3d11
DM
1759 cf: RRDMode,
1760 _param: Value,
1761) -> Result<Value, Error> {
e9d2fc93 1762 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Read))?;
f27b6086
DC
1763 let disk_manager = crate::tools::disks::DiskManage::new();
1764
1765 let mut rrd_fields = vec![
dc7a5b34
TL
1766 "total",
1767 "used",
1768 "read_ios",
1769 "read_bytes",
1770 "write_ios",
1771 "write_bytes",
f27b6086
DC
1772 ];
1773
1774 // we do not have io_ticks for zpools, so don't include them
1775 match disk_manager.find_mounted_device(&datastore.base_path()) {
dc7a5b34 1776 Ok(Some((fs_type, _, _))) if fs_type.as_str() == "zfs" => {}
f27b6086
DC
1777 _ => rrd_fields.push("io_ticks"),
1778 };
1779
dc7a5b34 1780 create_value_from_rrd(&format!("datastore/{}", store), &rrd_fields, timeframe, cf)
1a0d3d11
DM
1781}
1782
5fd823c3
HL
1783#[api(
1784 input: {
1785 properties: {
1786 store: {
1787 schema: DATASTORE_SCHEMA,
1788 },
1789 },
1790 },
1791 access: {
1792 permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_AUDIT, true),
1793 },
1794)]
1795/// Read datastore stats
dc7a5b34 1796pub fn get_active_operations(store: String, _param: Value) -> Result<Value, Error> {
5fd823c3
HL
1797 let active_operations = task_tracking::get_active_operations(&store)?;
1798 Ok(json!({
1799 "read": active_operations.read,
1800 "write": active_operations.write,
1801 }))
1802}
1803
d6688884
SR
1804#[api(
1805 input: {
1806 properties: {
988d575d 1807 store: { schema: DATASTORE_SCHEMA },
133d718f
WB
1808 "backup-ns": {
1809 type: BackupNamespace,
1810 optional: true,
1811 },
8c74349b
WB
1812 backup_group: {
1813 type: pbs_api_types::BackupGroup,
1814 flatten: true,
1815 },
d6688884
SR
1816 },
1817 },
1818 access: {
7d6fc15b
TL
1819 permission: &Permission::Anybody,
1820 description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_AUDIT for any \
1821 or DATASTORE_BACKUP and being the owner of the group",
d6688884
SR
1822 },
1823)]
1824/// Get "notes" for a backup group
1825pub fn get_group_notes(
1826 store: String,
133d718f 1827 backup_ns: Option<BackupNamespace>,
8c74349b 1828 backup_group: pbs_api_types::BackupGroup,
d6688884
SR
1829 rpcenv: &mut dyn RpcEnvironment,
1830) -> Result<String, Error> {
d6688884 1831 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
133d718f 1832 let backup_ns = backup_ns.unwrap_or_default();
a724f5fd 1833 let user_privs = get_ns_privs_checked(
7d6fc15b 1834 &store,
133d718f 1835 &backup_ns,
7d6fc15b
TL
1836 &auth_id,
1837 PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP,
1838 )?;
1839 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Read))?;
d6688884 1840
a724f5fd
FG
1841 if user_privs & PRIV_DATASTORE_AUDIT == 0 {
1842 let owner = datastore.get_owner(&backup_ns, &backup_group)?;
1843 check_backup_owner(&owner, &auth_id)?;
1844 }
d6688884 1845
133d718f 1846 let note_path = get_group_note_path(&datastore, &backup_ns, &backup_group);
d6688884
SR
1847 Ok(file_read_optional_string(note_path)?.unwrap_or_else(|| "".to_owned()))
1848}
1849
1850#[api(
1851 input: {
1852 properties: {
988d575d 1853 store: { schema: DATASTORE_SCHEMA },
133d718f
WB
1854 "backup-ns": {
1855 type: BackupNamespace,
1856 optional: true,
1857 },
8c74349b
WB
1858 backup_group: {
1859 type: pbs_api_types::BackupGroup,
1860 flatten: true,
1861 },
d6688884
SR
1862 notes: {
1863 description: "A multiline text.",
1864 },
1865 },
1866 },
1867 access: {
7d6fc15b
TL
1868 permission: &Permission::Anybody,
1869 description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any \
1870 or DATASTORE_BACKUP and being the owner of the group",
d6688884
SR
1871 },
1872)]
1873/// Set "notes" for a backup group
1874pub fn set_group_notes(
1875 store: String,
133d718f 1876 backup_ns: Option<BackupNamespace>,
8c74349b 1877 backup_group: pbs_api_types::BackupGroup,
d6688884
SR
1878 notes: String,
1879 rpcenv: &mut dyn RpcEnvironment,
1880) -> Result<(), Error> {
d6688884 1881 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
133d718f 1882 let backup_ns = backup_ns.unwrap_or_default();
a724f5fd 1883 let user_privs = get_ns_privs_checked(
7d6fc15b 1884 &store,
133d718f 1885 &backup_ns,
7d6fc15b
TL
1886 &auth_id,
1887 PRIV_DATASTORE_MODIFY | PRIV_DATASTORE_BACKUP,
1888 )?;
1889 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Write))?;
a724f5fd
FG
1890 if user_privs & PRIV_DATASTORE_MODIFY == 0 {
1891 let owner = datastore.get_owner(&backup_ns, &backup_group)?;
1892 check_backup_owner(&owner, &auth_id)?;
1893 }
d6688884 1894
133d718f 1895 let note_path = get_group_note_path(&datastore, &backup_ns, &backup_group);
e0a19d33 1896 replace_file(note_path, notes.as_bytes(), CreateOptions::new(), false)?;
d6688884
SR
1897
1898 Ok(())
1899}
1900
912b3f5b
DM
1901#[api(
1902 input: {
1903 properties: {
988d575d 1904 store: { schema: DATASTORE_SCHEMA },
133d718f
WB
1905 "backup-ns": {
1906 type: BackupNamespace,
1907 optional: true,
1908 },
8c74349b
WB
1909 backup_dir: {
1910 type: pbs_api_types::BackupDir,
1911 flatten: true,
1912 },
912b3f5b
DM
1913 },
1914 },
1915 access: {
7d6fc15b
TL
1916 permission: &Permission::Anybody,
1917 description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_AUDIT for any \
1918 or DATASTORE_BACKUP and being the owner of the group",
912b3f5b
DM
1919 },
1920)]
1921/// Get "notes" for a specific backup
bf78f708 1922pub fn get_notes(
912b3f5b 1923 store: String,
133d718f 1924 backup_ns: Option<BackupNamespace>,
8c74349b 1925 backup_dir: pbs_api_types::BackupDir,
912b3f5b
DM
1926 rpcenv: &mut dyn RpcEnvironment,
1927) -> Result<String, Error> {
7d6fc15b 1928 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
133d718f 1929 let backup_ns = backup_ns.unwrap_or_default();
a724f5fd 1930 let user_privs = get_ns_privs_checked(
7d6fc15b 1931 &store,
133d718f 1932 &backup_ns,
7d6fc15b
TL
1933 &auth_id,
1934 PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP,
1935 )?;
e9d2fc93 1936 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Read))?;
a724f5fd
FG
1937 if user_privs & PRIV_DATASTORE_AUDIT == 0 {
1938 let owner = datastore.get_owner(&backup_ns, &backup_dir.group)?;
1939 check_backup_owner(&owner, &auth_id)?;
1940 }
912b3f5b 1941
133d718f 1942 let backup_dir = datastore.backup_dir(backup_ns, backup_dir)?;
912b3f5b 1943
133d718f 1944 let (manifest, _) = backup_dir.load_manifest()?;
912b3f5b 1945
dc7a5b34 1946 let notes = manifest.unprotected["notes"].as_str().unwrap_or("");
912b3f5b
DM
1947
1948 Ok(String::from(notes))
1949}
1950
1951#[api(
1952 input: {
1953 properties: {
988d575d 1954 store: { schema: DATASTORE_SCHEMA },
133d718f
WB
1955 "backup-ns": {
1956 type: BackupNamespace,
1957 optional: true,
1958 },
8c74349b
WB
1959 backup_dir: {
1960 type: pbs_api_types::BackupDir,
1961 flatten: true,
1962 },
912b3f5b
DM
1963 notes: {
1964 description: "A multiline text.",
1965 },
1966 },
1967 },
1968 access: {
7d6fc15b
TL
1969 permission: &Permission::Anybody,
1970 description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any \
1971 or DATASTORE_BACKUP and being the owner of the group",
912b3f5b
DM
1972 },
1973)]
1974/// Set "notes" for a specific backup
bf78f708 1975pub fn set_notes(
912b3f5b 1976 store: String,
133d718f 1977 backup_ns: Option<BackupNamespace>,
8c74349b 1978 backup_dir: pbs_api_types::BackupDir,
912b3f5b
DM
1979 notes: String,
1980 rpcenv: &mut dyn RpcEnvironment,
1981) -> Result<(), Error> {
7d6fc15b 1982 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
133d718f 1983 let backup_ns = backup_ns.unwrap_or_default();
a724f5fd 1984 let user_privs = get_ns_privs_checked(
7d6fc15b 1985 &store,
133d718f 1986 &backup_ns,
7d6fc15b
TL
1987 &auth_id,
1988 PRIV_DATASTORE_MODIFY | PRIV_DATASTORE_BACKUP,
1989 )?;
e9d2fc93 1990 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Write))?;
a724f5fd
FG
1991 if user_privs & PRIV_DATASTORE_MODIFY == 0 {
1992 let owner = datastore.get_owner(&backup_ns, &backup_dir.group)?;
1993 check_backup_owner(&owner, &auth_id)?;
1994 }
912b3f5b 1995
133d718f 1996 let backup_dir = datastore.backup_dir(backup_ns, backup_dir)?;
912b3f5b 1997
133d718f
WB
1998 backup_dir
1999 .update_manifest(|manifest| {
dc7a5b34
TL
2000 manifest.unprotected["notes"] = notes.into();
2001 })
2002 .map_err(|err| format_err!("unable to update manifest blob - {}", err))?;
912b3f5b
DM
2003
2004 Ok(())
2005}
2006
8292d3d2
DC
2007#[api(
2008 input: {
2009 properties: {
988d575d 2010 store: { schema: DATASTORE_SCHEMA },
133d718f
WB
2011 "backup-ns": {
2012 type: BackupNamespace,
2013 optional: true,
2014 },
8c74349b
WB
2015 backup_dir: {
2016 type: pbs_api_types::BackupDir,
2017 flatten: true,
2018 },
8292d3d2
DC
2019 },
2020 },
2021 access: {
7d6fc15b
TL
2022 permission: &Permission::Anybody,
2023 description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_AUDIT for any \
2024 or DATASTORE_BACKUP and being the owner of the group",
8292d3d2
DC
2025 },
2026)]
2027/// Query protection for a specific backup
2028pub fn get_protection(
2029 store: String,
133d718f 2030 backup_ns: Option<BackupNamespace>,
8c74349b 2031 backup_dir: pbs_api_types::BackupDir,
8292d3d2
DC
2032 rpcenv: &mut dyn RpcEnvironment,
2033) -> Result<bool, Error> {
7d6fc15b 2034 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
133d718f 2035 let backup_ns = backup_ns.unwrap_or_default();
a724f5fd 2036 let user_privs = get_ns_privs_checked(
7d6fc15b 2037 &store,
133d718f 2038 &backup_ns,
7d6fc15b
TL
2039 &auth_id,
2040 PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP,
2041 )?;
e9d2fc93 2042 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Read))?;
a724f5fd
FG
2043 if user_privs & PRIV_DATASTORE_AUDIT == 0 {
2044 let owner = datastore.get_owner(&backup_ns, &backup_dir.group)?;
2045 check_backup_owner(&owner, &auth_id)?;
2046 }
8292d3d2 2047
133d718f 2048 let backup_dir = datastore.backup_dir(backup_ns, backup_dir)?;
8292d3d2 2049
6da20161 2050 Ok(backup_dir.is_protected())
8292d3d2
DC
2051}
2052
2053#[api(
2054 input: {
2055 properties: {
988d575d 2056 store: { schema: DATASTORE_SCHEMA },
133d718f
WB
2057 "backup-ns": {
2058 type: BackupNamespace,
2059 optional: true,
2060 },
8c74349b
WB
2061 backup_dir: {
2062 type: pbs_api_types::BackupDir,
2063 flatten: true,
2064 },
8292d3d2
DC
2065 protected: {
2066 description: "Enable/disable protection.",
2067 },
2068 },
2069 },
2070 access: {
7d6fc15b
TL
2071 permission: &Permission::Anybody,
2072 description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any \
2073 or DATASTORE_BACKUP and being the owner of the group",
8292d3d2
DC
2074 },
2075)]
2076/// En- or disable protection for a specific backup
2077pub fn set_protection(
2078 store: String,
133d718f 2079 backup_ns: Option<BackupNamespace>,
8c74349b 2080 backup_dir: pbs_api_types::BackupDir,
8292d3d2
DC
2081 protected: bool,
2082 rpcenv: &mut dyn RpcEnvironment,
2083) -> Result<(), Error> {
7d6fc15b 2084 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
133d718f 2085 let backup_ns = backup_ns.unwrap_or_default();
a724f5fd 2086 let user_privs = get_ns_privs_checked(
7d6fc15b 2087 &store,
133d718f 2088 &backup_ns,
7d6fc15b
TL
2089 &auth_id,
2090 PRIV_DATASTORE_MODIFY | PRIV_DATASTORE_BACKUP,
2091 )?;
e9d2fc93 2092 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Write))?;
a724f5fd
FG
2093 if user_privs & PRIV_DATASTORE_MODIFY == 0 {
2094 let owner = datastore.get_owner(&backup_ns, &backup_dir.group)?;
2095 check_backup_owner(&owner, &auth_id)?;
2096 }
8292d3d2 2097
133d718f 2098 let backup_dir = datastore.backup_dir(backup_ns, backup_dir)?;
8292d3d2 2099
8292d3d2
DC
2100 datastore.update_protection(&backup_dir, protected)
2101}
2102
72be0eb1 2103#[api(
4940012d 2104 input: {
72be0eb1 2105 properties: {
988d575d 2106 store: { schema: DATASTORE_SCHEMA },
133d718f
WB
2107 "backup-ns": {
2108 type: BackupNamespace,
2109 optional: true,
2110 },
8c74349b
WB
2111 backup_group: {
2112 type: pbs_api_types::BackupGroup,
2113 flatten: true,
2114 },
72be0eb1 2115 "new-owner": {
e6dc35ac 2116 type: Authid,
72be0eb1
DW
2117 },
2118 },
4940012d
FG
2119 },
2120 access: {
bff85572 2121 permission: &Permission::Anybody,
7d6fc15b
TL
2122 description: "Datastore.Modify on whole datastore, or changing ownership between user and \
2123 a user's token for owned backups with Datastore.Backup"
4940012d 2124 },
72be0eb1
DW
2125)]
2126/// Change owner of a backup group
bf78f708 2127pub fn set_backup_owner(
72be0eb1 2128 store: String,
133d718f 2129 backup_ns: Option<BackupNamespace>,
8c74349b 2130 backup_group: pbs_api_types::BackupGroup,
e6dc35ac 2131 new_owner: Authid,
bff85572 2132 rpcenv: &mut dyn RpcEnvironment,
72be0eb1 2133) -> Result<(), Error> {
e9d2fc93 2134 let datastore = DataStore::lookup_datastore(&store, Some(Operation::Write))?;
72be0eb1 2135
bff85572 2136 let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
133d718f 2137 let backup_ns = backup_ns.unwrap_or_default();
a724f5fd
FG
2138
2139 let privs = get_ns_privs_checked(
2140 &store,
2141 &backup_ns,
2142 &auth_id,
2143 PRIV_DATASTORE_MODIFY | PRIV_DATASTORE_BACKUP,
2144 )?;
133d718f 2145 let backup_group = datastore.backup_group(backup_ns, backup_group);
bff85572
FG
2146
2147 let allowed = if (privs & PRIV_DATASTORE_MODIFY) != 0 {
7d6fc15b 2148 true // High-privilege user/token
bff85572 2149 } else if (privs & PRIV_DATASTORE_BACKUP) != 0 {
133d718f 2150 let owner = backup_group.get_owner()?;
bff85572
FG
2151
2152 match (owner.is_token(), new_owner.is_token()) {
2153 (true, true) => {
2154 // API token to API token, owned by same user
2155 let owner = owner.user();
2156 let new_owner = new_owner.user();
2157 owner == new_owner && Authid::from(owner.clone()) == auth_id
dc7a5b34 2158 }
bff85572
FG
2159 (true, false) => {
2160 // API token to API token owner
dc7a5b34
TL
2161 Authid::from(owner.user().clone()) == auth_id && new_owner == auth_id
2162 }
bff85572
FG
2163 (false, true) => {
2164 // API token owner to API token
dc7a5b34
TL
2165 owner == auth_id && Authid::from(new_owner.user().clone()) == auth_id
2166 }
bff85572
FG
2167 (false, false) => {
2168 // User to User, not allowed for unprivileged users
2169 false
dc7a5b34 2170 }
bff85572
FG
2171 }
2172 } else {
2173 false
2174 };
2175
2176 if !allowed {
dc7a5b34
TL
2177 return Err(http_err!(
2178 UNAUTHORIZED,
2179 "{} does not have permission to change owner of backup group '{}' to {}",
2180 auth_id,
2181 backup_group,
2182 new_owner,
bff85572
FG
2183 ));
2184 }
2185
7d6fc15b
TL
2186 let user_info = CachedUserInfo::new()?;
2187
e6dc35ac 2188 if !user_info.is_active_auth_id(&new_owner) {
dc7a5b34
TL
2189 bail!(
2190 "{} '{}' is inactive or non-existent",
2191 if new_owner.is_token() {
2192 "API token".to_string()
2193 } else {
2194 "user".to_string()
2195 },
2196 new_owner
2197 );
72be0eb1
DW
2198 }
2199
133d718f 2200 backup_group.set_owner(&new_owner, true)?;
72be0eb1
DW
2201
2202 Ok(())
2203}
2204
552c2259 2205#[sortable]
255f378a 2206const DATASTORE_INFO_SUBDIRS: SubdirMap = &[
5fd823c3
HL
2207 (
2208 "active-operations",
dc7a5b34 2209 &Router::new().get(&API_METHOD_GET_ACTIVE_OPERATIONS),
5b1cfa01 2210 ),
dc7a5b34 2211 ("catalog", &Router::new().get(&API_METHOD_CATALOG)),
72be0eb1
DW
2212 (
2213 "change-owner",
dc7a5b34 2214 &Router::new().post(&API_METHOD_SET_BACKUP_OWNER),
72be0eb1 2215 ),
255f378a
DM
2216 (
2217 "download",
dc7a5b34 2218 &Router::new().download(&API_METHOD_DOWNLOAD_FILE),
255f378a 2219 ),
6ef9bb59
DC
2220 (
2221 "download-decoded",
dc7a5b34 2222 &Router::new().download(&API_METHOD_DOWNLOAD_FILE_DECODED),
255f378a 2223 ),
dc7a5b34 2224 ("files", &Router::new().get(&API_METHOD_LIST_SNAPSHOT_FILES)),
255f378a
DM
2225 (
2226 "gc",
2227 &Router::new()
2228 .get(&API_METHOD_GARBAGE_COLLECTION_STATUS)
dc7a5b34 2229 .post(&API_METHOD_START_GARBAGE_COLLECTION),
255f378a 2230 ),
d6688884
SR
2231 (
2232 "group-notes",
2233 &Router::new()
2234 .get(&API_METHOD_GET_GROUP_NOTES)
dc7a5b34 2235 .put(&API_METHOD_SET_GROUP_NOTES),
d6688884 2236 ),
255f378a
DM
2237 (
2238 "groups",
2239 &Router::new()
b31c8019 2240 .get(&API_METHOD_LIST_GROUPS)
dc7a5b34 2241 .delete(&API_METHOD_DELETE_GROUP),
255f378a 2242 ),
18934ae5
TL
2243 (
2244 "namespace",
2245 // FIXME: move into datastore:: sub-module?!
2246 &crate::api2::admin::namespace::ROUTER,
2247 ),
912b3f5b
DM
2248 (
2249 "notes",
2250 &Router::new()
2251 .get(&API_METHOD_GET_NOTES)
dc7a5b34 2252 .put(&API_METHOD_SET_NOTES),
912b3f5b 2253 ),
8292d3d2
DC
2254 (
2255 "protected",
2256 &Router::new()
2257 .get(&API_METHOD_GET_PROTECTION)
dc7a5b34 2258 .put(&API_METHOD_SET_PROTECTION),
255f378a 2259 ),
dc7a5b34 2260 ("prune", &Router::new().post(&API_METHOD_PRUNE)),
9805207a
DC
2261 (
2262 "prune-datastore",
dc7a5b34 2263 &Router::new().post(&API_METHOD_PRUNE_DATASTORE),
9805207a 2264 ),
d33d8f4e
DC
2265 (
2266 "pxar-file-download",
dc7a5b34 2267 &Router::new().download(&API_METHOD_PXAR_FILE_DOWNLOAD),
1a0d3d11 2268 ),
dc7a5b34 2269 ("rrd", &Router::new().get(&API_METHOD_GET_RRD_STATS)),
255f378a
DM
2270 (
2271 "snapshots",
2272 &Router::new()
fc189b19 2273 .get(&API_METHOD_LIST_SNAPSHOTS)
dc7a5b34 2274 .delete(&API_METHOD_DELETE_SNAPSHOT),
255f378a 2275 ),
dc7a5b34 2276 ("status", &Router::new().get(&API_METHOD_STATUS)),
255f378a
DM
2277 (
2278 "upload-backup-log",
dc7a5b34 2279 &Router::new().upload(&API_METHOD_UPLOAD_BACKUP_LOG),
c2009e53 2280 ),
dc7a5b34 2281 ("verify", &Router::new().post(&API_METHOD_VERIFY)),
255f378a
DM
2282];
2283
ad51d02a 2284const DATASTORE_INFO_ROUTER: Router = Router::new()
255f378a
DM
2285 .get(&list_subdirs_api_method!(DATASTORE_INFO_SUBDIRS))
2286 .subdirs(DATASTORE_INFO_SUBDIRS);
2287
255f378a 2288pub const ROUTER: Router = Router::new()
bb34b589 2289 .get(&API_METHOD_GET_DATASTORE_LIST)
255f378a 2290 .match_all("store", &DATASTORE_INFO_ROUTER);