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