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