]>
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 | ||
d20137e5 | 591 | // only include groups with snapshots, counting/displaying empty groups can confuse |
f12f408e TL |
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 | 649 | match user_info.any_privs_below(&auth_id, &["datastore", &store], NS_PRIVS_OK) { |
d20137e5 | 650 | // avoid leaking existence info if users hasn't at least any priv. below |
2981cdd4 TL |
651 | Ok(false) | Err(_) => return Err(http_err!(FORBIDDEN, "permission check failed")), |
652 | _ => false, | |
653 | } | |
84de1012 | 654 | }; |
d20137e5 | 655 | let datastore = datastore?; // only unwrap no to avoid leaking existence 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 | 676 | Ok(if store_stats { |
1cc73a43 | 677 | let storage = proxmox_sys::fs::fs_info(&datastore.base_path())?; |
84de1012 TL |
678 | DataStoreStatus { |
679 | total: storage.total, | |
680 | used: storage.used, | |
1cc73a43 | 681 | avail: storage.available, |
84de1012 TL |
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(), | |
dc7a5b34 | 1705 | )); |
984ddb2f DC |
1706 | let zstdstream = ZstdEncoder::new(ReceiverStream::new(receiver))?; |
1707 | Body::wrap_stream(zstdstream.map_err(move |err| { | |
0608b36b | 1708 | log::error!("error during streaming of tar.zst '{:?}' - {}", path, err); |
984ddb2f DC |
1709 | err |
1710 | })) | |
1711 | } else { | |
dc7a5b34 TL |
1712 | proxmox_rest_server::spawn_internal_task(create_zip( |
1713 | channelwriter, | |
1714 | decoder, | |
1715 | path.clone(), | |
dc7a5b34 | 1716 | )); |
984ddb2f | 1717 | Body::wrap_stream(ReceiverStream::new(receiver).map_err(move |err| { |
0608b36b | 1718 | log::error!("error during streaming of zip '{:?}' - {}", path, err); |
984ddb2f DC |
1719 | err |
1720 | })) | |
1721 | } | |
804f6143 DC |
1722 | } |
1723 | other => bail!("cannot download file of type {:?}", other), | |
1724 | }; | |
d33d8f4e DC |
1725 | |
1726 | // fixme: set other headers ? | |
1727 | Ok(Response::builder() | |
dc7a5b34 TL |
1728 | .status(StatusCode::OK) |
1729 | .header(header::CONTENT_TYPE, "application/octet-stream") | |
1730 | .body(body) | |
1731 | .unwrap()) | |
1732 | } | |
1733 | .boxed() | |
d33d8f4e DC |
1734 | } |
1735 | ||
1a0d3d11 DM |
1736 | #[api( |
1737 | input: { | |
1738 | properties: { | |
1739 | store: { | |
1740 | schema: DATASTORE_SCHEMA, | |
1741 | }, | |
1742 | timeframe: { | |
c68fa58a | 1743 | type: RRDTimeFrame, |
1a0d3d11 DM |
1744 | }, |
1745 | cf: { | |
1746 | type: RRDMode, | |
1747 | }, | |
1748 | }, | |
1749 | }, | |
1750 | access: { | |
7d6fc15b TL |
1751 | permission: &Permission::Privilege( |
1752 | &["datastore", "{store}"], PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP, true), | |
1a0d3d11 DM |
1753 | }, |
1754 | )] | |
1755 | /// Read datastore stats | |
bf78f708 | 1756 | pub fn get_rrd_stats( |
1a0d3d11 | 1757 | store: String, |
c68fa58a | 1758 | timeframe: RRDTimeFrame, |
1a0d3d11 DM |
1759 | cf: RRDMode, |
1760 | _param: Value, | |
1761 | ) -> Result<Value, Error> { | |
e9d2fc93 | 1762 | let datastore = DataStore::lookup_datastore(&store, Some(Operation::Read))?; |
f27b6086 DC |
1763 | let disk_manager = crate::tools::disks::DiskManage::new(); |
1764 | ||
1765 | let mut rrd_fields = vec![ | |
dc7a5b34 TL |
1766 | "total", |
1767 | "used", | |
1768 | "read_ios", | |
1769 | "read_bytes", | |
1770 | "write_ios", | |
1771 | "write_bytes", | |
f27b6086 DC |
1772 | ]; |
1773 | ||
1774 | // we do not have io_ticks for zpools, so don't include them | |
1775 | match disk_manager.find_mounted_device(&datastore.base_path()) { | |
dc7a5b34 | 1776 | Ok(Some((fs_type, _, _))) if fs_type.as_str() == "zfs" => {} |
f27b6086 DC |
1777 | _ => rrd_fields.push("io_ticks"), |
1778 | }; | |
1779 | ||
dc7a5b34 | 1780 | create_value_from_rrd(&format!("datastore/{}", store), &rrd_fields, timeframe, cf) |
1a0d3d11 DM |
1781 | } |
1782 | ||
5fd823c3 HL |
1783 | #[api( |
1784 | input: { | |
1785 | properties: { | |
1786 | store: { | |
1787 | schema: DATASTORE_SCHEMA, | |
1788 | }, | |
1789 | }, | |
1790 | }, | |
1791 | access: { | |
1792 | permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_AUDIT, true), | |
1793 | }, | |
1794 | )] | |
1795 | /// Read datastore stats | |
dc7a5b34 | 1796 | pub fn get_active_operations(store: String, _param: Value) -> Result<Value, Error> { |
5fd823c3 HL |
1797 | let active_operations = task_tracking::get_active_operations(&store)?; |
1798 | Ok(json!({ | |
1799 | "read": active_operations.read, | |
1800 | "write": active_operations.write, | |
1801 | })) | |
1802 | } | |
1803 | ||
d6688884 SR |
1804 | #[api( |
1805 | input: { | |
1806 | properties: { | |
988d575d | 1807 | store: { schema: DATASTORE_SCHEMA }, |
bc21ade2 | 1808 | ns: { |
133d718f WB |
1809 | type: BackupNamespace, |
1810 | optional: true, | |
1811 | }, | |
8c74349b WB |
1812 | backup_group: { |
1813 | type: pbs_api_types::BackupGroup, | |
1814 | flatten: true, | |
1815 | }, | |
d6688884 SR |
1816 | }, |
1817 | }, | |
1818 | access: { | |
7d6fc15b TL |
1819 | permission: &Permission::Anybody, |
1820 | description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_AUDIT for any \ | |
1821 | or DATASTORE_BACKUP and being the owner of the group", | |
d6688884 SR |
1822 | }, |
1823 | )] | |
1824 | /// Get "notes" for a backup group | |
1825 | pub fn get_group_notes( | |
1826 | store: String, | |
bc21ade2 | 1827 | ns: Option<BackupNamespace>, |
8c74349b | 1828 | backup_group: pbs_api_types::BackupGroup, |
d6688884 SR |
1829 | rpcenv: &mut dyn RpcEnvironment, |
1830 | ) -> Result<String, Error> { | |
d6688884 | 1831 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
abd82485 | 1832 | let ns = ns.unwrap_or_default(); |
ea2e91e5 | 1833 | |
7a404dc5 | 1834 | let datastore = check_privs_and_load_store( |
abd82485 FG |
1835 | &store, |
1836 | &ns, | |
7d6fc15b | 1837 | &auth_id, |
2bc2435a FG |
1838 | PRIV_DATASTORE_AUDIT, |
1839 | PRIV_DATASTORE_BACKUP, | |
c9396984 | 1840 | Some(Operation::Read), |
c9396984 FG |
1841 | &backup_group, |
1842 | )?; | |
d6688884 | 1843 | |
abd82485 | 1844 | let note_path = get_group_note_path(&datastore, &ns, &backup_group); |
d6688884 SR |
1845 | Ok(file_read_optional_string(note_path)?.unwrap_or_else(|| "".to_owned())) |
1846 | } | |
1847 | ||
1848 | #[api( | |
1849 | input: { | |
1850 | properties: { | |
988d575d | 1851 | store: { schema: DATASTORE_SCHEMA }, |
bc21ade2 | 1852 | ns: { |
133d718f WB |
1853 | type: BackupNamespace, |
1854 | optional: true, | |
1855 | }, | |
8c74349b WB |
1856 | backup_group: { |
1857 | type: pbs_api_types::BackupGroup, | |
1858 | flatten: true, | |
1859 | }, | |
d6688884 SR |
1860 | notes: { |
1861 | description: "A multiline text.", | |
1862 | }, | |
1863 | }, | |
1864 | }, | |
1865 | access: { | |
7d6fc15b TL |
1866 | permission: &Permission::Anybody, |
1867 | description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any \ | |
1868 | or DATASTORE_BACKUP and being the owner of the group", | |
d6688884 SR |
1869 | }, |
1870 | )] | |
1871 | /// Set "notes" for a backup group | |
1872 | pub fn set_group_notes( | |
1873 | store: String, | |
bc21ade2 | 1874 | ns: Option<BackupNamespace>, |
8c74349b | 1875 | backup_group: pbs_api_types::BackupGroup, |
d6688884 SR |
1876 | notes: String, |
1877 | rpcenv: &mut dyn RpcEnvironment, | |
1878 | ) -> Result<(), Error> { | |
d6688884 | 1879 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
abd82485 FG |
1880 | let ns = ns.unwrap_or_default(); |
1881 | ||
7a404dc5 | 1882 | let datastore = check_privs_and_load_store( |
abd82485 FG |
1883 | &store, |
1884 | &ns, | |
7d6fc15b | 1885 | &auth_id, |
2bc2435a FG |
1886 | PRIV_DATASTORE_MODIFY, |
1887 | PRIV_DATASTORE_BACKUP, | |
c9396984 | 1888 | Some(Operation::Write), |
c9396984 FG |
1889 | &backup_group, |
1890 | )?; | |
d6688884 | 1891 | |
abd82485 | 1892 | let note_path = get_group_note_path(&datastore, &ns, &backup_group); |
e0a19d33 | 1893 | replace_file(note_path, notes.as_bytes(), CreateOptions::new(), false)?; |
d6688884 SR |
1894 | |
1895 | Ok(()) | |
1896 | } | |
1897 | ||
912b3f5b DM |
1898 | #[api( |
1899 | input: { | |
1900 | properties: { | |
988d575d | 1901 | store: { schema: DATASTORE_SCHEMA }, |
bc21ade2 | 1902 | ns: { |
133d718f WB |
1903 | type: BackupNamespace, |
1904 | optional: true, | |
1905 | }, | |
8c74349b WB |
1906 | backup_dir: { |
1907 | type: pbs_api_types::BackupDir, | |
1908 | flatten: true, | |
1909 | }, | |
912b3f5b DM |
1910 | }, |
1911 | }, | |
1912 | access: { | |
7d6fc15b TL |
1913 | permission: &Permission::Anybody, |
1914 | description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_AUDIT for any \ | |
1915 | or DATASTORE_BACKUP and being the owner of the group", | |
912b3f5b DM |
1916 | }, |
1917 | )] | |
1918 | /// Get "notes" for a specific backup | |
bf78f708 | 1919 | pub fn get_notes( |
912b3f5b | 1920 | store: String, |
bc21ade2 | 1921 | ns: Option<BackupNamespace>, |
8c74349b | 1922 | backup_dir: pbs_api_types::BackupDir, |
912b3f5b DM |
1923 | rpcenv: &mut dyn RpcEnvironment, |
1924 | ) -> Result<String, Error> { | |
7d6fc15b | 1925 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
abd82485 | 1926 | let ns = ns.unwrap_or_default(); |
ea2e91e5 | 1927 | |
7a404dc5 | 1928 | let datastore = check_privs_and_load_store( |
abd82485 FG |
1929 | &store, |
1930 | &ns, | |
7d6fc15b | 1931 | &auth_id, |
2bc2435a FG |
1932 | PRIV_DATASTORE_AUDIT, |
1933 | PRIV_DATASTORE_BACKUP, | |
c9396984 | 1934 | Some(Operation::Read), |
c9396984 FG |
1935 | &backup_dir.group, |
1936 | )?; | |
912b3f5b | 1937 | |
fbfb64a6 | 1938 | let backup_dir = datastore.backup_dir(ns, backup_dir)?; |
912b3f5b | 1939 | |
133d718f | 1940 | let (manifest, _) = backup_dir.load_manifest()?; |
912b3f5b | 1941 | |
dc7a5b34 | 1942 | let notes = manifest.unprotected["notes"].as_str().unwrap_or(""); |
912b3f5b DM |
1943 | |
1944 | Ok(String::from(notes)) | |
1945 | } | |
1946 | ||
1947 | #[api( | |
1948 | input: { | |
1949 | properties: { | |
988d575d | 1950 | store: { schema: DATASTORE_SCHEMA }, |
bc21ade2 | 1951 | ns: { |
133d718f WB |
1952 | type: BackupNamespace, |
1953 | optional: true, | |
1954 | }, | |
8c74349b WB |
1955 | backup_dir: { |
1956 | type: pbs_api_types::BackupDir, | |
1957 | flatten: true, | |
1958 | }, | |
912b3f5b DM |
1959 | notes: { |
1960 | description: "A multiline text.", | |
1961 | }, | |
1962 | }, | |
1963 | }, | |
1964 | access: { | |
7d6fc15b TL |
1965 | permission: &Permission::Anybody, |
1966 | description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any \ | |
1967 | or DATASTORE_BACKUP and being the owner of the group", | |
912b3f5b DM |
1968 | }, |
1969 | )] | |
1970 | /// Set "notes" for a specific backup | |
bf78f708 | 1971 | pub fn set_notes( |
912b3f5b | 1972 | store: String, |
bc21ade2 | 1973 | ns: Option<BackupNamespace>, |
8c74349b | 1974 | backup_dir: pbs_api_types::BackupDir, |
912b3f5b DM |
1975 | notes: String, |
1976 | rpcenv: &mut dyn RpcEnvironment, | |
1977 | ) -> Result<(), Error> { | |
7d6fc15b | 1978 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
abd82485 | 1979 | let ns = ns.unwrap_or_default(); |
ea2e91e5 | 1980 | |
7a404dc5 | 1981 | let datastore = check_privs_and_load_store( |
abd82485 FG |
1982 | &store, |
1983 | &ns, | |
7d6fc15b | 1984 | &auth_id, |
2bc2435a FG |
1985 | PRIV_DATASTORE_MODIFY, |
1986 | PRIV_DATASTORE_BACKUP, | |
c9396984 | 1987 | Some(Operation::Write), |
c9396984 FG |
1988 | &backup_dir.group, |
1989 | )?; | |
912b3f5b | 1990 | |
fbfb64a6 | 1991 | let backup_dir = datastore.backup_dir(ns, backup_dir)?; |
912b3f5b | 1992 | |
133d718f WB |
1993 | backup_dir |
1994 | .update_manifest(|manifest| { | |
dc7a5b34 TL |
1995 | manifest.unprotected["notes"] = notes.into(); |
1996 | }) | |
1997 | .map_err(|err| format_err!("unable to update manifest blob - {}", err))?; | |
912b3f5b DM |
1998 | |
1999 | Ok(()) | |
2000 | } | |
2001 | ||
8292d3d2 DC |
2002 | #[api( |
2003 | input: { | |
2004 | properties: { | |
988d575d | 2005 | store: { schema: DATASTORE_SCHEMA }, |
bc21ade2 | 2006 | ns: { |
133d718f WB |
2007 | type: BackupNamespace, |
2008 | optional: true, | |
2009 | }, | |
8c74349b WB |
2010 | backup_dir: { |
2011 | type: pbs_api_types::BackupDir, | |
2012 | flatten: true, | |
2013 | }, | |
8292d3d2 DC |
2014 | }, |
2015 | }, | |
2016 | access: { | |
7d6fc15b TL |
2017 | permission: &Permission::Anybody, |
2018 | description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_AUDIT for any \ | |
2019 | or DATASTORE_BACKUP and being the owner of the group", | |
8292d3d2 DC |
2020 | }, |
2021 | )] | |
2022 | /// Query protection for a specific backup | |
2023 | pub fn get_protection( | |
2024 | store: String, | |
bc21ade2 | 2025 | ns: Option<BackupNamespace>, |
8c74349b | 2026 | backup_dir: pbs_api_types::BackupDir, |
8292d3d2 DC |
2027 | rpcenv: &mut dyn RpcEnvironment, |
2028 | ) -> Result<bool, Error> { | |
7d6fc15b | 2029 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
abd82485 | 2030 | let ns = ns.unwrap_or_default(); |
7a404dc5 | 2031 | let datastore = check_privs_and_load_store( |
abd82485 FG |
2032 | &store, |
2033 | &ns, | |
7d6fc15b | 2034 | &auth_id, |
2bc2435a FG |
2035 | PRIV_DATASTORE_AUDIT, |
2036 | PRIV_DATASTORE_BACKUP, | |
c9396984 | 2037 | Some(Operation::Read), |
c9396984 FG |
2038 | &backup_dir.group, |
2039 | )?; | |
8292d3d2 | 2040 | |
fbfb64a6 | 2041 | let backup_dir = datastore.backup_dir(ns, backup_dir)?; |
8292d3d2 | 2042 | |
6da20161 | 2043 | Ok(backup_dir.is_protected()) |
8292d3d2 DC |
2044 | } |
2045 | ||
2046 | #[api( | |
2047 | input: { | |
2048 | properties: { | |
988d575d | 2049 | store: { schema: DATASTORE_SCHEMA }, |
bc21ade2 | 2050 | ns: { |
133d718f WB |
2051 | type: BackupNamespace, |
2052 | optional: true, | |
2053 | }, | |
8c74349b WB |
2054 | backup_dir: { |
2055 | type: pbs_api_types::BackupDir, | |
2056 | flatten: true, | |
2057 | }, | |
8292d3d2 DC |
2058 | protected: { |
2059 | description: "Enable/disable protection.", | |
2060 | }, | |
2061 | }, | |
2062 | }, | |
2063 | access: { | |
7d6fc15b TL |
2064 | permission: &Permission::Anybody, |
2065 | description: "Requires on /datastore/{store}[/{namespace}] either DATASTORE_MODIFY for any \ | |
2066 | or DATASTORE_BACKUP and being the owner of the group", | |
8292d3d2 DC |
2067 | }, |
2068 | )] | |
2069 | /// En- or disable protection for a specific backup | |
2070 | pub fn set_protection( | |
2071 | store: String, | |
bc21ade2 | 2072 | ns: Option<BackupNamespace>, |
8c74349b | 2073 | backup_dir: pbs_api_types::BackupDir, |
8292d3d2 DC |
2074 | protected: bool, |
2075 | rpcenv: &mut dyn RpcEnvironment, | |
2076 | ) -> Result<(), Error> { | |
7d6fc15b | 2077 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
abd82485 | 2078 | let ns = ns.unwrap_or_default(); |
7a404dc5 | 2079 | let datastore = check_privs_and_load_store( |
abd82485 FG |
2080 | &store, |
2081 | &ns, | |
7d6fc15b | 2082 | &auth_id, |
2bc2435a FG |
2083 | PRIV_DATASTORE_MODIFY, |
2084 | PRIV_DATASTORE_BACKUP, | |
c9396984 | 2085 | Some(Operation::Write), |
c9396984 FG |
2086 | &backup_dir.group, |
2087 | )?; | |
8292d3d2 | 2088 | |
fbfb64a6 | 2089 | let backup_dir = datastore.backup_dir(ns, backup_dir)?; |
8292d3d2 | 2090 | |
8292d3d2 DC |
2091 | datastore.update_protection(&backup_dir, protected) |
2092 | } | |
2093 | ||
72be0eb1 | 2094 | #[api( |
4940012d | 2095 | input: { |
72be0eb1 | 2096 | properties: { |
988d575d | 2097 | store: { schema: DATASTORE_SCHEMA }, |
bc21ade2 | 2098 | ns: { |
133d718f WB |
2099 | type: BackupNamespace, |
2100 | optional: true, | |
2101 | }, | |
8c74349b WB |
2102 | backup_group: { |
2103 | type: pbs_api_types::BackupGroup, | |
2104 | flatten: true, | |
2105 | }, | |
72be0eb1 | 2106 | "new-owner": { |
e6dc35ac | 2107 | type: Authid, |
72be0eb1 DW |
2108 | }, |
2109 | }, | |
4940012d FG |
2110 | }, |
2111 | access: { | |
bff85572 | 2112 | permission: &Permission::Anybody, |
7d6fc15b TL |
2113 | description: "Datastore.Modify on whole datastore, or changing ownership between user and \ |
2114 | a user's token for owned backups with Datastore.Backup" | |
4940012d | 2115 | }, |
72be0eb1 DW |
2116 | )] |
2117 | /// Change owner of a backup group | |
bf78f708 | 2118 | pub fn set_backup_owner( |
72be0eb1 | 2119 | store: String, |
bc21ade2 | 2120 | ns: Option<BackupNamespace>, |
8c74349b | 2121 | backup_group: pbs_api_types::BackupGroup, |
e6dc35ac | 2122 | new_owner: Authid, |
bff85572 | 2123 | rpcenv: &mut dyn RpcEnvironment, |
72be0eb1 | 2124 | ) -> Result<(), Error> { |
bff85572 | 2125 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
abd82485 | 2126 | let ns = ns.unwrap_or_default(); |
ea2e91e5 | 2127 | let owner_check_required = check_ns_privs_full( |
abd82485 FG |
2128 | &store, |
2129 | &ns, | |
a724f5fd | 2130 | &auth_id, |
2bc2435a FG |
2131 | PRIV_DATASTORE_MODIFY, |
2132 | PRIV_DATASTORE_BACKUP, | |
a724f5fd | 2133 | )?; |
1909ece2 | 2134 | |
abd82485 | 2135 | let datastore = DataStore::lookup_datastore(&store, Some(Operation::Write))?; |
1909ece2 | 2136 | |
abd82485 | 2137 | let backup_group = datastore.backup_group(ns, backup_group); |
bff85572 | 2138 | |
2bc2435a | 2139 | if owner_check_required { |
133d718f | 2140 | let owner = backup_group.get_owner()?; |
bff85572 | 2141 | |
2bc2435a | 2142 | let allowed = match (owner.is_token(), new_owner.is_token()) { |
bff85572 FG |
2143 | (true, true) => { |
2144 | // API token to API token, owned by same user | |
2145 | let owner = owner.user(); | |
2146 | let new_owner = new_owner.user(); | |
2147 | owner == new_owner && Authid::from(owner.clone()) == auth_id | |
dc7a5b34 | 2148 | } |
bff85572 FG |
2149 | (true, false) => { |
2150 | // API token to API token owner | |
dc7a5b34 TL |
2151 | Authid::from(owner.user().clone()) == auth_id && new_owner == auth_id |
2152 | } | |
bff85572 FG |
2153 | (false, true) => { |
2154 | // API token owner to API token | |
dc7a5b34 TL |
2155 | owner == auth_id && Authid::from(new_owner.user().clone()) == auth_id |
2156 | } | |
bff85572 FG |
2157 | (false, false) => { |
2158 | // User to User, not allowed for unprivileged users | |
2159 | false | |
dc7a5b34 | 2160 | } |
2bc2435a | 2161 | }; |
bff85572 | 2162 | |
2bc2435a FG |
2163 | if !allowed { |
2164 | return Err(http_err!( | |
2165 | UNAUTHORIZED, | |
2166 | "{} does not have permission to change owner of backup group '{}' to {}", | |
2167 | auth_id, | |
e13303fc | 2168 | backup_group.group(), |
2bc2435a FG |
2169 | new_owner, |
2170 | )); | |
2171 | } | |
bff85572 FG |
2172 | } |
2173 | ||
7d6fc15b TL |
2174 | let user_info = CachedUserInfo::new()?; |
2175 | ||
e6dc35ac | 2176 | if !user_info.is_active_auth_id(&new_owner) { |
dc7a5b34 TL |
2177 | bail!( |
2178 | "{} '{}' is inactive or non-existent", | |
2179 | if new_owner.is_token() { | |
2180 | "API token".to_string() | |
2181 | } else { | |
2182 | "user".to_string() | |
2183 | }, | |
2184 | new_owner | |
2185 | ); | |
72be0eb1 DW |
2186 | } |
2187 | ||
133d718f | 2188 | backup_group.set_owner(&new_owner, true)?; |
72be0eb1 DW |
2189 | |
2190 | Ok(()) | |
2191 | } | |
2192 | ||
552c2259 | 2193 | #[sortable] |
255f378a | 2194 | const DATASTORE_INFO_SUBDIRS: SubdirMap = &[ |
5fd823c3 HL |
2195 | ( |
2196 | "active-operations", | |
dc7a5b34 | 2197 | &Router::new().get(&API_METHOD_GET_ACTIVE_OPERATIONS), |
5b1cfa01 | 2198 | ), |
dc7a5b34 | 2199 | ("catalog", &Router::new().get(&API_METHOD_CATALOG)), |
72be0eb1 DW |
2200 | ( |
2201 | "change-owner", | |
dc7a5b34 | 2202 | &Router::new().post(&API_METHOD_SET_BACKUP_OWNER), |
72be0eb1 | 2203 | ), |
255f378a DM |
2204 | ( |
2205 | "download", | |
dc7a5b34 | 2206 | &Router::new().download(&API_METHOD_DOWNLOAD_FILE), |
255f378a | 2207 | ), |
6ef9bb59 DC |
2208 | ( |
2209 | "download-decoded", | |
dc7a5b34 | 2210 | &Router::new().download(&API_METHOD_DOWNLOAD_FILE_DECODED), |
255f378a | 2211 | ), |
dc7a5b34 | 2212 | ("files", &Router::new().get(&API_METHOD_LIST_SNAPSHOT_FILES)), |
255f378a DM |
2213 | ( |
2214 | "gc", | |
2215 | &Router::new() | |
2216 | .get(&API_METHOD_GARBAGE_COLLECTION_STATUS) | |
dc7a5b34 | 2217 | .post(&API_METHOD_START_GARBAGE_COLLECTION), |
255f378a | 2218 | ), |
d6688884 SR |
2219 | ( |
2220 | "group-notes", | |
2221 | &Router::new() | |
2222 | .get(&API_METHOD_GET_GROUP_NOTES) | |
dc7a5b34 | 2223 | .put(&API_METHOD_SET_GROUP_NOTES), |
d6688884 | 2224 | ), |
255f378a DM |
2225 | ( |
2226 | "groups", | |
2227 | &Router::new() | |
b31c8019 | 2228 | .get(&API_METHOD_LIST_GROUPS) |
dc7a5b34 | 2229 | .delete(&API_METHOD_DELETE_GROUP), |
255f378a | 2230 | ), |
18934ae5 TL |
2231 | ( |
2232 | "namespace", | |
2233 | // FIXME: move into datastore:: sub-module?! | |
2234 | &crate::api2::admin::namespace::ROUTER, | |
2235 | ), | |
912b3f5b DM |
2236 | ( |
2237 | "notes", | |
2238 | &Router::new() | |
2239 | .get(&API_METHOD_GET_NOTES) | |
dc7a5b34 | 2240 | .put(&API_METHOD_SET_NOTES), |
912b3f5b | 2241 | ), |
8292d3d2 DC |
2242 | ( |
2243 | "protected", | |
2244 | &Router::new() | |
2245 | .get(&API_METHOD_GET_PROTECTION) | |
dc7a5b34 | 2246 | .put(&API_METHOD_SET_PROTECTION), |
255f378a | 2247 | ), |
dc7a5b34 | 2248 | ("prune", &Router::new().post(&API_METHOD_PRUNE)), |
9805207a DC |
2249 | ( |
2250 | "prune-datastore", | |
dc7a5b34 | 2251 | &Router::new().post(&API_METHOD_PRUNE_DATASTORE), |
9805207a | 2252 | ), |
d33d8f4e DC |
2253 | ( |
2254 | "pxar-file-download", | |
dc7a5b34 | 2255 | &Router::new().download(&API_METHOD_PXAR_FILE_DOWNLOAD), |
1a0d3d11 | 2256 | ), |
dc7a5b34 | 2257 | ("rrd", &Router::new().get(&API_METHOD_GET_RRD_STATS)), |
255f378a DM |
2258 | ( |
2259 | "snapshots", | |
2260 | &Router::new() | |
fc189b19 | 2261 | .get(&API_METHOD_LIST_SNAPSHOTS) |
dc7a5b34 | 2262 | .delete(&API_METHOD_DELETE_SNAPSHOT), |
255f378a | 2263 | ), |
dc7a5b34 | 2264 | ("status", &Router::new().get(&API_METHOD_STATUS)), |
255f378a DM |
2265 | ( |
2266 | "upload-backup-log", | |
dc7a5b34 | 2267 | &Router::new().upload(&API_METHOD_UPLOAD_BACKUP_LOG), |
c2009e53 | 2268 | ), |
dc7a5b34 | 2269 | ("verify", &Router::new().post(&API_METHOD_VERIFY)), |
255f378a DM |
2270 | ]; |
2271 | ||
ad51d02a | 2272 | const DATASTORE_INFO_ROUTER: Router = Router::new() |
255f378a DM |
2273 | .get(&list_subdirs_api_method!(DATASTORE_INFO_SUBDIRS)) |
2274 | .subdirs(DATASTORE_INFO_SUBDIRS); | |
2275 | ||
255f378a | 2276 | pub const ROUTER: Router = Router::new() |
bb34b589 | 2277 | .get(&API_METHOD_GET_DATASTORE_LIST) |
255f378a | 2278 | .match_all("store", &DATASTORE_INFO_ROUTER); |