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