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