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