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