]> git.proxmox.com Git - proxmox-backup.git/blame - src/api2/admin/datastore.rs
introduce TaskState trait
[proxmox-backup.git] / src / api2 / admin / datastore.rs
CommitLineData
cad540e9 1use std::collections::{HashSet, HashMap};
d33d8f4e
DC
2use std::ffi::OsStr;
3use std::os::unix::ffi::OsStrExt;
6b809ff5 4use std::sync::{Arc, Mutex};
cad540e9 5
6ef9bb59 6use anyhow::{bail, format_err, Error};
9e47c0a5 7use futures::*;
cad540e9
WB
8use hyper::http::request::Parts;
9use hyper::{header, Body, Response, StatusCode};
15e9b4ed
DM
10use serde_json::{json, Value};
11
bb34b589
DM
12use proxmox::api::{
13 api, ApiResponseFuture, ApiHandler, ApiMethod, Router,
e7cb4dc5
WB
14 RpcEnvironment, RpcEnvironmentType, Permission
15};
cad540e9
WB
16use proxmox::api::router::SubdirMap;
17use proxmox::api::schema::*;
60f9a6ea 18use proxmox::tools::fs::{replace_file, CreateOptions};
9ea4bce4
WB
19use proxmox::try_block;
20use proxmox::{http_err, identity, list_subdirs_api_method, sortable};
e18a6c9e 21
d33d8f4e
DC
22use pxar::accessor::aio::Accessor;
23use pxar::EntryKind;
24
cad540e9 25use crate::api2::types::*;
431cc7b1 26use crate::api2::node::rrd::create_value_from_rrd;
e5064ba6 27use crate::backup::*;
cad540e9 28use crate::config::datastore;
54552dda
DM
29use crate::config::cached_user_info::CachedUserInfo;
30
0f778e06 31use crate::server::WorkerTask;
f386f512 32use crate::tools::{self, AsyncReaderStream, WrappedReaderStream};
d00e1a21
DM
33use crate::config::acl::{
34 PRIV_DATASTORE_AUDIT,
54552dda 35 PRIV_DATASTORE_MODIFY,
d00e1a21
DM
36 PRIV_DATASTORE_READ,
37 PRIV_DATASTORE_PRUNE,
54552dda 38 PRIV_DATASTORE_BACKUP,
d00e1a21 39};
1629d2ad 40
e7cb4dc5
WB
41fn check_backup_owner(
42 store: &DataStore,
43 group: &BackupGroup,
44 userid: &Userid,
45) -> Result<(), Error> {
54552dda
DM
46 let owner = store.get_owner(group)?;
47 if &owner != userid {
48 bail!("backup owner check failed ({} != {})", userid, owner);
49 }
50 Ok(())
51}
52
e7cb4dc5
WB
53fn read_backup_index(
54 store: &DataStore,
55 backup_dir: &BackupDir,
56) -> Result<(BackupManifest, Vec<BackupContent>), Error> {
8c70e3eb 57
ff86ef00 58 let (manifest, index_size) = store.load_manifest(backup_dir)?;
8c70e3eb 59
09b1f7b2
DM
60 let mut result = Vec::new();
61 for item in manifest.files() {
62 result.push(BackupContent {
63 filename: item.filename.clone(),
f28d9088 64 crypt_mode: Some(item.crypt_mode),
09b1f7b2
DM
65 size: Some(item.size),
66 });
8c70e3eb
DM
67 }
68
09b1f7b2 69 result.push(BackupContent {
96d65fbc 70 filename: MANIFEST_BLOB_NAME.to_string(),
882c0823
FG
71 crypt_mode: match manifest.signature {
72 Some(_) => Some(CryptMode::SignOnly),
73 None => Some(CryptMode::None),
74 },
09b1f7b2
DM
75 size: Some(index_size),
76 });
4f1e40a2 77
70030b43 78 Ok((manifest, result))
8c70e3eb
DM
79}
80
1c090810
DC
81fn get_all_snapshot_files(
82 store: &DataStore,
83 info: &BackupInfo,
70030b43
DM
84) -> Result<(BackupManifest, Vec<BackupContent>), Error> {
85
86 let (manifest, mut files) = read_backup_index(&store, &info.backup_dir)?;
1c090810
DC
87
88 let file_set = files.iter().fold(HashSet::new(), |mut acc, item| {
89 acc.insert(item.filename.clone());
90 acc
91 });
92
93 for file in &info.files {
94 if file_set.contains(file) { continue; }
f28d9088
WB
95 files.push(BackupContent {
96 filename: file.to_string(),
97 size: None,
98 crypt_mode: None,
99 });
1c090810
DC
100 }
101
70030b43 102 Ok((manifest, files))
1c090810
DC
103}
104
8f579717
DM
105fn group_backups(backup_list: Vec<BackupInfo>) -> HashMap<String, Vec<BackupInfo>> {
106
107 let mut group_hash = HashMap::new();
108
109 for info in backup_list {
9b492eb2 110 let group_id = info.backup_dir.group().group_path().to_str().unwrap().to_owned();
8f579717
DM
111 let time_list = group_hash.entry(group_id).or_insert(vec![]);
112 time_list.push(info);
113 }
114
115 group_hash
116}
117
b31c8019
DM
118#[api(
119 input: {
120 properties: {
121 store: {
122 schema: DATASTORE_SCHEMA,
123 },
124 },
125 },
126 returns: {
127 type: Array,
128 description: "Returns the list of backup groups.",
129 items: {
130 type: GroupListItem,
131 }
132 },
bb34b589 133 access: {
54552dda
DM
134 permission: &Permission::Privilege(
135 &["datastore", "{store}"],
136 PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP,
137 true),
bb34b589 138 },
b31c8019
DM
139)]
140/// List backup groups.
ad20d198 141fn list_groups(
b31c8019 142 store: String,
54552dda 143 rpcenv: &mut dyn RpcEnvironment,
b31c8019 144) -> Result<Vec<GroupListItem>, Error> {
812c6f87 145
e7cb4dc5 146 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
54552dda 147 let user_info = CachedUserInfo::new()?;
e7cb4dc5 148 let user_privs = user_info.lookup_privs(&userid, &["datastore", &store]);
54552dda 149
b31c8019 150 let datastore = DataStore::lookup_datastore(&store)?;
812c6f87 151
c0977501 152 let backup_list = BackupInfo::list_backups(&datastore.base_path())?;
812c6f87
DM
153
154 let group_hash = group_backups(backup_list);
155
b31c8019 156 let mut groups = Vec::new();
812c6f87
DM
157
158 for (_group_id, mut list) in group_hash {
159
2b01a225 160 BackupInfo::sort_list(&mut list, false);
812c6f87
DM
161
162 let info = &list[0];
54552dda 163
9b492eb2 164 let group = info.backup_dir.group();
812c6f87 165
54552dda 166 let list_all = (user_privs & PRIV_DATASTORE_AUDIT) != 0;
04b0ca8b 167 let owner = datastore.get_owner(group)?;
54552dda 168 if !list_all {
e7cb4dc5 169 if owner != userid { continue; }
54552dda
DM
170 }
171
b31c8019
DM
172 let result_item = GroupListItem {
173 backup_type: group.backup_type().to_string(),
174 backup_id: group.backup_id().to_string(),
6a7be83e 175 last_backup: info.backup_dir.backup_time(),
b31c8019
DM
176 backup_count: list.len() as u64,
177 files: info.files.clone(),
04b0ca8b 178 owner: Some(owner),
b31c8019
DM
179 };
180 groups.push(result_item);
812c6f87
DM
181 }
182
b31c8019 183 Ok(groups)
812c6f87 184}
8f579717 185
09b1f7b2
DM
186#[api(
187 input: {
188 properties: {
189 store: {
190 schema: DATASTORE_SCHEMA,
191 },
192 "backup-type": {
193 schema: BACKUP_TYPE_SCHEMA,
194 },
195 "backup-id": {
196 schema: BACKUP_ID_SCHEMA,
197 },
198 "backup-time": {
199 schema: BACKUP_TIME_SCHEMA,
200 },
201 },
202 },
203 returns: {
204 type: Array,
205 description: "Returns the list of archive files inside a backup snapshots.",
206 items: {
207 type: BackupContent,
208 }
209 },
bb34b589 210 access: {
54552dda
DM
211 permission: &Permission::Privilege(
212 &["datastore", "{store}"],
213 PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP,
214 true),
bb34b589 215 },
09b1f7b2
DM
216)]
217/// List snapshot files.
ea5f547f 218pub fn list_snapshot_files(
09b1f7b2
DM
219 store: String,
220 backup_type: String,
221 backup_id: String,
222 backup_time: i64,
01a13423 223 _info: &ApiMethod,
54552dda 224 rpcenv: &mut dyn RpcEnvironment,
09b1f7b2 225) -> Result<Vec<BackupContent>, Error> {
01a13423 226
e7cb4dc5 227 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
54552dda 228 let user_info = CachedUserInfo::new()?;
e7cb4dc5 229 let user_privs = user_info.lookup_privs(&userid, &["datastore", &store]);
54552dda 230
09b1f7b2 231 let datastore = DataStore::lookup_datastore(&store)?;
54552dda 232
e0e5b442 233 let snapshot = BackupDir::new(backup_type, backup_id, backup_time)?;
01a13423 234
54552dda 235 let allowed = (user_privs & (PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_READ)) != 0;
e7cb4dc5 236 if !allowed { check_backup_owner(&datastore, snapshot.group(), &userid)?; }
54552dda 237
d7c24397 238 let info = BackupInfo::new(&datastore.base_path(), snapshot)?;
01a13423 239
70030b43
DM
240 let (_manifest, files) = get_all_snapshot_files(&datastore, &info)?;
241
242 Ok(files)
01a13423
DM
243}
244
68a6a0ee
DM
245#[api(
246 input: {
247 properties: {
248 store: {
249 schema: DATASTORE_SCHEMA,
250 },
251 "backup-type": {
252 schema: BACKUP_TYPE_SCHEMA,
253 },
254 "backup-id": {
255 schema: BACKUP_ID_SCHEMA,
256 },
257 "backup-time": {
258 schema: BACKUP_TIME_SCHEMA,
259 },
260 },
261 },
bb34b589 262 access: {
54552dda
DM
263 permission: &Permission::Privilege(
264 &["datastore", "{store}"],
265 PRIV_DATASTORE_MODIFY| PRIV_DATASTORE_PRUNE,
266 true),
bb34b589 267 },
68a6a0ee
DM
268)]
269/// Delete backup snapshot.
270fn delete_snapshot(
271 store: String,
272 backup_type: String,
273 backup_id: String,
274 backup_time: i64,
6f62c924 275 _info: &ApiMethod,
54552dda 276 rpcenv: &mut dyn RpcEnvironment,
6f62c924
DM
277) -> Result<Value, Error> {
278
e7cb4dc5 279 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
54552dda 280 let user_info = CachedUserInfo::new()?;
e7cb4dc5 281 let user_privs = user_info.lookup_privs(&userid, &["datastore", &store]);
54552dda 282
e0e5b442 283 let snapshot = BackupDir::new(backup_type, backup_id, backup_time)?;
6f62c924 284
68a6a0ee 285 let datastore = DataStore::lookup_datastore(&store)?;
6f62c924 286
54552dda 287 let allowed = (user_privs & PRIV_DATASTORE_MODIFY) != 0;
e7cb4dc5 288 if !allowed { check_backup_owner(&datastore, snapshot.group(), &userid)?; }
54552dda 289
c9756b40 290 datastore.remove_backup_dir(&snapshot, false)?;
6f62c924
DM
291
292 Ok(Value::Null)
293}
294
fc189b19
DM
295#[api(
296 input: {
297 properties: {
298 store: {
299 schema: DATASTORE_SCHEMA,
300 },
301 "backup-type": {
302 optional: true,
303 schema: BACKUP_TYPE_SCHEMA,
304 },
305 "backup-id": {
306 optional: true,
307 schema: BACKUP_ID_SCHEMA,
308 },
309 },
310 },
311 returns: {
312 type: Array,
313 description: "Returns the list of snapshots.",
314 items: {
315 type: SnapshotListItem,
316 }
317 },
bb34b589 318 access: {
54552dda
DM
319 permission: &Permission::Privilege(
320 &["datastore", "{store}"],
321 PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP,
322 true),
bb34b589 323 },
fc189b19
DM
324)]
325/// List backup snapshots.
f24fc116 326pub fn list_snapshots (
54552dda
DM
327 store: String,
328 backup_type: Option<String>,
329 backup_id: Option<String>,
330 _param: Value,
184f17af 331 _info: &ApiMethod,
54552dda 332 rpcenv: &mut dyn RpcEnvironment,
fc189b19 333) -> Result<Vec<SnapshotListItem>, Error> {
184f17af 334
e7cb4dc5 335 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
54552dda 336 let user_info = CachedUserInfo::new()?;
e7cb4dc5 337 let user_privs = user_info.lookup_privs(&userid, &["datastore", &store]);
184f17af 338
54552dda 339 let datastore = DataStore::lookup_datastore(&store)?;
184f17af 340
c0977501 341 let base_path = datastore.base_path();
184f17af 342
15c847f1 343 let backup_list = BackupInfo::list_backups(&base_path)?;
184f17af
DM
344
345 let mut snapshots = vec![];
346
c0977501 347 for info in backup_list {
15c847f1 348 let group = info.backup_dir.group();
54552dda 349 if let Some(ref backup_type) = backup_type {
15c847f1
DM
350 if backup_type != group.backup_type() { continue; }
351 }
54552dda 352 if let Some(ref backup_id) = backup_id {
15c847f1
DM
353 if backup_id != group.backup_id() { continue; }
354 }
a17a0e7a 355
54552dda 356 let list_all = (user_privs & PRIV_DATASTORE_AUDIT) != 0;
04b0ca8b
DC
357 let owner = datastore.get_owner(group)?;
358
54552dda 359 if !list_all {
e7cb4dc5 360 if owner != userid { continue; }
54552dda
DM
361 }
362
1c090810
DC
363 let mut size = None;
364
3b2046d2 365 let (comment, verification, files) = match get_all_snapshot_files(&datastore, &info) {
70030b43 366 Ok((manifest, files)) => {
1c090810 367 size = Some(files.iter().map(|x| x.size.unwrap_or(0)).sum());
70030b43
DM
368 // extract the first line from notes
369 let comment: Option<String> = manifest.unprotected["notes"]
370 .as_str()
371 .and_then(|notes| notes.lines().next())
372 .map(String::from);
373
3b2046d2
TL
374 let verify = manifest.unprotected["verify_state"].clone();
375 let verify: Option<SnapshotVerifyState> = match serde_json::from_value(verify) {
376 Ok(verify) => verify,
377 Err(err) => {
378 eprintln!("error parsing verification state : '{}'", err);
379 None
380 }
381 };
382
383 (comment, verify, files)
1c090810
DC
384 },
385 Err(err) => {
386 eprintln!("error during snapshot file listing: '{}'", err);
70030b43 387 (
3b2046d2 388 None,
70030b43
DM
389 None,
390 info
391 .files
392 .iter()
393 .map(|x| BackupContent {
394 filename: x.to_string(),
395 size: None,
396 crypt_mode: None,
397 })
398 .collect()
399 )
1c090810
DC
400 },
401 };
402
403 let result_item = SnapshotListItem {
fc189b19
DM
404 backup_type: group.backup_type().to_string(),
405 backup_id: group.backup_id().to_string(),
6a7be83e 406 backup_time: info.backup_dir.backup_time(),
70030b43 407 comment,
3b2046d2 408 verification,
1c090810
DC
409 files,
410 size,
04b0ca8b 411 owner: Some(owner),
fc189b19 412 };
a17a0e7a 413
a17a0e7a 414 snapshots.push(result_item);
184f17af
DM
415 }
416
fc189b19 417 Ok(snapshots)
184f17af
DM
418}
419
1dc117bb
DM
420#[api(
421 input: {
422 properties: {
423 store: {
424 schema: DATASTORE_SCHEMA,
425 },
426 },
427 },
428 returns: {
429 type: StorageStatus,
430 },
bb34b589 431 access: {
54552dda 432 permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP, true),
bb34b589 433 },
1dc117bb
DM
434)]
435/// Get datastore status.
ea5f547f 436pub fn status(
1dc117bb 437 store: String,
0eecf38f
DM
438 _info: &ApiMethod,
439 _rpcenv: &mut dyn RpcEnvironment,
1dc117bb 440) -> Result<StorageStatus, Error> {
1dc117bb 441 let datastore = DataStore::lookup_datastore(&store)?;
33070956 442 crate::tools::disks::disk_usage(&datastore.base_path())
0eecf38f
DM
443}
444
c2009e53
DM
445#[api(
446 input: {
447 properties: {
448 store: {
449 schema: DATASTORE_SCHEMA,
450 },
451 "backup-type": {
452 schema: BACKUP_TYPE_SCHEMA,
453 optional: true,
454 },
455 "backup-id": {
456 schema: BACKUP_ID_SCHEMA,
457 optional: true,
458 },
459 "backup-time": {
460 schema: BACKUP_TIME_SCHEMA,
461 optional: true,
462 },
463 },
464 },
465 returns: {
466 schema: UPID_SCHEMA,
467 },
468 access: {
469 permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP, true), // fixme
470 },
471)]
472/// Verify backups.
473///
474/// This function can verify a single backup snapshot, all backup from a backup group,
475/// or all backups in the datastore.
476pub fn verify(
477 store: String,
478 backup_type: Option<String>,
479 backup_id: Option<String>,
480 backup_time: Option<i64>,
481 rpcenv: &mut dyn RpcEnvironment,
482) -> Result<Value, Error> {
483 let datastore = DataStore::lookup_datastore(&store)?;
484
8ea00f6e 485 let worker_id;
c2009e53
DM
486
487 let mut backup_dir = None;
488 let mut backup_group = None;
489
490 match (backup_type, backup_id, backup_time) {
491 (Some(backup_type), Some(backup_id), Some(backup_time)) => {
2162e2c1 492 worker_id = format!("{}_{}_{}_{:08X}", store, backup_type, backup_id, backup_time);
e0e5b442 493 let dir = BackupDir::new(backup_type, backup_id, backup_time)?;
c2009e53
DM
494 backup_dir = Some(dir);
495 }
496 (Some(backup_type), Some(backup_id), None) => {
2162e2c1 497 worker_id = format!("{}_{}_{}", store, backup_type, backup_id);
c2009e53 498 let group = BackupGroup::new(backup_type, backup_id);
c2009e53
DM
499 backup_group = Some(group);
500 }
501 (None, None, None) => {
8ea00f6e 502 worker_id = store.clone();
c2009e53 503 }
5a718dce 504 _ => bail!("parameters do not specify a backup group or snapshot"),
c2009e53
DM
505 }
506
e7cb4dc5 507 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
c2009e53
DM
508 let to_stdout = if rpcenv.env_type() == RpcEnvironmentType::CLI { true } else { false };
509
510 let upid_str = WorkerTask::new_thread(
e7cb4dc5
WB
511 "verify",
512 Some(worker_id.clone()),
513 userid,
514 to_stdout,
515 move |worker| {
4f09d310
DM
516 let verified_chunks = Arc::new(Mutex::new(HashSet::with_capacity(1024*16)));
517 let corrupt_chunks = Arc::new(Mutex::new(HashSet::with_capacity(64)));
518
adfdc369 519 let failed_dirs = if let Some(backup_dir) = backup_dir {
adfdc369 520 let mut res = Vec::new();
6b809ff5 521 if !verify_backup_dir(datastore, &backup_dir, verified_chunks, corrupt_chunks, worker.clone())? {
adfdc369
DC
522 res.push(backup_dir.to_string());
523 }
524 res
c2009e53 525 } else if let Some(backup_group) = backup_group {
63d9aca9
DM
526 let (_count, failed_dirs) = verify_backup_group(
527 datastore,
528 &backup_group,
529 verified_chunks,
530 corrupt_chunks,
531 None,
532 worker.clone(),
533 )?;
534 failed_dirs
c2009e53 535 } else {
6b809ff5 536 verify_all_backups(datastore, worker.clone())?
c2009e53 537 };
adfdc369
DC
538 if failed_dirs.len() > 0 {
539 worker.log("Failed to verify following snapshots:");
540 for dir in failed_dirs {
541 worker.log(format!("\t{}", dir));
542 }
1ffe0301 543 bail!("verification failed - please check the log for details");
c2009e53
DM
544 }
545 Ok(())
e7cb4dc5
WB
546 },
547 )?;
c2009e53
DM
548
549 Ok(json!(upid_str))
550}
551
255f378a
DM
552#[macro_export]
553macro_rules! add_common_prune_prameters {
552c2259
DM
554 ( [ $( $list1:tt )* ] ) => {
555 add_common_prune_prameters!([$( $list1 )* ] , [])
556 };
557 ( [ $( $list1:tt )* ] , [ $( $list2:tt )* ] ) => {
255f378a 558 [
552c2259 559 $( $list1 )*
255f378a 560 (
552c2259 561 "keep-daily",
255f378a 562 true,
49ff1092 563 &PRUNE_SCHEMA_KEEP_DAILY,
255f378a 564 ),
102d8d41
DM
565 (
566 "keep-hourly",
567 true,
49ff1092 568 &PRUNE_SCHEMA_KEEP_HOURLY,
102d8d41 569 ),
255f378a 570 (
552c2259 571 "keep-last",
255f378a 572 true,
49ff1092 573 &PRUNE_SCHEMA_KEEP_LAST,
255f378a
DM
574 ),
575 (
552c2259 576 "keep-monthly",
255f378a 577 true,
49ff1092 578 &PRUNE_SCHEMA_KEEP_MONTHLY,
255f378a
DM
579 ),
580 (
552c2259 581 "keep-weekly",
255f378a 582 true,
49ff1092 583 &PRUNE_SCHEMA_KEEP_WEEKLY,
255f378a
DM
584 ),
585 (
586 "keep-yearly",
587 true,
49ff1092 588 &PRUNE_SCHEMA_KEEP_YEARLY,
255f378a 589 ),
552c2259 590 $( $list2 )*
255f378a
DM
591 ]
592 }
0eecf38f
DM
593}
594
db1e061d
DM
595pub const API_RETURN_SCHEMA_PRUNE: Schema = ArraySchema::new(
596 "Returns the list of snapshots and a flag indicating if there are kept or removed.",
660a3489 597 &PruneListItem::API_SCHEMA
db1e061d
DM
598).schema();
599
0ab08ac9
DM
600const API_METHOD_PRUNE: ApiMethod = ApiMethod::new(
601 &ApiHandler::Sync(&prune),
255f378a 602 &ObjectSchema::new(
0ab08ac9
DM
603 "Prune the datastore.",
604 &add_common_prune_prameters!([
605 ("backup-id", false, &BACKUP_ID_SCHEMA),
606 ("backup-type", false, &BACKUP_TYPE_SCHEMA),
3b03abfe
DM
607 ("dry-run", true, &BooleanSchema::new(
608 "Just show what prune would do, but do not delete anything.")
609 .schema()
610 ),
0ab08ac9 611 ],[
66c49c21 612 ("store", false, &DATASTORE_SCHEMA),
0ab08ac9 613 ])
db1e061d
DM
614 ))
615 .returns(&API_RETURN_SCHEMA_PRUNE)
616 .access(None, &Permission::Privilege(
54552dda
DM
617 &["datastore", "{store}"],
618 PRIV_DATASTORE_MODIFY | PRIV_DATASTORE_PRUNE,
619 true)
620);
255f378a 621
83b7db02
DM
622fn prune(
623 param: Value,
624 _info: &ApiMethod,
54552dda 625 rpcenv: &mut dyn RpcEnvironment,
83b7db02
DM
626) -> Result<Value, Error> {
627
54552dda 628 let store = tools::required_string_param(&param, "store")?;
9fdc3ef4
DM
629 let backup_type = tools::required_string_param(&param, "backup-type")?;
630 let backup_id = tools::required_string_param(&param, "backup-id")?;
631
e7cb4dc5 632 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
54552dda 633 let user_info = CachedUserInfo::new()?;
e7cb4dc5 634 let user_privs = user_info.lookup_privs(&userid, &["datastore", &store]);
54552dda 635
3b03abfe
DM
636 let dry_run = param["dry-run"].as_bool().unwrap_or(false);
637
9fdc3ef4
DM
638 let group = BackupGroup::new(backup_type, backup_id);
639
54552dda
DM
640 let datastore = DataStore::lookup_datastore(&store)?;
641
642 let allowed = (user_privs & PRIV_DATASTORE_MODIFY) != 0;
e7cb4dc5 643 if !allowed { check_backup_owner(&datastore, &group, &userid)?; }
83b7db02 644
9e3f0088
DM
645 let prune_options = PruneOptions {
646 keep_last: param["keep-last"].as_u64(),
102d8d41 647 keep_hourly: param["keep-hourly"].as_u64(),
9e3f0088
DM
648 keep_daily: param["keep-daily"].as_u64(),
649 keep_weekly: param["keep-weekly"].as_u64(),
650 keep_monthly: param["keep-monthly"].as_u64(),
651 keep_yearly: param["keep-yearly"].as_u64(),
652 };
8f579717 653
503995c7
DM
654 let worker_id = format!("{}_{}_{}", store, backup_type, backup_id);
655
dda70154
DM
656 let mut prune_result = Vec::new();
657
658 let list = group.list_backups(&datastore.base_path())?;
659
660 let mut prune_info = compute_prune_info(list, &prune_options)?;
661
662 prune_info.reverse(); // delete older snapshots first
663
664 let keep_all = !prune_options.keeps_something();
665
666 if dry_run {
667 for (info, mut keep) in prune_info {
668 if keep_all { keep = true; }
669
670 let backup_time = info.backup_dir.backup_time();
671 let group = info.backup_dir.group();
672
673 prune_result.push(json!({
674 "backup-type": group.backup_type(),
675 "backup-id": group.backup_id(),
6a7be83e 676 "backup-time": backup_time,
dda70154
DM
677 "keep": keep,
678 }));
679 }
680 return Ok(json!(prune_result));
681 }
682
683
163e9bbe 684 // We use a WorkerTask just to have a task log, but run synchrounously
e7cb4dc5 685 let worker = WorkerTask::new("prune", Some(worker_id), Userid::root_userid().clone(), true)?;
dda70154 686
dd8e744f 687 let result = try_block! {
dda70154 688 if keep_all {
9fdc3ef4 689 worker.log("No prune selection - keeping all files.");
dd8e744f 690 } else {
236a396a 691 worker.log(format!("retention options: {}", prune_options.cli_options_string()));
dda70154
DM
692 worker.log(format!("Starting prune on store \"{}\" group \"{}/{}\"",
693 store, backup_type, backup_id));
dd8e744f 694 }
8f579717 695
dda70154
DM
696 for (info, mut keep) in prune_info {
697 if keep_all { keep = true; }
dd8e744f 698
3b03abfe 699 let backup_time = info.backup_dir.backup_time();
6a7be83e 700 let timestamp = info.backup_dir.backup_time_string();
3b03abfe
DM
701 let group = info.backup_dir.group();
702
dda70154 703
3b03abfe
DM
704 let msg = format!(
705 "{}/{}/{} {}",
706 group.backup_type(),
707 group.backup_id(),
708 timestamp,
709 if keep { "keep" } else { "remove" },
710 );
711
712 worker.log(msg);
713
dda70154
DM
714 prune_result.push(json!({
715 "backup-type": group.backup_type(),
716 "backup-id": group.backup_id(),
6a7be83e 717 "backup-time": backup_time,
dda70154
DM
718 "keep": keep,
719 }));
720
3b03abfe 721 if !(dry_run || keep) {
c9756b40 722 datastore.remove_backup_dir(&info.backup_dir, true)?;
8f0b4c1f 723 }
8f579717 724 }
dd8e744f
DM
725
726 Ok(())
727 };
728
729 worker.log_result(&result);
730
731 if let Err(err) = result {
732 bail!("prune failed - {}", err);
dda70154 733 };
83b7db02 734
dda70154 735 Ok(json!(prune_result))
83b7db02
DM
736}
737
dfc58d47
DM
738#[api(
739 input: {
740 properties: {
741 store: {
742 schema: DATASTORE_SCHEMA,
743 },
744 },
745 },
746 returns: {
747 schema: UPID_SCHEMA,
748 },
bb34b589 749 access: {
54552dda 750 permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_MODIFY, false),
bb34b589 751 },
dfc58d47
DM
752)]
753/// Start garbage collection.
6049b71f 754fn start_garbage_collection(
dfc58d47 755 store: String,
6049b71f 756 _info: &ApiMethod,
dd5495d6 757 rpcenv: &mut dyn RpcEnvironment,
6049b71f 758) -> Result<Value, Error> {
15e9b4ed 759
3e6a7dee 760 let datastore = DataStore::lookup_datastore(&store)?;
15e9b4ed 761
5a778d92 762 println!("Starting garbage collection on store {}", store);
15e9b4ed 763
0f778e06 764 let to_stdout = if rpcenv.env_type() == RpcEnvironmentType::CLI { true } else { false };
15e9b4ed 765
0f778e06 766 let upid_str = WorkerTask::new_thread(
e7cb4dc5
WB
767 "garbage_collection",
768 Some(store.clone()),
769 Userid::root_userid().clone(),
770 to_stdout,
771 move |worker| {
0f778e06 772 worker.log(format!("starting garbage collection on store {}", store));
99641a6b 773 datastore.garbage_collection(&worker)
e7cb4dc5
WB
774 },
775 )?;
0f778e06
DM
776
777 Ok(json!(upid_str))
15e9b4ed
DM
778}
779
a92830dc
DM
780#[api(
781 input: {
782 properties: {
783 store: {
784 schema: DATASTORE_SCHEMA,
785 },
786 },
787 },
788 returns: {
789 type: GarbageCollectionStatus,
bb34b589
DM
790 },
791 access: {
792 permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_AUDIT, false),
793 },
a92830dc
DM
794)]
795/// Garbage collection status.
5eeea607 796pub fn garbage_collection_status(
a92830dc 797 store: String,
6049b71f 798 _info: &ApiMethod,
dd5495d6 799 _rpcenv: &mut dyn RpcEnvironment,
a92830dc 800) -> Result<GarbageCollectionStatus, Error> {
691c89a0 801
f2b99c34
DM
802 let datastore = DataStore::lookup_datastore(&store)?;
803
f2b99c34 804 let status = datastore.last_gc_status();
691c89a0 805
a92830dc 806 Ok(status)
691c89a0
DM
807}
808
bb34b589 809#[api(
30fb6025
DM
810 returns: {
811 description: "List the accessible datastores.",
812 type: Array,
813 items: {
814 description: "Datastore name and description.",
815 properties: {
816 store: {
817 schema: DATASTORE_SCHEMA,
818 },
819 comment: {
820 optional: true,
821 schema: SINGLE_LINE_COMMENT_SCHEMA,
822 },
823 },
824 },
825 },
bb34b589 826 access: {
54552dda 827 permission: &Permission::Anybody,
bb34b589
DM
828 },
829)]
830/// Datastore list
6049b71f
DM
831fn get_datastore_list(
832 _param: Value,
833 _info: &ApiMethod,
54552dda 834 rpcenv: &mut dyn RpcEnvironment,
6049b71f 835) -> Result<Value, Error> {
15e9b4ed 836
d0187a51 837 let (config, _digest) = datastore::config()?;
15e9b4ed 838
e7cb4dc5 839 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
54552dda
DM
840 let user_info = CachedUserInfo::new()?;
841
30fb6025 842 let mut list = Vec::new();
54552dda 843
30fb6025 844 for (store, (_, data)) in &config.sections {
e7cb4dc5 845 let user_privs = user_info.lookup_privs(&userid, &["datastore", &store]);
54552dda 846 let allowed = (user_privs & (PRIV_DATASTORE_AUDIT| PRIV_DATASTORE_BACKUP)) != 0;
30fb6025
DM
847 if allowed {
848 let mut entry = json!({ "store": store });
849 if let Some(comment) = data["comment"].as_str() {
850 entry["comment"] = comment.into();
851 }
852 list.push(entry);
853 }
54552dda
DM
854 }
855
30fb6025 856 Ok(list.into())
15e9b4ed
DM
857}
858
0ab08ac9
DM
859#[sortable]
860pub const API_METHOD_DOWNLOAD_FILE: ApiMethod = ApiMethod::new(
861 &ApiHandler::AsyncHttp(&download_file),
862 &ObjectSchema::new(
863 "Download single raw file from backup snapshot.",
864 &sorted!([
66c49c21 865 ("store", false, &DATASTORE_SCHEMA),
0ab08ac9
DM
866 ("backup-type", false, &BACKUP_TYPE_SCHEMA),
867 ("backup-id", false, &BACKUP_ID_SCHEMA),
868 ("backup-time", false, &BACKUP_TIME_SCHEMA),
4191018c 869 ("file-name", false, &BACKUP_ARCHIVE_NAME_SCHEMA),
0ab08ac9
DM
870 ]),
871 )
54552dda
DM
872).access(None, &Permission::Privilege(
873 &["datastore", "{store}"],
874 PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP,
875 true)
876);
691c89a0 877
9e47c0a5
DM
878fn download_file(
879 _parts: Parts,
880 _req_body: Body,
881 param: Value,
255f378a 882 _info: &ApiMethod,
54552dda 883 rpcenv: Box<dyn RpcEnvironment>,
bb084b9c 884) -> ApiResponseFuture {
9e47c0a5 885
ad51d02a
DM
886 async move {
887 let store = tools::required_string_param(&param, "store")?;
ad51d02a 888 let datastore = DataStore::lookup_datastore(store)?;
f14a8c9a 889
e7cb4dc5 890 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
54552dda 891 let user_info = CachedUserInfo::new()?;
e7cb4dc5 892 let user_privs = user_info.lookup_privs(&userid, &["datastore", &store]);
54552dda 893
ad51d02a 894 let file_name = tools::required_string_param(&param, "file-name")?.to_owned();
9e47c0a5 895
ad51d02a
DM
896 let backup_type = tools::required_string_param(&param, "backup-type")?;
897 let backup_id = tools::required_string_param(&param, "backup-id")?;
898 let backup_time = tools::required_integer_param(&param, "backup-time")?;
9e47c0a5 899
e0e5b442 900 let backup_dir = BackupDir::new(backup_type, backup_id, backup_time)?;
54552dda
DM
901
902 let allowed = (user_privs & PRIV_DATASTORE_READ) != 0;
e7cb4dc5 903 if !allowed { check_backup_owner(&datastore, backup_dir.group(), &userid)?; }
54552dda 904
abdb9763 905 println!("Download {} from {} ({}/{})", file_name, store, backup_dir, file_name);
9e47c0a5 906
ad51d02a
DM
907 let mut path = datastore.base_path();
908 path.push(backup_dir.relative_path());
909 path.push(&file_name);
910
ba694720 911 let file = tokio::fs::File::open(&path)
8aa67ee7
WB
912 .await
913 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
ad51d02a 914
db0cb9ce 915 let payload = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new())
ba694720
DC
916 .map_ok(|bytes| hyper::body::Bytes::from(bytes.freeze()))
917 .map_err(move |err| {
918 eprintln!("error during streaming of '{:?}' - {}", &path, err);
919 err
920 });
ad51d02a 921 let body = Body::wrap_stream(payload);
9e47c0a5 922
ad51d02a
DM
923 // fixme: set other headers ?
924 Ok(Response::builder()
925 .status(StatusCode::OK)
926 .header(header::CONTENT_TYPE, "application/octet-stream")
927 .body(body)
928 .unwrap())
929 }.boxed()
9e47c0a5
DM
930}
931
6ef9bb59
DC
932#[sortable]
933pub const API_METHOD_DOWNLOAD_FILE_DECODED: ApiMethod = ApiMethod::new(
934 &ApiHandler::AsyncHttp(&download_file_decoded),
935 &ObjectSchema::new(
936 "Download single decoded file from backup snapshot. Only works if it's not encrypted.",
937 &sorted!([
938 ("store", false, &DATASTORE_SCHEMA),
939 ("backup-type", false, &BACKUP_TYPE_SCHEMA),
940 ("backup-id", false, &BACKUP_ID_SCHEMA),
941 ("backup-time", false, &BACKUP_TIME_SCHEMA),
942 ("file-name", false, &BACKUP_ARCHIVE_NAME_SCHEMA),
943 ]),
944 )
945).access(None, &Permission::Privilege(
946 &["datastore", "{store}"],
947 PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP,
948 true)
949);
950
951fn download_file_decoded(
952 _parts: Parts,
953 _req_body: Body,
954 param: Value,
955 _info: &ApiMethod,
956 rpcenv: Box<dyn RpcEnvironment>,
957) -> ApiResponseFuture {
958
959 async move {
960 let store = tools::required_string_param(&param, "store")?;
961 let datastore = DataStore::lookup_datastore(store)?;
962
e7cb4dc5 963 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
6ef9bb59 964 let user_info = CachedUserInfo::new()?;
e7cb4dc5 965 let user_privs = user_info.lookup_privs(&userid, &["datastore", &store]);
6ef9bb59
DC
966
967 let file_name = tools::required_string_param(&param, "file-name")?.to_owned();
968
969 let backup_type = tools::required_string_param(&param, "backup-type")?;
970 let backup_id = tools::required_string_param(&param, "backup-id")?;
971 let backup_time = tools::required_integer_param(&param, "backup-time")?;
972
e0e5b442 973 let backup_dir = BackupDir::new(backup_type, backup_id, backup_time)?;
6ef9bb59
DC
974
975 let allowed = (user_privs & PRIV_DATASTORE_READ) != 0;
e7cb4dc5 976 if !allowed { check_backup_owner(&datastore, backup_dir.group(), &userid)?; }
6ef9bb59 977
2d55beec 978 let (manifest, files) = read_backup_index(&datastore, &backup_dir)?;
6ef9bb59 979 for file in files {
f28d9088 980 if file.filename == file_name && file.crypt_mode == Some(CryptMode::Encrypt) {
6ef9bb59
DC
981 bail!("cannot decode '{}' - is encrypted", file_name);
982 }
983 }
984
985 println!("Download {} from {} ({}/{})", file_name, store, backup_dir, file_name);
986
987 let mut path = datastore.base_path();
988 path.push(backup_dir.relative_path());
989 path.push(&file_name);
990
991 let extension = file_name.rsplitn(2, '.').next().unwrap();
992
993 let body = match extension {
994 "didx" => {
995 let index = DynamicIndexReader::open(&path)
996 .map_err(|err| format_err!("unable to read dynamic index '{:?}' - {}", &path, err))?;
2d55beec
FG
997 let (csum, size) = index.compute_csum();
998 manifest.verify_file(&file_name, &csum, size)?;
6ef9bb59 999
14f6c9cb 1000 let chunk_reader = LocalChunkReader::new(datastore, None, CryptMode::None);
6ef9bb59 1001 let reader = AsyncIndexReader::new(index, chunk_reader);
f386f512 1002 Body::wrap_stream(AsyncReaderStream::new(reader)
6ef9bb59
DC
1003 .map_err(move |err| {
1004 eprintln!("error during streaming of '{:?}' - {}", path, err);
1005 err
1006 }))
1007 },
1008 "fidx" => {
1009 let index = FixedIndexReader::open(&path)
1010 .map_err(|err| format_err!("unable to read fixed index '{:?}' - {}", &path, err))?;
1011
2d55beec
FG
1012 let (csum, size) = index.compute_csum();
1013 manifest.verify_file(&file_name, &csum, size)?;
1014
14f6c9cb 1015 let chunk_reader = LocalChunkReader::new(datastore, None, CryptMode::None);
6ef9bb59 1016 let reader = AsyncIndexReader::new(index, chunk_reader);
f386f512 1017 Body::wrap_stream(AsyncReaderStream::with_buffer_size(reader, 4*1024*1024)
6ef9bb59
DC
1018 .map_err(move |err| {
1019 eprintln!("error during streaming of '{:?}' - {}", path, err);
1020 err
1021 }))
1022 },
1023 "blob" => {
1024 let file = std::fs::File::open(&path)
8aa67ee7 1025 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
6ef9bb59 1026
2d55beec
FG
1027 // FIXME: load full blob to verify index checksum?
1028
6ef9bb59
DC
1029 Body::wrap_stream(
1030 WrappedReaderStream::new(DataBlobReader::new(file, None)?)
1031 .map_err(move |err| {
1032 eprintln!("error during streaming of '{:?}' - {}", path, err);
1033 err
1034 })
1035 )
1036 },
1037 extension => {
1038 bail!("cannot download '{}' files", extension);
1039 },
1040 };
1041
1042 // fixme: set other headers ?
1043 Ok(Response::builder()
1044 .status(StatusCode::OK)
1045 .header(header::CONTENT_TYPE, "application/octet-stream")
1046 .body(body)
1047 .unwrap())
1048 }.boxed()
1049}
1050
552c2259 1051#[sortable]
0ab08ac9
DM
1052pub const API_METHOD_UPLOAD_BACKUP_LOG: ApiMethod = ApiMethod::new(
1053 &ApiHandler::AsyncHttp(&upload_backup_log),
255f378a 1054 &ObjectSchema::new(
54552dda 1055 "Upload the client backup log file into a backup snapshot ('client.log.blob').",
552c2259 1056 &sorted!([
66c49c21 1057 ("store", false, &DATASTORE_SCHEMA),
255f378a 1058 ("backup-type", false, &BACKUP_TYPE_SCHEMA),
0ab08ac9 1059 ("backup-id", false, &BACKUP_ID_SCHEMA),
255f378a 1060 ("backup-time", false, &BACKUP_TIME_SCHEMA),
552c2259 1061 ]),
9e47c0a5 1062 )
54552dda
DM
1063).access(
1064 Some("Only the backup creator/owner is allowed to do this."),
1065 &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_BACKUP, false)
1066);
9e47c0a5 1067
07ee2235
DM
1068fn upload_backup_log(
1069 _parts: Parts,
1070 req_body: Body,
1071 param: Value,
255f378a 1072 _info: &ApiMethod,
54552dda 1073 rpcenv: Box<dyn RpcEnvironment>,
bb084b9c 1074) -> ApiResponseFuture {
07ee2235 1075
ad51d02a
DM
1076 async move {
1077 let store = tools::required_string_param(&param, "store")?;
ad51d02a 1078 let datastore = DataStore::lookup_datastore(store)?;
07ee2235 1079
96d65fbc 1080 let file_name = CLIENT_LOG_BLOB_NAME;
07ee2235 1081
ad51d02a
DM
1082 let backup_type = tools::required_string_param(&param, "backup-type")?;
1083 let backup_id = tools::required_string_param(&param, "backup-id")?;
1084 let backup_time = tools::required_integer_param(&param, "backup-time")?;
07ee2235 1085
e0e5b442 1086 let backup_dir = BackupDir::new(backup_type, backup_id, backup_time)?;
07ee2235 1087
e7cb4dc5
WB
1088 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
1089 check_backup_owner(&datastore, backup_dir.group(), &userid)?;
54552dda 1090
ad51d02a
DM
1091 let mut path = datastore.base_path();
1092 path.push(backup_dir.relative_path());
1093 path.push(&file_name);
07ee2235 1094
ad51d02a
DM
1095 if path.exists() {
1096 bail!("backup already contains a log.");
1097 }
e128d4e8 1098
ad51d02a 1099 println!("Upload backup log to {}/{}/{}/{}/{}", store,
6a7be83e 1100 backup_type, backup_id, backup_dir.backup_time_string(), file_name);
ad51d02a
DM
1101
1102 let data = req_body
1103 .map_err(Error::from)
1104 .try_fold(Vec::new(), |mut acc, chunk| {
1105 acc.extend_from_slice(&*chunk);
1106 future::ok::<_, Error>(acc)
1107 })
1108 .await?;
1109
39f18b30
DM
1110 // always verify blob/CRC at server side
1111 let blob = DataBlob::load_from_reader(&mut &data[..])?;
1112
1113 replace_file(&path, blob.raw_data(), CreateOptions::new())?;
ad51d02a
DM
1114
1115 // fixme: use correct formatter
1116 Ok(crate::server::formatter::json_response(Ok(Value::Null)))
1117 }.boxed()
07ee2235
DM
1118}
1119
5b1cfa01
DC
1120#[api(
1121 input: {
1122 properties: {
1123 store: {
1124 schema: DATASTORE_SCHEMA,
1125 },
1126 "backup-type": {
1127 schema: BACKUP_TYPE_SCHEMA,
1128 },
1129 "backup-id": {
1130 schema: BACKUP_ID_SCHEMA,
1131 },
1132 "backup-time": {
1133 schema: BACKUP_TIME_SCHEMA,
1134 },
1135 "filepath": {
1136 description: "Base64 encoded path.",
1137 type: String,
1138 }
1139 },
1140 },
1141 access: {
1142 permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP, true),
1143 },
1144)]
1145/// Get the entries of the given path of the catalog
1146fn catalog(
1147 store: String,
1148 backup_type: String,
1149 backup_id: String,
1150 backup_time: i64,
1151 filepath: String,
1152 _param: Value,
1153 _info: &ApiMethod,
1154 rpcenv: &mut dyn RpcEnvironment,
1155) -> Result<Value, Error> {
1156 let datastore = DataStore::lookup_datastore(&store)?;
1157
e7cb4dc5 1158 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
5b1cfa01 1159 let user_info = CachedUserInfo::new()?;
e7cb4dc5 1160 let user_privs = user_info.lookup_privs(&userid, &["datastore", &store]);
5b1cfa01 1161
e0e5b442 1162 let backup_dir = BackupDir::new(backup_type, backup_id, backup_time)?;
5b1cfa01
DC
1163
1164 let allowed = (user_privs & PRIV_DATASTORE_READ) != 0;
e7cb4dc5 1165 if !allowed { check_backup_owner(&datastore, backup_dir.group(), &userid)?; }
5b1cfa01 1166
9238cdf5
FG
1167 let file_name = CATALOG_NAME;
1168
2d55beec 1169 let (manifest, files) = read_backup_index(&datastore, &backup_dir)?;
9238cdf5
FG
1170 for file in files {
1171 if file.filename == file_name && file.crypt_mode == Some(CryptMode::Encrypt) {
1172 bail!("cannot decode '{}' - is encrypted", file_name);
1173 }
1174 }
1175
5b1cfa01
DC
1176 let mut path = datastore.base_path();
1177 path.push(backup_dir.relative_path());
9238cdf5 1178 path.push(file_name);
5b1cfa01
DC
1179
1180 let index = DynamicIndexReader::open(&path)
1181 .map_err(|err| format_err!("unable to read dynamic index '{:?}' - {}", &path, err))?;
1182
2d55beec
FG
1183 let (csum, size) = index.compute_csum();
1184 manifest.verify_file(&file_name, &csum, size)?;
1185
14f6c9cb 1186 let chunk_reader = LocalChunkReader::new(datastore, None, CryptMode::None);
5b1cfa01
DC
1187 let reader = BufferedDynamicReader::new(index, chunk_reader);
1188
1189 let mut catalog_reader = CatalogReader::new(reader);
1190 let mut current = catalog_reader.root()?;
1191 let mut components = vec![];
1192
1193
1194 if filepath != "root" {
1195 components = base64::decode(filepath)?;
1196 if components.len() > 0 && components[0] == '/' as u8 {
1197 components.remove(0);
1198 }
1199 for component in components.split(|c| *c == '/' as u8) {
1200 if let Some(entry) = catalog_reader.lookup(&current, component)? {
1201 current = entry;
1202 } else {
1203 bail!("path {:?} not found in catalog", &String::from_utf8_lossy(&components));
1204 }
1205 }
1206 }
1207
1208 let mut res = Vec::new();
1209
1210 for direntry in catalog_reader.read_dir(&current)? {
1211 let mut components = components.clone();
1212 components.push('/' as u8);
1213 components.extend(&direntry.name);
1214 let path = base64::encode(components);
1215 let text = String::from_utf8_lossy(&direntry.name);
1216 let mut entry = json!({
1217 "filepath": path,
1218 "text": text,
1219 "type": CatalogEntryType::from(&direntry.attr).to_string(),
1220 "leaf": true,
1221 });
1222 match direntry.attr {
1223 DirEntryAttribute::Directory { start: _ } => {
1224 entry["leaf"] = false.into();
1225 },
1226 DirEntryAttribute::File { size, mtime } => {
1227 entry["size"] = size.into();
1228 entry["mtime"] = mtime.into();
1229 },
1230 _ => {},
1231 }
1232 res.push(entry);
1233 }
1234
1235 Ok(res.into())
1236}
1237
d33d8f4e
DC
1238#[sortable]
1239pub const API_METHOD_PXAR_FILE_DOWNLOAD: ApiMethod = ApiMethod::new(
1240 &ApiHandler::AsyncHttp(&pxar_file_download),
1241 &ObjectSchema::new(
1ffe0301 1242 "Download single file from pxar file of a backup snapshot. Only works if it's not encrypted.",
d33d8f4e
DC
1243 &sorted!([
1244 ("store", false, &DATASTORE_SCHEMA),
1245 ("backup-type", false, &BACKUP_TYPE_SCHEMA),
1246 ("backup-id", false, &BACKUP_ID_SCHEMA),
1247 ("backup-time", false, &BACKUP_TIME_SCHEMA),
1248 ("filepath", false, &StringSchema::new("Base64 encoded path").schema()),
1249 ]),
1250 )
1251).access(None, &Permission::Privilege(
1252 &["datastore", "{store}"],
1253 PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP,
1254 true)
1255);
1256
1257fn pxar_file_download(
1258 _parts: Parts,
1259 _req_body: Body,
1260 param: Value,
1261 _info: &ApiMethod,
1262 rpcenv: Box<dyn RpcEnvironment>,
1263) -> ApiResponseFuture {
1264
1265 async move {
1266 let store = tools::required_string_param(&param, "store")?;
1267 let datastore = DataStore::lookup_datastore(&store)?;
1268
e7cb4dc5 1269 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
d33d8f4e 1270 let user_info = CachedUserInfo::new()?;
e7cb4dc5 1271 let user_privs = user_info.lookup_privs(&userid, &["datastore", &store]);
d33d8f4e
DC
1272
1273 let filepath = tools::required_string_param(&param, "filepath")?.to_owned();
1274
1275 let backup_type = tools::required_string_param(&param, "backup-type")?;
1276 let backup_id = tools::required_string_param(&param, "backup-id")?;
1277 let backup_time = tools::required_integer_param(&param, "backup-time")?;
1278
e0e5b442 1279 let backup_dir = BackupDir::new(backup_type, backup_id, backup_time)?;
d33d8f4e
DC
1280
1281 let allowed = (user_privs & PRIV_DATASTORE_READ) != 0;
e7cb4dc5 1282 if !allowed { check_backup_owner(&datastore, backup_dir.group(), &userid)?; }
d33d8f4e 1283
d33d8f4e
DC
1284 let mut components = base64::decode(&filepath)?;
1285 if components.len() > 0 && components[0] == '/' as u8 {
1286 components.remove(0);
1287 }
1288
1289 let mut split = components.splitn(2, |c| *c == '/' as u8);
9238cdf5 1290 let pxar_name = std::str::from_utf8(split.next().unwrap())?;
d33d8f4e 1291 let file_path = split.next().ok_or(format_err!("filepath looks strange '{}'", filepath))?;
2d55beec 1292 let (manifest, files) = read_backup_index(&datastore, &backup_dir)?;
9238cdf5
FG
1293 for file in files {
1294 if file.filename == pxar_name && file.crypt_mode == Some(CryptMode::Encrypt) {
1295 bail!("cannot decode '{}' - is encrypted", pxar_name);
1296 }
1297 }
d33d8f4e 1298
9238cdf5
FG
1299 let mut path = datastore.base_path();
1300 path.push(backup_dir.relative_path());
1301 path.push(pxar_name);
d33d8f4e
DC
1302
1303 let index = DynamicIndexReader::open(&path)
1304 .map_err(|err| format_err!("unable to read dynamic index '{:?}' - {}", &path, err))?;
1305
2d55beec
FG
1306 let (csum, size) = index.compute_csum();
1307 manifest.verify_file(&pxar_name, &csum, size)?;
1308
14f6c9cb 1309 let chunk_reader = LocalChunkReader::new(datastore, None, CryptMode::None);
d33d8f4e
DC
1310 let reader = BufferedDynamicReader::new(index, chunk_reader);
1311 let archive_size = reader.archive_size();
1312 let reader = LocalDynamicReadAt::new(reader);
1313
1314 let decoder = Accessor::new(reader, archive_size).await?;
1315 let root = decoder.open_root().await?;
1316 let file = root
1317 .lookup(OsStr::from_bytes(file_path)).await?
1318 .ok_or(format_err!("error opening '{:?}'", file_path))?;
1319
1320 let file = match file.kind() {
1321 EntryKind::File { .. } => file,
1322 EntryKind::Hardlink(_) => {
1323 decoder.follow_hardlink(&file).await?
1324 },
1325 // TODO symlink
1326 other => bail!("cannot download file of type {:?}", other),
1327 };
1328
1329 let body = Body::wrap_stream(
1330 AsyncReaderStream::new(file.contents().await?)
1331 .map_err(move |err| {
1332 eprintln!("error during streaming of '{:?}' - {}", filepath, err);
1333 err
1334 })
1335 );
1336
1337 // fixme: set other headers ?
1338 Ok(Response::builder()
1339 .status(StatusCode::OK)
1340 .header(header::CONTENT_TYPE, "application/octet-stream")
1341 .body(body)
1342 .unwrap())
1343 }.boxed()
1344}
1345
1a0d3d11
DM
1346#[api(
1347 input: {
1348 properties: {
1349 store: {
1350 schema: DATASTORE_SCHEMA,
1351 },
1352 timeframe: {
1353 type: RRDTimeFrameResolution,
1354 },
1355 cf: {
1356 type: RRDMode,
1357 },
1358 },
1359 },
1360 access: {
1361 permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP, true),
1362 },
1363)]
1364/// Read datastore stats
1365fn get_rrd_stats(
1366 store: String,
1367 timeframe: RRDTimeFrameResolution,
1368 cf: RRDMode,
1369 _param: Value,
1370) -> Result<Value, Error> {
1371
431cc7b1
DC
1372 create_value_from_rrd(
1373 &format!("datastore/{}", store),
1a0d3d11
DM
1374 &[
1375 "total", "used",
c94e1f65
DM
1376 "read_ios", "read_bytes",
1377 "write_ios", "write_bytes",
1378 "io_ticks",
1a0d3d11
DM
1379 ],
1380 timeframe,
1381 cf,
1382 )
1383}
1384
912b3f5b
DM
1385#[api(
1386 input: {
1387 properties: {
1388 store: {
1389 schema: DATASTORE_SCHEMA,
1390 },
1391 "backup-type": {
1392 schema: BACKUP_TYPE_SCHEMA,
1393 },
1394 "backup-id": {
1395 schema: BACKUP_ID_SCHEMA,
1396 },
1397 "backup-time": {
1398 schema: BACKUP_TIME_SCHEMA,
1399 },
1400 },
1401 },
1402 access: {
1403 permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP, true),
1404 },
1405)]
1406/// Get "notes" for a specific backup
1407fn get_notes(
1408 store: String,
1409 backup_type: String,
1410 backup_id: String,
1411 backup_time: i64,
1412 rpcenv: &mut dyn RpcEnvironment,
1413) -> Result<String, Error> {
1414 let datastore = DataStore::lookup_datastore(&store)?;
1415
e7cb4dc5 1416 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
912b3f5b 1417 let user_info = CachedUserInfo::new()?;
e7cb4dc5 1418 let user_privs = user_info.lookup_privs(&userid, &["datastore", &store]);
912b3f5b 1419
e0e5b442 1420 let backup_dir = BackupDir::new(backup_type, backup_id, backup_time)?;
912b3f5b
DM
1421
1422 let allowed = (user_privs & PRIV_DATASTORE_READ) != 0;
e7cb4dc5 1423 if !allowed { check_backup_owner(&datastore, backup_dir.group(), &userid)?; }
912b3f5b
DM
1424
1425 let manifest = datastore.load_manifest_json(&backup_dir)?;
1426
1427 let notes = manifest["unprotected"]["notes"]
1428 .as_str()
1429 .unwrap_or("");
1430
1431 Ok(String::from(notes))
1432}
1433
1434#[api(
1435 input: {
1436 properties: {
1437 store: {
1438 schema: DATASTORE_SCHEMA,
1439 },
1440 "backup-type": {
1441 schema: BACKUP_TYPE_SCHEMA,
1442 },
1443 "backup-id": {
1444 schema: BACKUP_ID_SCHEMA,
1445 },
1446 "backup-time": {
1447 schema: BACKUP_TIME_SCHEMA,
1448 },
1449 notes: {
1450 description: "A multiline text.",
1451 },
1452 },
1453 },
1454 access: {
1455 permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_MODIFY, true),
1456 },
1457)]
1458/// Set "notes" for a specific backup
1459fn set_notes(
1460 store: String,
1461 backup_type: String,
1462 backup_id: String,
1463 backup_time: i64,
1464 notes: String,
1465 rpcenv: &mut dyn RpcEnvironment,
1466) -> Result<(), Error> {
1467 let datastore = DataStore::lookup_datastore(&store)?;
1468
e7cb4dc5 1469 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
912b3f5b 1470 let user_info = CachedUserInfo::new()?;
e7cb4dc5 1471 let user_privs = user_info.lookup_privs(&userid, &["datastore", &store]);
912b3f5b 1472
e0e5b442 1473 let backup_dir = BackupDir::new(backup_type, backup_id, backup_time)?;
912b3f5b
DM
1474
1475 let allowed = (user_privs & PRIV_DATASTORE_READ) != 0;
e7cb4dc5 1476 if !allowed { check_backup_owner(&datastore, backup_dir.group(), &userid)?; }
912b3f5b
DM
1477
1478 let mut manifest = datastore.load_manifest_json(&backup_dir)?;
1479
1480 manifest["unprotected"]["notes"] = notes.into();
1481
1482 datastore.store_manifest(&backup_dir, manifest)?;
1483
1484 Ok(())
1485}
1486
552c2259 1487#[sortable]
255f378a 1488const DATASTORE_INFO_SUBDIRS: SubdirMap = &[
5b1cfa01
DC
1489 (
1490 "catalog",
1491 &Router::new()
1492 .get(&API_METHOD_CATALOG)
1493 ),
255f378a
DM
1494 (
1495 "download",
1496 &Router::new()
1497 .download(&API_METHOD_DOWNLOAD_FILE)
1498 ),
6ef9bb59
DC
1499 (
1500 "download-decoded",
1501 &Router::new()
1502 .download(&API_METHOD_DOWNLOAD_FILE_DECODED)
1503 ),
255f378a
DM
1504 (
1505 "files",
1506 &Router::new()
09b1f7b2 1507 .get(&API_METHOD_LIST_SNAPSHOT_FILES)
255f378a
DM
1508 ),
1509 (
1510 "gc",
1511 &Router::new()
1512 .get(&API_METHOD_GARBAGE_COLLECTION_STATUS)
1513 .post(&API_METHOD_START_GARBAGE_COLLECTION)
1514 ),
1515 (
1516 "groups",
1517 &Router::new()
b31c8019 1518 .get(&API_METHOD_LIST_GROUPS)
255f378a 1519 ),
912b3f5b
DM
1520 (
1521 "notes",
1522 &Router::new()
1523 .get(&API_METHOD_GET_NOTES)
1524 .put(&API_METHOD_SET_NOTES)
1525 ),
255f378a
DM
1526 (
1527 "prune",
1528 &Router::new()
1529 .post(&API_METHOD_PRUNE)
1530 ),
d33d8f4e
DC
1531 (
1532 "pxar-file-download",
1533 &Router::new()
1534 .download(&API_METHOD_PXAR_FILE_DOWNLOAD)
1535 ),
1a0d3d11
DM
1536 (
1537 "rrd",
1538 &Router::new()
1539 .get(&API_METHOD_GET_RRD_STATS)
1540 ),
255f378a
DM
1541 (
1542 "snapshots",
1543 &Router::new()
fc189b19 1544 .get(&API_METHOD_LIST_SNAPSHOTS)
68a6a0ee 1545 .delete(&API_METHOD_DELETE_SNAPSHOT)
255f378a
DM
1546 ),
1547 (
1548 "status",
1549 &Router::new()
1550 .get(&API_METHOD_STATUS)
1551 ),
1552 (
1553 "upload-backup-log",
1554 &Router::new()
1555 .upload(&API_METHOD_UPLOAD_BACKUP_LOG)
1556 ),
c2009e53
DM
1557 (
1558 "verify",
1559 &Router::new()
1560 .post(&API_METHOD_VERIFY)
1561 ),
255f378a
DM
1562];
1563
ad51d02a 1564const DATASTORE_INFO_ROUTER: Router = Router::new()
255f378a
DM
1565 .get(&list_subdirs_api_method!(DATASTORE_INFO_SUBDIRS))
1566 .subdirs(DATASTORE_INFO_SUBDIRS);
1567
1568
1569pub const ROUTER: Router = Router::new()
bb34b589 1570 .get(&API_METHOD_GET_DATASTORE_LIST)
255f378a 1571 .match_all("store", &DATASTORE_INFO_ROUTER);