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