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