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