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