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