]>
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; |
cad540e9 | 7 | |
6ef9bb59 | 8 | use anyhow::{bail, format_err, Error}; |
9e47c0a5 | 9 | use futures::*; |
cad540e9 WB |
10 | use hyper::http::request::Parts; |
11 | use hyper::{header, Body, Response, StatusCode}; | |
15e9b4ed | 12 | use serde_json::{json, Value}; |
7c667013 | 13 | use tokio_stream::wrappers::ReceiverStream; |
15e9b4ed | 14 | |
6ef1b649 | 15 | use proxmox::{identity, sortable}; |
d6688884 SR |
16 | use proxmox::tools::fs::{ |
17 | file_read_firstline, file_read_optional_string, replace_file, CreateOptions, | |
18 | }; | |
6ef1b649 WB |
19 | use proxmox_router::{ |
20 | list_subdirs_api_method, http_err, ApiResponseFuture, ApiHandler, ApiMethod, Router, | |
21 | RpcEnvironment, RpcEnvironmentType, SubdirMap, Permission, | |
22 | }; | |
23 | use proxmox_schema::*; | |
e18a6c9e | 24 | |
2e219481 | 25 | use pxar::accessor::aio::Accessor; |
d33d8f4e DC |
26 | use pxar::EntryKind; |
27 | ||
89725197 DM |
28 | use pbs_api_types::{ Authid, BackupContent, Counts, CryptMode, |
29 | DataStoreListItem, GarbageCollectionStatus, GroupListItem, | |
30 | SnapshotListItem, SnapshotVerifyState, PruneOptions, | |
c68fa58a | 31 | DataStoreStatus, RRDMode, RRDTimeFrame, |
89725197 DM |
32 | BACKUP_ARCHIVE_NAME_SCHEMA, BACKUP_ID_SCHEMA, BACKUP_TIME_SCHEMA, |
33 | BACKUP_TYPE_SCHEMA, DATASTORE_SCHEMA, | |
34 | IGNORE_VERIFIED_BACKUPS_SCHEMA, UPID_SCHEMA, | |
35 | VERIFICATION_OUTDATED_AFTER_SCHEMA, PRIV_DATASTORE_AUDIT, | |
36 | PRIV_DATASTORE_MODIFY, PRIV_DATASTORE_READ, PRIV_DATASTORE_PRUNE, | |
8cc3760e DM |
37 | PRIV_DATASTORE_BACKUP, PRIV_DATASTORE_VERIFY, |
38 | ||
b2065dc7 | 39 | }; |
2b7f8dd5 | 40 | use pbs_client::pxar::create_zip; |
8a23ea46 DM |
41 | use pbs_datastore::{ |
42 | check_backup_owner, DataStore, BackupDir, BackupGroup, StoreProgress, LocalChunkReader, | |
43 | CATALOG_NAME, | |
44 | }; | |
b2065dc7 WB |
45 | use pbs_datastore::backup_info::BackupInfo; |
46 | use pbs_datastore::cached_chunk_reader::CachedChunkReader; | |
013b1e8b | 47 | use pbs_datastore::catalog::{ArchiveEntry, CatalogReader}; |
b2065dc7 WB |
48 | use pbs_datastore::data_blob::DataBlob; |
49 | use pbs_datastore::data_blob_reader::DataBlobReader; | |
50 | use pbs_datastore::dynamic_index::{BufferedDynamicReader, DynamicIndexReader, LocalDynamicReadAt}; | |
51 | use pbs_datastore::fixed_index::{FixedIndexReader}; | |
52 | use pbs_datastore::index::IndexFile; | |
53 | use pbs_datastore::manifest::{BackupManifest, CLIENT_LOG_BLOB_NAME, MANIFEST_BLOB_NAME}; | |
89725197 | 54 | use pbs_datastore::prune::compute_prune_info; |
fc5870be WB |
55 | use pbs_tools::blocking::WrappedReaderStream; |
56 | use pbs_tools::stream::{AsyncReaderStream, AsyncChannelWriter}; | |
3c8c2827 | 57 | use pbs_tools::json::{required_integer_param, required_string_param}; |
1ec0d70d | 58 | use pbs_tools::{task_log, task_warn}; |
e7d4be9d | 59 | use pbs_config::CachedUserInfo; |
b9700a9f | 60 | use proxmox_rest_server::{WorkerTask, formatter}; |
2b7f8dd5 | 61 | |
431cc7b1 | 62 | use crate::api2::node::rrd::create_value_from_rrd; |
b2065dc7 | 63 | use crate::backup::{ |
6d5d305d | 64 | verify_all_backups, verify_backup_group, verify_backup_dir, verify_filter, |
b2065dc7 | 65 | }; |
54552dda | 66 | |
b9700a9f | 67 | use crate::server::jobstate::Job; |
804f6143 | 68 | |
1629d2ad | 69 | |
d6688884 SR |
70 | const GROUP_NOTES_FILE_NAME: &str = "notes"; |
71 | ||
72 | fn get_group_note_path(store: &DataStore, group: &BackupGroup) -> PathBuf { | |
73 | let mut note_path = store.base_path(); | |
74 | note_path.push(group.group_path()); | |
75 | note_path.push(GROUP_NOTES_FILE_NAME); | |
76 | note_path | |
77 | } | |
78 | ||
bff85572 | 79 | fn check_priv_or_backup_owner( |
e7cb4dc5 WB |
80 | store: &DataStore, |
81 | group: &BackupGroup, | |
e6dc35ac | 82 | auth_id: &Authid, |
bff85572 FG |
83 | required_privs: u64, |
84 | ) -> Result<(), Error> { | |
85 | let user_info = CachedUserInfo::new()?; | |
86 | let privs = user_info.lookup_privs(&auth_id, &["datastore", store.name()]); | |
87 | ||
88 | if privs & required_privs == 0 { | |
89 | let owner = store.get_owner(group)?; | |
90 | check_backup_owner(&owner, auth_id)?; | |
91 | } | |
92 | Ok(()) | |
93 | } | |
94 | ||
e7cb4dc5 WB |
95 | fn read_backup_index( |
96 | store: &DataStore, | |
97 | backup_dir: &BackupDir, | |
98 | ) -> Result<(BackupManifest, Vec<BackupContent>), Error> { | |
8c70e3eb | 99 | |
ff86ef00 | 100 | let (manifest, index_size) = store.load_manifest(backup_dir)?; |
8c70e3eb | 101 | |
09b1f7b2 DM |
102 | let mut result = Vec::new(); |
103 | for item in manifest.files() { | |
104 | result.push(BackupContent { | |
105 | filename: item.filename.clone(), | |
f28d9088 | 106 | crypt_mode: Some(item.crypt_mode), |
09b1f7b2 DM |
107 | size: Some(item.size), |
108 | }); | |
8c70e3eb DM |
109 | } |
110 | ||
09b1f7b2 | 111 | result.push(BackupContent { |
96d65fbc | 112 | filename: MANIFEST_BLOB_NAME.to_string(), |
882c0823 FG |
113 | crypt_mode: match manifest.signature { |
114 | Some(_) => Some(CryptMode::SignOnly), | |
115 | None => Some(CryptMode::None), | |
116 | }, | |
09b1f7b2 DM |
117 | size: Some(index_size), |
118 | }); | |
4f1e40a2 | 119 | |
70030b43 | 120 | Ok((manifest, result)) |
8c70e3eb DM |
121 | } |
122 | ||
1c090810 DC |
123 | fn get_all_snapshot_files( |
124 | store: &DataStore, | |
125 | info: &BackupInfo, | |
70030b43 DM |
126 | ) -> Result<(BackupManifest, Vec<BackupContent>), Error> { |
127 | ||
128 | let (manifest, mut files) = read_backup_index(&store, &info.backup_dir)?; | |
1c090810 DC |
129 | |
130 | let file_set = files.iter().fold(HashSet::new(), |mut acc, item| { | |
131 | acc.insert(item.filename.clone()); | |
132 | acc | |
133 | }); | |
134 | ||
135 | for file in &info.files { | |
136 | if file_set.contains(file) { continue; } | |
f28d9088 WB |
137 | files.push(BackupContent { |
138 | filename: file.to_string(), | |
139 | size: None, | |
140 | crypt_mode: None, | |
141 | }); | |
1c090810 DC |
142 | } |
143 | ||
70030b43 | 144 | Ok((manifest, files)) |
1c090810 DC |
145 | } |
146 | ||
b31c8019 DM |
147 | #[api( |
148 | input: { | |
149 | properties: { | |
150 | store: { | |
151 | schema: DATASTORE_SCHEMA, | |
152 | }, | |
153 | }, | |
154 | }, | |
7b570c17 | 155 | returns: pbs_api_types::ADMIN_DATASTORE_LIST_GROUPS_RETURN_TYPE, |
bb34b589 | 156 | access: { |
54552dda DM |
157 | permission: &Permission::Privilege( |
158 | &["datastore", "{store}"], | |
159 | PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP, | |
160 | true), | |
bb34b589 | 161 | }, |
b31c8019 DM |
162 | )] |
163 | /// List backup groups. | |
b2362a12 | 164 | pub fn list_groups( |
b31c8019 | 165 | store: String, |
54552dda | 166 | rpcenv: &mut dyn RpcEnvironment, |
b31c8019 | 167 | ) -> Result<Vec<GroupListItem>, Error> { |
812c6f87 | 168 | |
e6dc35ac | 169 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
54552dda | 170 | let user_info = CachedUserInfo::new()?; |
e6dc35ac | 171 | let user_privs = user_info.lookup_privs(&auth_id, &["datastore", &store]); |
54552dda | 172 | |
b31c8019 | 173 | let datastore = DataStore::lookup_datastore(&store)?; |
0d08fcee FG |
174 | let list_all = (user_privs & PRIV_DATASTORE_AUDIT) != 0; |
175 | ||
176 | let backup_groups = BackupInfo::list_backup_groups(&datastore.base_path())?; | |
177 | ||
178 | let group_info = backup_groups | |
179 | .into_iter() | |
180 | .fold(Vec::new(), |mut group_info, group| { | |
181 | let owner = match datastore.get_owner(&group) { | |
182 | Ok(auth_id) => auth_id, | |
183 | Err(err) => { | |
1ed02257 FG |
184 | eprintln!("Failed to get owner of group '{}/{}' - {}", |
185 | &store, | |
186 | group, | |
187 | err); | |
0d08fcee FG |
188 | return group_info; |
189 | }, | |
190 | }; | |
191 | if !list_all && check_backup_owner(&owner, &auth_id).is_err() { | |
192 | return group_info; | |
193 | } | |
194 | ||
195 | let snapshots = match group.list_backups(&datastore.base_path()) { | |
196 | Ok(snapshots) => snapshots, | |
197 | Err(_) => { | |
198 | return group_info; | |
199 | }, | |
200 | }; | |
201 | ||
202 | let backup_count: u64 = snapshots.len() as u64; | |
203 | if backup_count == 0 { | |
204 | return group_info; | |
205 | } | |
206 | ||
207 | let last_backup = snapshots | |
208 | .iter() | |
209 | .fold(&snapshots[0], |last, curr| { | |
210 | if curr.is_finished() | |
211 | && curr.backup_dir.backup_time() > last.backup_dir.backup_time() { | |
212 | curr | |
213 | } else { | |
214 | last | |
215 | } | |
216 | }) | |
217 | .to_owned(); | |
218 | ||
d6688884 SR |
219 | let note_path = get_group_note_path(&datastore, &group); |
220 | let comment = file_read_firstline(¬e_path).ok(); | |
221 | ||
0d08fcee FG |
222 | group_info.push(GroupListItem { |
223 | backup_type: group.backup_type().to_string(), | |
224 | backup_id: group.backup_id().to_string(), | |
225 | last_backup: last_backup.backup_dir.backup_time(), | |
226 | owner: Some(owner), | |
227 | backup_count, | |
228 | files: last_backup.files, | |
d6688884 | 229 | comment, |
0d08fcee FG |
230 | }); |
231 | ||
232 | group_info | |
233 | }); | |
812c6f87 | 234 | |
0d08fcee | 235 | Ok(group_info) |
812c6f87 | 236 | } |
8f579717 | 237 | |
f32791b4 DC |
238 | #[api( |
239 | input: { | |
240 | properties: { | |
241 | store: { | |
242 | schema: DATASTORE_SCHEMA, | |
243 | }, | |
244 | "backup-type": { | |
245 | schema: BACKUP_TYPE_SCHEMA, | |
246 | }, | |
247 | "backup-id": { | |
248 | schema: BACKUP_ID_SCHEMA, | |
249 | }, | |
250 | }, | |
251 | }, | |
252 | access: { | |
253 | permission: &Permission::Privilege( | |
254 | &["datastore", "{store}"], | |
255 | PRIV_DATASTORE_MODIFY| PRIV_DATASTORE_PRUNE, | |
256 | true), | |
257 | }, | |
258 | )] | |
259 | /// Delete backup group including all snapshots. | |
260 | pub fn delete_group( | |
261 | store: String, | |
262 | backup_type: String, | |
263 | backup_id: String, | |
264 | _info: &ApiMethod, | |
265 | rpcenv: &mut dyn RpcEnvironment, | |
266 | ) -> Result<Value, Error> { | |
267 | ||
268 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; | |
269 | ||
270 | let group = BackupGroup::new(backup_type, backup_id); | |
271 | let datastore = DataStore::lookup_datastore(&store)?; | |
272 | ||
273 | check_priv_or_backup_owner(&datastore, &group, &auth_id, PRIV_DATASTORE_MODIFY)?; | |
274 | ||
5cc7d891 DC |
275 | if !datastore.remove_backup_group(&group)? { |
276 | bail!("did not delete whole group because of protected snapthots"); | |
277 | } | |
f32791b4 DC |
278 | |
279 | Ok(Value::Null) | |
280 | } | |
281 | ||
09b1f7b2 DM |
282 | #[api( |
283 | input: { | |
284 | properties: { | |
285 | store: { | |
286 | schema: DATASTORE_SCHEMA, | |
287 | }, | |
288 | "backup-type": { | |
289 | schema: BACKUP_TYPE_SCHEMA, | |
290 | }, | |
291 | "backup-id": { | |
292 | schema: BACKUP_ID_SCHEMA, | |
293 | }, | |
294 | "backup-time": { | |
295 | schema: BACKUP_TIME_SCHEMA, | |
296 | }, | |
297 | }, | |
298 | }, | |
7b570c17 | 299 | returns: pbs_api_types::ADMIN_DATASTORE_LIST_SNAPSHOT_FILES_RETURN_TYPE, |
bb34b589 | 300 | access: { |
54552dda DM |
301 | permission: &Permission::Privilege( |
302 | &["datastore", "{store}"], | |
303 | PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP, | |
304 | true), | |
bb34b589 | 305 | }, |
09b1f7b2 DM |
306 | )] |
307 | /// List snapshot files. | |
ea5f547f | 308 | pub fn list_snapshot_files( |
09b1f7b2 DM |
309 | store: String, |
310 | backup_type: String, | |
311 | backup_id: String, | |
312 | backup_time: i64, | |
01a13423 | 313 | _info: &ApiMethod, |
54552dda | 314 | rpcenv: &mut dyn RpcEnvironment, |
09b1f7b2 | 315 | ) -> Result<Vec<BackupContent>, Error> { |
01a13423 | 316 | |
e6dc35ac | 317 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
09b1f7b2 | 318 | let datastore = DataStore::lookup_datastore(&store)?; |
54552dda | 319 | |
e0e5b442 | 320 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time)?; |
01a13423 | 321 | |
bff85572 | 322 | check_priv_or_backup_owner(&datastore, snapshot.group(), &auth_id, PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_READ)?; |
54552dda | 323 | |
d7c24397 | 324 | let info = BackupInfo::new(&datastore.base_path(), snapshot)?; |
01a13423 | 325 | |
70030b43 DM |
326 | let (_manifest, files) = get_all_snapshot_files(&datastore, &info)?; |
327 | ||
328 | Ok(files) | |
01a13423 DM |
329 | } |
330 | ||
68a6a0ee DM |
331 | #[api( |
332 | input: { | |
333 | properties: { | |
334 | store: { | |
335 | schema: DATASTORE_SCHEMA, | |
336 | }, | |
337 | "backup-type": { | |
338 | schema: BACKUP_TYPE_SCHEMA, | |
339 | }, | |
340 | "backup-id": { | |
341 | schema: BACKUP_ID_SCHEMA, | |
342 | }, | |
343 | "backup-time": { | |
344 | schema: BACKUP_TIME_SCHEMA, | |
345 | }, | |
346 | }, | |
347 | }, | |
bb34b589 | 348 | access: { |
54552dda DM |
349 | permission: &Permission::Privilege( |
350 | &["datastore", "{store}"], | |
351 | PRIV_DATASTORE_MODIFY| PRIV_DATASTORE_PRUNE, | |
352 | true), | |
bb34b589 | 353 | }, |
68a6a0ee DM |
354 | )] |
355 | /// Delete backup snapshot. | |
bf78f708 | 356 | pub fn delete_snapshot( |
68a6a0ee DM |
357 | store: String, |
358 | backup_type: String, | |
359 | backup_id: String, | |
360 | backup_time: i64, | |
6f62c924 | 361 | _info: &ApiMethod, |
54552dda | 362 | rpcenv: &mut dyn RpcEnvironment, |
6f62c924 DM |
363 | ) -> Result<Value, Error> { |
364 | ||
e6dc35ac | 365 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
54552dda | 366 | |
e0e5b442 | 367 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time)?; |
68a6a0ee | 368 | let datastore = DataStore::lookup_datastore(&store)?; |
6f62c924 | 369 | |
bff85572 | 370 | check_priv_or_backup_owner(&datastore, snapshot.group(), &auth_id, PRIV_DATASTORE_MODIFY)?; |
54552dda | 371 | |
c9756b40 | 372 | datastore.remove_backup_dir(&snapshot, false)?; |
6f62c924 DM |
373 | |
374 | Ok(Value::Null) | |
375 | } | |
376 | ||
fc189b19 DM |
377 | #[api( |
378 | input: { | |
379 | properties: { | |
380 | store: { | |
381 | schema: DATASTORE_SCHEMA, | |
382 | }, | |
383 | "backup-type": { | |
384 | optional: true, | |
385 | schema: BACKUP_TYPE_SCHEMA, | |
386 | }, | |
387 | "backup-id": { | |
388 | optional: true, | |
389 | schema: BACKUP_ID_SCHEMA, | |
390 | }, | |
391 | }, | |
392 | }, | |
7b570c17 | 393 | returns: pbs_api_types::ADMIN_DATASTORE_LIST_SNAPSHOTS_RETURN_TYPE, |
bb34b589 | 394 | access: { |
54552dda DM |
395 | permission: &Permission::Privilege( |
396 | &["datastore", "{store}"], | |
397 | PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP, | |
398 | true), | |
bb34b589 | 399 | }, |
fc189b19 DM |
400 | )] |
401 | /// List backup snapshots. | |
f24fc116 | 402 | pub fn list_snapshots ( |
54552dda DM |
403 | store: String, |
404 | backup_type: Option<String>, | |
405 | backup_id: Option<String>, | |
406 | _param: Value, | |
184f17af | 407 | _info: &ApiMethod, |
54552dda | 408 | rpcenv: &mut dyn RpcEnvironment, |
fc189b19 | 409 | ) -> Result<Vec<SnapshotListItem>, Error> { |
184f17af | 410 | |
e6dc35ac | 411 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
54552dda | 412 | let user_info = CachedUserInfo::new()?; |
e6dc35ac | 413 | let user_privs = user_info.lookup_privs(&auth_id, &["datastore", &store]); |
184f17af | 414 | |
0d08fcee FG |
415 | let list_all = (user_privs & PRIV_DATASTORE_AUDIT) != 0; |
416 | ||
54552dda | 417 | let datastore = DataStore::lookup_datastore(&store)?; |
184f17af | 418 | |
c0977501 | 419 | let base_path = datastore.base_path(); |
184f17af | 420 | |
0d08fcee FG |
421 | let groups = match (backup_type, backup_id) { |
422 | (Some(backup_type), Some(backup_id)) => { | |
423 | let mut groups = Vec::with_capacity(1); | |
424 | groups.push(BackupGroup::new(backup_type, backup_id)); | |
425 | groups | |
426 | }, | |
427 | (Some(backup_type), None) => { | |
428 | BackupInfo::list_backup_groups(&base_path)? | |
429 | .into_iter() | |
430 | .filter(|group| group.backup_type() == backup_type) | |
431 | .collect() | |
432 | }, | |
433 | (None, Some(backup_id)) => { | |
434 | BackupInfo::list_backup_groups(&base_path)? | |
435 | .into_iter() | |
436 | .filter(|group| group.backup_id() == backup_id) | |
437 | .collect() | |
438 | }, | |
439 | _ => BackupInfo::list_backup_groups(&base_path)?, | |
440 | }; | |
54552dda | 441 | |
0d08fcee | 442 | let info_to_snapshot_list_item = |group: &BackupGroup, owner, info: BackupInfo| { |
79c53595 FG |
443 | let backup_type = group.backup_type().to_string(); |
444 | let backup_id = group.backup_id().to_string(); | |
0d08fcee | 445 | let backup_time = info.backup_dir.backup_time(); |
02db7267 | 446 | let protected = info.backup_dir.is_protected(base_path.clone()); |
1c090810 | 447 | |
79c53595 | 448 | match get_all_snapshot_files(&datastore, &info) { |
70030b43 | 449 | Ok((manifest, files)) => { |
70030b43 DM |
450 | // extract the first line from notes |
451 | let comment: Option<String> = manifest.unprotected["notes"] | |
452 | .as_str() | |
453 | .and_then(|notes| notes.lines().next()) | |
454 | .map(String::from); | |
455 | ||
035c40e6 FG |
456 | let fingerprint = match manifest.fingerprint() { |
457 | Ok(fp) => fp, | |
458 | Err(err) => { | |
459 | eprintln!("error parsing fingerprint: '{}'", err); | |
460 | None | |
461 | }, | |
462 | }; | |
463 | ||
79c53595 FG |
464 | let verification = manifest.unprotected["verify_state"].clone(); |
465 | let verification: Option<SnapshotVerifyState> = match serde_json::from_value(verification) { | |
3b2046d2 TL |
466 | Ok(verify) => verify, |
467 | Err(err) => { | |
468 | eprintln!("error parsing verification state : '{}'", err); | |
469 | None | |
470 | } | |
471 | }; | |
472 | ||
0d08fcee FG |
473 | let size = Some(files.iter().map(|x| x.size.unwrap_or(0)).sum()); |
474 | ||
79c53595 FG |
475 | SnapshotListItem { |
476 | backup_type, | |
477 | backup_id, | |
478 | backup_time, | |
479 | comment, | |
480 | verification, | |
035c40e6 | 481 | fingerprint, |
79c53595 FG |
482 | files, |
483 | size, | |
484 | owner, | |
02db7267 | 485 | protected, |
79c53595 | 486 | } |
1c090810 DC |
487 | }, |
488 | Err(err) => { | |
489 | eprintln!("error during snapshot file listing: '{}'", err); | |
79c53595 | 490 | let files = info |
70030b43 | 491 | .files |
0d08fcee | 492 | .into_iter() |
44288184 FG |
493 | .map(|filename| BackupContent { |
494 | filename, | |
70030b43 DM |
495 | size: None, |
496 | crypt_mode: None, | |
497 | }) | |
79c53595 FG |
498 | .collect(); |
499 | ||
500 | SnapshotListItem { | |
501 | backup_type, | |
502 | backup_id, | |
503 | backup_time, | |
504 | comment: None, | |
505 | verification: None, | |
035c40e6 | 506 | fingerprint: None, |
79c53595 FG |
507 | files, |
508 | size: None, | |
509 | owner, | |
02db7267 | 510 | protected, |
79c53595 | 511 | } |
1c090810 | 512 | }, |
0d08fcee FG |
513 | } |
514 | }; | |
184f17af | 515 | |
0d08fcee FG |
516 | groups |
517 | .iter() | |
518 | .try_fold(Vec::new(), |mut snapshots, group| { | |
519 | let owner = match datastore.get_owner(group) { | |
520 | Ok(auth_id) => auth_id, | |
521 | Err(err) => { | |
522 | eprintln!("Failed to get owner of group '{}/{}' - {}", | |
523 | &store, | |
524 | group, | |
525 | err); | |
526 | return Ok(snapshots); | |
527 | }, | |
528 | }; | |
529 | ||
530 | if !list_all && check_backup_owner(&owner, &auth_id).is_err() { | |
531 | return Ok(snapshots); | |
532 | } | |
533 | ||
534 | let group_backups = group.list_backups(&datastore.base_path())?; | |
535 | ||
536 | snapshots.extend( | |
537 | group_backups | |
538 | .into_iter() | |
539 | .map(|info| info_to_snapshot_list_item(&group, Some(owner.clone()), info)) | |
540 | ); | |
541 | ||
542 | Ok(snapshots) | |
543 | }) | |
184f17af DM |
544 | } |
545 | ||
fdfcb74d | 546 | fn get_snapshots_count(store: &DataStore, filter_owner: Option<&Authid>) -> Result<Counts, Error> { |
16f9f244 | 547 | let base_path = store.base_path(); |
fdfcb74d | 548 | let groups = BackupInfo::list_backup_groups(&base_path)?; |
16f9f244 | 549 | |
fdfcb74d FG |
550 | groups.iter() |
551 | .filter(|group| { | |
552 | let owner = match store.get_owner(&group) { | |
553 | Ok(owner) => owner, | |
554 | Err(err) => { | |
1ed02257 FG |
555 | eprintln!("Failed to get owner of group '{}/{}' - {}", |
556 | store.name(), | |
557 | group, | |
558 | err); | |
fdfcb74d FG |
559 | return false; |
560 | }, | |
561 | }; | |
14e08625 | 562 | |
fdfcb74d FG |
563 | match filter_owner { |
564 | Some(filter) => check_backup_owner(&owner, filter).is_ok(), | |
565 | None => true, | |
566 | } | |
567 | }) | |
568 | .try_fold(Counts::default(), |mut counts, group| { | |
569 | let snapshot_count = group.list_backups(&base_path)?.len() as u64; | |
570 | ||
571 | let type_count = match group.backup_type() { | |
572 | "ct" => counts.ct.get_or_insert(Default::default()), | |
573 | "vm" => counts.vm.get_or_insert(Default::default()), | |
574 | "host" => counts.host.get_or_insert(Default::default()), | |
575 | _ => counts.other.get_or_insert(Default::default()), | |
576 | }; | |
14e08625 | 577 | |
fdfcb74d FG |
578 | type_count.groups += 1; |
579 | type_count.snapshots += snapshot_count; | |
16f9f244 | 580 | |
fdfcb74d FG |
581 | Ok(counts) |
582 | }) | |
16f9f244 DC |
583 | } |
584 | ||
1dc117bb DM |
585 | #[api( |
586 | input: { | |
587 | properties: { | |
588 | store: { | |
589 | schema: DATASTORE_SCHEMA, | |
590 | }, | |
98afc7b1 FG |
591 | verbose: { |
592 | type: bool, | |
593 | default: false, | |
594 | optional: true, | |
595 | description: "Include additional information like snapshot counts and GC status.", | |
596 | }, | |
1dc117bb | 597 | }, |
98afc7b1 | 598 | |
1dc117bb DM |
599 | }, |
600 | returns: { | |
14e08625 | 601 | type: DataStoreStatus, |
1dc117bb | 602 | }, |
bb34b589 | 603 | access: { |
54552dda | 604 | permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP, true), |
bb34b589 | 605 | }, |
1dc117bb DM |
606 | )] |
607 | /// Get datastore status. | |
ea5f547f | 608 | pub fn status( |
1dc117bb | 609 | store: String, |
98afc7b1 | 610 | verbose: bool, |
0eecf38f | 611 | _info: &ApiMethod, |
fdfcb74d | 612 | rpcenv: &mut dyn RpcEnvironment, |
14e08625 | 613 | ) -> Result<DataStoreStatus, Error> { |
1dc117bb | 614 | let datastore = DataStore::lookup_datastore(&store)?; |
14e08625 | 615 | let storage = crate::tools::disks::disk_usage(&datastore.base_path())?; |
fdfcb74d FG |
616 | let (counts, gc_status) = if verbose { |
617 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; | |
618 | let user_info = CachedUserInfo::new()?; | |
619 | ||
620 | let store_privs = user_info.lookup_privs(&auth_id, &["datastore", &store]); | |
621 | let filter_owner = if store_privs & PRIV_DATASTORE_AUDIT != 0 { | |
622 | None | |
623 | } else { | |
624 | Some(&auth_id) | |
625 | }; | |
626 | ||
627 | let counts = Some(get_snapshots_count(&datastore, filter_owner)?); | |
628 | let gc_status = Some(datastore.last_gc_status()); | |
629 | ||
630 | (counts, gc_status) | |
631 | } else { | |
632 | (None, None) | |
98afc7b1 | 633 | }; |
16f9f244 | 634 | |
14e08625 DC |
635 | Ok(DataStoreStatus { |
636 | total: storage.total, | |
637 | used: storage.used, | |
638 | avail: storage.avail, | |
639 | gc_status, | |
640 | counts, | |
641 | }) | |
0eecf38f DM |
642 | } |
643 | ||
c2009e53 DM |
644 | #[api( |
645 | input: { | |
646 | properties: { | |
647 | store: { | |
648 | schema: DATASTORE_SCHEMA, | |
649 | }, | |
650 | "backup-type": { | |
651 | schema: BACKUP_TYPE_SCHEMA, | |
652 | optional: true, | |
653 | }, | |
654 | "backup-id": { | |
655 | schema: BACKUP_ID_SCHEMA, | |
656 | optional: true, | |
657 | }, | |
dcbf29e7 HL |
658 | "ignore-verified": { |
659 | schema: IGNORE_VERIFIED_BACKUPS_SCHEMA, | |
660 | optional: true, | |
661 | }, | |
662 | "outdated-after": { | |
663 | schema: VERIFICATION_OUTDATED_AFTER_SCHEMA, | |
664 | optional: true, | |
665 | }, | |
c2009e53 DM |
666 | "backup-time": { |
667 | schema: BACKUP_TIME_SCHEMA, | |
668 | optional: true, | |
669 | }, | |
670 | }, | |
671 | }, | |
672 | returns: { | |
673 | schema: UPID_SCHEMA, | |
674 | }, | |
675 | access: { | |
09f6a240 | 676 | permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_VERIFY | PRIV_DATASTORE_BACKUP, true), |
c2009e53 DM |
677 | }, |
678 | )] | |
679 | /// Verify backups. | |
680 | /// | |
681 | /// This function can verify a single backup snapshot, all backup from a backup group, | |
682 | /// or all backups in the datastore. | |
683 | pub fn verify( | |
684 | store: String, | |
685 | backup_type: Option<String>, | |
686 | backup_id: Option<String>, | |
687 | backup_time: Option<i64>, | |
dcbf29e7 HL |
688 | ignore_verified: Option<bool>, |
689 | outdated_after: Option<i64>, | |
c2009e53 DM |
690 | rpcenv: &mut dyn RpcEnvironment, |
691 | ) -> Result<Value, Error> { | |
692 | let datastore = DataStore::lookup_datastore(&store)?; | |
dcbf29e7 | 693 | let ignore_verified = ignore_verified.unwrap_or(true); |
c2009e53 | 694 | |
09f6a240 | 695 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
8ea00f6e | 696 | let worker_id; |
c2009e53 DM |
697 | |
698 | let mut backup_dir = None; | |
699 | let mut backup_group = None; | |
133042b5 | 700 | let mut worker_type = "verify"; |
c2009e53 DM |
701 | |
702 | match (backup_type, backup_id, backup_time) { | |
703 | (Some(backup_type), Some(backup_id), Some(backup_time)) => { | |
4ebda996 | 704 | worker_id = format!("{}:{}/{}/{:08X}", store, backup_type, backup_id, backup_time); |
e0e5b442 | 705 | let dir = BackupDir::new(backup_type, backup_id, backup_time)?; |
09f6a240 FG |
706 | |
707 | check_priv_or_backup_owner(&datastore, dir.group(), &auth_id, PRIV_DATASTORE_VERIFY)?; | |
708 | ||
c2009e53 | 709 | backup_dir = Some(dir); |
133042b5 | 710 | worker_type = "verify_snapshot"; |
c2009e53 DM |
711 | } |
712 | (Some(backup_type), Some(backup_id), None) => { | |
4ebda996 | 713 | worker_id = format!("{}:{}/{}", store, backup_type, backup_id); |
c2009e53 | 714 | let group = BackupGroup::new(backup_type, backup_id); |
09f6a240 FG |
715 | |
716 | check_priv_or_backup_owner(&datastore, &group, &auth_id, PRIV_DATASTORE_VERIFY)?; | |
717 | ||
c2009e53 | 718 | backup_group = Some(group); |
133042b5 | 719 | worker_type = "verify_group"; |
c2009e53 DM |
720 | } |
721 | (None, None, None) => { | |
8ea00f6e | 722 | worker_id = store.clone(); |
c2009e53 | 723 | } |
5a718dce | 724 | _ => bail!("parameters do not specify a backup group or snapshot"), |
c2009e53 DM |
725 | } |
726 | ||
39735609 | 727 | let to_stdout = rpcenv.env_type() == RpcEnvironmentType::CLI; |
c2009e53 DM |
728 | |
729 | let upid_str = WorkerTask::new_thread( | |
133042b5 | 730 | worker_type, |
44288184 | 731 | Some(worker_id), |
049a22a3 | 732 | auth_id.to_string(), |
e7cb4dc5 WB |
733 | to_stdout, |
734 | move |worker| { | |
9c26a3d6 | 735 | let verify_worker = crate::backup::VerifyWorker::new(worker.clone(), datastore); |
adfdc369 | 736 | let failed_dirs = if let Some(backup_dir) = backup_dir { |
adfdc369 | 737 | let mut res = Vec::new(); |
f6b1d1cc | 738 | if !verify_backup_dir( |
9c26a3d6 | 739 | &verify_worker, |
f6b1d1cc | 740 | &backup_dir, |
f6b1d1cc | 741 | worker.upid().clone(), |
dcbf29e7 HL |
742 | Some(&move |manifest| { |
743 | verify_filter(ignore_verified, outdated_after, manifest) | |
744 | }), | |
f6b1d1cc | 745 | )? { |
adfdc369 DC |
746 | res.push(backup_dir.to_string()); |
747 | } | |
748 | res | |
c2009e53 | 749 | } else if let Some(backup_group) = backup_group { |
7e25b9aa | 750 | let failed_dirs = verify_backup_group( |
9c26a3d6 | 751 | &verify_worker, |
63d9aca9 | 752 | &backup_group, |
7e25b9aa | 753 | &mut StoreProgress::new(1), |
f6b1d1cc | 754 | worker.upid(), |
dcbf29e7 HL |
755 | Some(&move |manifest| { |
756 | verify_filter(ignore_verified, outdated_after, manifest) | |
757 | }), | |
63d9aca9 DM |
758 | )?; |
759 | failed_dirs | |
c2009e53 | 760 | } else { |
09f6a240 FG |
761 | let privs = CachedUserInfo::new()? |
762 | .lookup_privs(&auth_id, &["datastore", &store]); | |
763 | ||
764 | let owner = if privs & PRIV_DATASTORE_VERIFY == 0 { | |
765 | Some(auth_id) | |
766 | } else { | |
767 | None | |
768 | }; | |
769 | ||
dcbf29e7 HL |
770 | verify_all_backups( |
771 | &verify_worker, | |
772 | worker.upid(), | |
773 | owner, | |
774 | Some(&move |manifest| { | |
775 | verify_filter(ignore_verified, outdated_after, manifest) | |
776 | }), | |
777 | )? | |
c2009e53 | 778 | }; |
3984a5fd | 779 | if !failed_dirs.is_empty() { |
1ec0d70d | 780 | task_log!(worker, "Failed to verify the following snapshots/groups:"); |
adfdc369 | 781 | for dir in failed_dirs { |
1ec0d70d | 782 | task_log!(worker, "\t{}", dir); |
adfdc369 | 783 | } |
1ffe0301 | 784 | bail!("verification failed - please check the log for details"); |
c2009e53 DM |
785 | } |
786 | Ok(()) | |
e7cb4dc5 WB |
787 | }, |
788 | )?; | |
c2009e53 DM |
789 | |
790 | Ok(json!(upid_str)) | |
791 | } | |
792 | ||
0a240aaa DC |
793 | #[api( |
794 | input: { | |
795 | properties: { | |
796 | "backup-id": { | |
797 | schema: BACKUP_ID_SCHEMA, | |
798 | }, | |
799 | "backup-type": { | |
800 | schema: BACKUP_TYPE_SCHEMA, | |
801 | }, | |
802 | "dry-run": { | |
803 | optional: true, | |
804 | type: bool, | |
805 | default: false, | |
806 | description: "Just show what prune would do, but do not delete anything.", | |
807 | }, | |
808 | "prune-options": { | |
809 | type: PruneOptions, | |
810 | flatten: true, | |
811 | }, | |
812 | store: { | |
813 | schema: DATASTORE_SCHEMA, | |
814 | }, | |
815 | }, | |
816 | }, | |
7b570c17 | 817 | returns: pbs_api_types::ADMIN_DATASTORE_PRUNE_RETURN_TYPE, |
0a240aaa DC |
818 | access: { |
819 | permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_MODIFY | PRIV_DATASTORE_PRUNE, true), | |
820 | }, | |
821 | )] | |
9805207a | 822 | /// Prune a group on the datastore |
bf78f708 | 823 | pub fn prune( |
0a240aaa DC |
824 | backup_id: String, |
825 | backup_type: String, | |
826 | dry_run: bool, | |
827 | prune_options: PruneOptions, | |
828 | store: String, | |
829 | _param: Value, | |
54552dda | 830 | rpcenv: &mut dyn RpcEnvironment, |
83b7db02 DM |
831 | ) -> Result<Value, Error> { |
832 | ||
e6dc35ac | 833 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
54552dda | 834 | |
0a240aaa | 835 | let group = BackupGroup::new(&backup_type, &backup_id); |
9fdc3ef4 | 836 | |
54552dda DM |
837 | let datastore = DataStore::lookup_datastore(&store)?; |
838 | ||
bff85572 | 839 | check_priv_or_backup_owner(&datastore, &group, &auth_id, PRIV_DATASTORE_MODIFY)?; |
83b7db02 | 840 | |
0a240aaa | 841 | let worker_id = format!("{}:{}/{}", store, &backup_type, &backup_id); |
503995c7 | 842 | |
dda70154 DM |
843 | let mut prune_result = Vec::new(); |
844 | ||
845 | let list = group.list_backups(&datastore.base_path())?; | |
846 | ||
847 | let mut prune_info = compute_prune_info(list, &prune_options)?; | |
848 | ||
849 | prune_info.reverse(); // delete older snapshots first | |
850 | ||
89725197 | 851 | let keep_all = !pbs_datastore::prune::keeps_something(&prune_options); |
dda70154 DM |
852 | |
853 | if dry_run { | |
02db7267 DC |
854 | for (info, mark) in prune_info { |
855 | let keep = keep_all || mark.keep(); | |
dda70154 DM |
856 | |
857 | let backup_time = info.backup_dir.backup_time(); | |
858 | let group = info.backup_dir.group(); | |
859 | ||
860 | prune_result.push(json!({ | |
861 | "backup-type": group.backup_type(), | |
862 | "backup-id": group.backup_id(), | |
6a7be83e | 863 | "backup-time": backup_time, |
dda70154 | 864 | "keep": keep, |
02db7267 | 865 | "protected": mark.protected(), |
dda70154 DM |
866 | })); |
867 | } | |
868 | return Ok(json!(prune_result)); | |
869 | } | |
870 | ||
871 | ||
163e9bbe | 872 | // We use a WorkerTask just to have a task log, but run synchrounously |
049a22a3 | 873 | let worker = WorkerTask::new("prune", Some(worker_id), auth_id.to_string(), true)?; |
dda70154 | 874 | |
f1539300 | 875 | if keep_all { |
1ec0d70d | 876 | task_log!(worker, "No prune selection - keeping all files."); |
f1539300 | 877 | } else { |
1ec0d70d DM |
878 | task_log!(worker, "retention options: {}", pbs_datastore::prune::cli_options_string(&prune_options)); |
879 | task_log!(worker, "Starting prune on store \"{}\" group \"{}/{}\"", | |
880 | store, backup_type, backup_id); | |
f1539300 | 881 | } |
3b03abfe | 882 | |
02db7267 DC |
883 | for (info, mark) in prune_info { |
884 | let keep = keep_all || mark.keep(); | |
dda70154 | 885 | |
f1539300 SR |
886 | let backup_time = info.backup_dir.backup_time(); |
887 | let timestamp = info.backup_dir.backup_time_string(); | |
888 | let group = info.backup_dir.group(); | |
3b03abfe | 889 | |
3b03abfe | 890 | |
f1539300 SR |
891 | let msg = format!( |
892 | "{}/{}/{} {}", | |
893 | group.backup_type(), | |
894 | group.backup_id(), | |
895 | timestamp, | |
02db7267 | 896 | mark, |
f1539300 SR |
897 | ); |
898 | ||
1ec0d70d | 899 | task_log!(worker, "{}", msg); |
f1539300 SR |
900 | |
901 | prune_result.push(json!({ | |
902 | "backup-type": group.backup_type(), | |
903 | "backup-id": group.backup_id(), | |
904 | "backup-time": backup_time, | |
905 | "keep": keep, | |
02db7267 | 906 | "protected": mark.protected(), |
f1539300 SR |
907 | })); |
908 | ||
909 | if !(dry_run || keep) { | |
910 | if let Err(err) = datastore.remove_backup_dir(&info.backup_dir, false) { | |
1ec0d70d DM |
911 | task_warn!( |
912 | worker, | |
913 | "failed to remove dir {:?}: {}", | |
914 | info.backup_dir.relative_path(), | |
915 | err, | |
f1539300 | 916 | ); |
8f0b4c1f | 917 | } |
8f579717 | 918 | } |
f1539300 | 919 | } |
dd8e744f | 920 | |
f1539300 | 921 | worker.log_result(&Ok(())); |
83b7db02 | 922 | |
dda70154 | 923 | Ok(json!(prune_result)) |
83b7db02 DM |
924 | } |
925 | ||
9805207a DC |
926 | #[api( |
927 | input: { | |
928 | properties: { | |
929 | "dry-run": { | |
930 | optional: true, | |
931 | type: bool, | |
932 | default: false, | |
933 | description: "Just show what prune would do, but do not delete anything.", | |
934 | }, | |
935 | "prune-options": { | |
936 | type: PruneOptions, | |
937 | flatten: true, | |
938 | }, | |
939 | store: { | |
940 | schema: DATASTORE_SCHEMA, | |
941 | }, | |
942 | }, | |
943 | }, | |
944 | returns: { | |
945 | schema: UPID_SCHEMA, | |
946 | }, | |
947 | access: { | |
948 | permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_MODIFY | PRIV_DATASTORE_PRUNE, true), | |
949 | }, | |
950 | )] | |
951 | /// Prune the datastore | |
952 | pub fn prune_datastore( | |
953 | dry_run: bool, | |
954 | prune_options: PruneOptions, | |
955 | store: String, | |
956 | _param: Value, | |
957 | rpcenv: &mut dyn RpcEnvironment, | |
958 | ) -> Result<String, Error> { | |
959 | ||
960 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; | |
961 | ||
962 | let datastore = DataStore::lookup_datastore(&store)?; | |
963 | ||
bfa942c0 DC |
964 | let to_stdout = rpcenv.env_type() == RpcEnvironmentType::CLI; |
965 | ||
9805207a DC |
966 | let upid_str = WorkerTask::new_thread( |
967 | "prune", | |
968 | Some(store.clone()), | |
049a22a3 | 969 | auth_id.to_string(), |
bfa942c0 | 970 | to_stdout, |
9805207a DC |
971 | move |worker| crate::server::prune_datastore( |
972 | worker.clone(), | |
973 | auth_id, | |
974 | prune_options, | |
975 | &store, | |
976 | datastore, | |
977 | dry_run | |
978 | ), | |
979 | )?; | |
980 | ||
981 | Ok(upid_str) | |
982 | } | |
983 | ||
dfc58d47 DM |
984 | #[api( |
985 | input: { | |
986 | properties: { | |
987 | store: { | |
988 | schema: DATASTORE_SCHEMA, | |
989 | }, | |
990 | }, | |
991 | }, | |
992 | returns: { | |
993 | schema: UPID_SCHEMA, | |
994 | }, | |
bb34b589 | 995 | access: { |
54552dda | 996 | permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_MODIFY, false), |
bb34b589 | 997 | }, |
dfc58d47 DM |
998 | )] |
999 | /// Start garbage collection. | |
bf78f708 | 1000 | pub fn start_garbage_collection( |
dfc58d47 | 1001 | store: String, |
6049b71f | 1002 | _info: &ApiMethod, |
dd5495d6 | 1003 | rpcenv: &mut dyn RpcEnvironment, |
6049b71f | 1004 | ) -> Result<Value, Error> { |
15e9b4ed | 1005 | |
3e6a7dee | 1006 | let datastore = DataStore::lookup_datastore(&store)?; |
e6dc35ac | 1007 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
15e9b4ed | 1008 | |
4fdf5ddf DC |
1009 | let job = Job::new("garbage_collection", &store) |
1010 | .map_err(|_| format_err!("garbage collection already running"))?; | |
15e9b4ed | 1011 | |
39735609 | 1012 | let to_stdout = rpcenv.env_type() == RpcEnvironmentType::CLI; |
15e9b4ed | 1013 | |
4fdf5ddf DC |
1014 | let upid_str = crate::server::do_garbage_collection_job(job, datastore, &auth_id, None, to_stdout) |
1015 | .map_err(|err| format_err!("unable to start garbage collection job on datastore {} - {}", store, err))?; | |
0f778e06 DM |
1016 | |
1017 | Ok(json!(upid_str)) | |
15e9b4ed DM |
1018 | } |
1019 | ||
a92830dc DM |
1020 | #[api( |
1021 | input: { | |
1022 | properties: { | |
1023 | store: { | |
1024 | schema: DATASTORE_SCHEMA, | |
1025 | }, | |
1026 | }, | |
1027 | }, | |
1028 | returns: { | |
1029 | type: GarbageCollectionStatus, | |
bb34b589 DM |
1030 | }, |
1031 | access: { | |
1032 | permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_AUDIT, false), | |
1033 | }, | |
a92830dc DM |
1034 | )] |
1035 | /// Garbage collection status. | |
5eeea607 | 1036 | pub fn garbage_collection_status( |
a92830dc | 1037 | store: String, |
6049b71f | 1038 | _info: &ApiMethod, |
dd5495d6 | 1039 | _rpcenv: &mut dyn RpcEnvironment, |
a92830dc | 1040 | ) -> Result<GarbageCollectionStatus, Error> { |
691c89a0 | 1041 | |
f2b99c34 DM |
1042 | let datastore = DataStore::lookup_datastore(&store)?; |
1043 | ||
f2b99c34 | 1044 | let status = datastore.last_gc_status(); |
691c89a0 | 1045 | |
a92830dc | 1046 | Ok(status) |
691c89a0 DM |
1047 | } |
1048 | ||
bb34b589 | 1049 | #[api( |
30fb6025 DM |
1050 | returns: { |
1051 | description: "List the accessible datastores.", | |
1052 | type: Array, | |
9b93c620 | 1053 | items: { type: DataStoreListItem }, |
30fb6025 | 1054 | }, |
bb34b589 | 1055 | access: { |
54552dda | 1056 | permission: &Permission::Anybody, |
bb34b589 DM |
1057 | }, |
1058 | )] | |
1059 | /// Datastore list | |
bf78f708 | 1060 | pub fn get_datastore_list( |
6049b71f DM |
1061 | _param: Value, |
1062 | _info: &ApiMethod, | |
54552dda | 1063 | rpcenv: &mut dyn RpcEnvironment, |
455e5f71 | 1064 | ) -> Result<Vec<DataStoreListItem>, Error> { |
15e9b4ed | 1065 | |
e7d4be9d | 1066 | let (config, _digest) = pbs_config::datastore::config()?; |
15e9b4ed | 1067 | |
e6dc35ac | 1068 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
54552dda DM |
1069 | let user_info = CachedUserInfo::new()?; |
1070 | ||
30fb6025 | 1071 | let mut list = Vec::new(); |
54552dda | 1072 | |
30fb6025 | 1073 | for (store, (_, data)) in &config.sections { |
e6dc35ac | 1074 | let user_privs = user_info.lookup_privs(&auth_id, &["datastore", &store]); |
54552dda | 1075 | let allowed = (user_privs & (PRIV_DATASTORE_AUDIT| PRIV_DATASTORE_BACKUP)) != 0; |
30fb6025 | 1076 | if allowed { |
455e5f71 FG |
1077 | list.push( |
1078 | DataStoreListItem { | |
1079 | store: store.clone(), | |
1080 | comment: data["comment"].as_str().map(String::from), | |
1081 | } | |
1082 | ); | |
30fb6025 | 1083 | } |
54552dda DM |
1084 | } |
1085 | ||
44288184 | 1086 | Ok(list) |
15e9b4ed DM |
1087 | } |
1088 | ||
0ab08ac9 DM |
1089 | #[sortable] |
1090 | pub const API_METHOD_DOWNLOAD_FILE: ApiMethod = ApiMethod::new( | |
1091 | &ApiHandler::AsyncHttp(&download_file), | |
1092 | &ObjectSchema::new( | |
1093 | "Download single raw file from backup snapshot.", | |
1094 | &sorted!([ | |
66c49c21 | 1095 | ("store", false, &DATASTORE_SCHEMA), |
0ab08ac9 DM |
1096 | ("backup-type", false, &BACKUP_TYPE_SCHEMA), |
1097 | ("backup-id", false, &BACKUP_ID_SCHEMA), | |
1098 | ("backup-time", false, &BACKUP_TIME_SCHEMA), | |
4191018c | 1099 | ("file-name", false, &BACKUP_ARCHIVE_NAME_SCHEMA), |
0ab08ac9 DM |
1100 | ]), |
1101 | ) | |
54552dda DM |
1102 | ).access(None, &Permission::Privilege( |
1103 | &["datastore", "{store}"], | |
1104 | PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP, | |
1105 | true) | |
1106 | ); | |
691c89a0 | 1107 | |
bf78f708 | 1108 | pub fn download_file( |
9e47c0a5 DM |
1109 | _parts: Parts, |
1110 | _req_body: Body, | |
1111 | param: Value, | |
255f378a | 1112 | _info: &ApiMethod, |
54552dda | 1113 | rpcenv: Box<dyn RpcEnvironment>, |
bb084b9c | 1114 | ) -> ApiResponseFuture { |
9e47c0a5 | 1115 | |
ad51d02a | 1116 | async move { |
3c8c2827 | 1117 | let store = required_string_param(¶m, "store")?; |
ad51d02a | 1118 | let datastore = DataStore::lookup_datastore(store)?; |
f14a8c9a | 1119 | |
e6dc35ac | 1120 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
54552dda | 1121 | |
3c8c2827 | 1122 | let file_name = required_string_param(¶m, "file-name")?.to_owned(); |
9e47c0a5 | 1123 | |
3c8c2827 WB |
1124 | let backup_type = required_string_param(¶m, "backup-type")?; |
1125 | let backup_id = required_string_param(¶m, "backup-id")?; | |
1126 | let backup_time = required_integer_param(¶m, "backup-time")?; | |
9e47c0a5 | 1127 | |
e0e5b442 | 1128 | let backup_dir = BackupDir::new(backup_type, backup_id, backup_time)?; |
54552dda | 1129 | |
bff85572 | 1130 | check_priv_or_backup_owner(&datastore, backup_dir.group(), &auth_id, PRIV_DATASTORE_READ)?; |
54552dda | 1131 | |
abdb9763 | 1132 | println!("Download {} from {} ({}/{})", file_name, store, backup_dir, file_name); |
9e47c0a5 | 1133 | |
ad51d02a DM |
1134 | let mut path = datastore.base_path(); |
1135 | path.push(backup_dir.relative_path()); | |
1136 | path.push(&file_name); | |
1137 | ||
ba694720 | 1138 | let file = tokio::fs::File::open(&path) |
8aa67ee7 WB |
1139 | .await |
1140 | .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?; | |
ad51d02a | 1141 | |
db0cb9ce | 1142 | let payload = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new()) |
44288184 | 1143 | .map_ok(|bytes| bytes.freeze()) |
ba694720 DC |
1144 | .map_err(move |err| { |
1145 | eprintln!("error during streaming of '{:?}' - {}", &path, err); | |
1146 | err | |
1147 | }); | |
ad51d02a | 1148 | let body = Body::wrap_stream(payload); |
9e47c0a5 | 1149 | |
ad51d02a DM |
1150 | // fixme: set other headers ? |
1151 | Ok(Response::builder() | |
1152 | .status(StatusCode::OK) | |
1153 | .header(header::CONTENT_TYPE, "application/octet-stream") | |
1154 | .body(body) | |
1155 | .unwrap()) | |
1156 | }.boxed() | |
9e47c0a5 DM |
1157 | } |
1158 | ||
6ef9bb59 DC |
1159 | #[sortable] |
1160 | pub const API_METHOD_DOWNLOAD_FILE_DECODED: ApiMethod = ApiMethod::new( | |
1161 | &ApiHandler::AsyncHttp(&download_file_decoded), | |
1162 | &ObjectSchema::new( | |
1163 | "Download single decoded file from backup snapshot. Only works if it's not encrypted.", | |
1164 | &sorted!([ | |
1165 | ("store", false, &DATASTORE_SCHEMA), | |
1166 | ("backup-type", false, &BACKUP_TYPE_SCHEMA), | |
1167 | ("backup-id", false, &BACKUP_ID_SCHEMA), | |
1168 | ("backup-time", false, &BACKUP_TIME_SCHEMA), | |
1169 | ("file-name", false, &BACKUP_ARCHIVE_NAME_SCHEMA), | |
1170 | ]), | |
1171 | ) | |
1172 | ).access(None, &Permission::Privilege( | |
1173 | &["datastore", "{store}"], | |
1174 | PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP, | |
1175 | true) | |
1176 | ); | |
1177 | ||
bf78f708 | 1178 | pub fn download_file_decoded( |
6ef9bb59 DC |
1179 | _parts: Parts, |
1180 | _req_body: Body, | |
1181 | param: Value, | |
1182 | _info: &ApiMethod, | |
1183 | rpcenv: Box<dyn RpcEnvironment>, | |
1184 | ) -> ApiResponseFuture { | |
1185 | ||
1186 | async move { | |
3c8c2827 | 1187 | let store = required_string_param(¶m, "store")?; |
6ef9bb59 DC |
1188 | let datastore = DataStore::lookup_datastore(store)?; |
1189 | ||
e6dc35ac | 1190 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
6ef9bb59 | 1191 | |
3c8c2827 | 1192 | let file_name = required_string_param(¶m, "file-name")?.to_owned(); |
6ef9bb59 | 1193 | |
3c8c2827 WB |
1194 | let backup_type = required_string_param(¶m, "backup-type")?; |
1195 | let backup_id = required_string_param(¶m, "backup-id")?; | |
1196 | let backup_time = required_integer_param(¶m, "backup-time")?; | |
6ef9bb59 | 1197 | |
e0e5b442 | 1198 | let backup_dir = BackupDir::new(backup_type, backup_id, backup_time)?; |
6ef9bb59 | 1199 | |
bff85572 | 1200 | check_priv_or_backup_owner(&datastore, backup_dir.group(), &auth_id, PRIV_DATASTORE_READ)?; |
6ef9bb59 | 1201 | |
2d55beec | 1202 | let (manifest, files) = read_backup_index(&datastore, &backup_dir)?; |
6ef9bb59 | 1203 | for file in files { |
f28d9088 | 1204 | if file.filename == file_name && file.crypt_mode == Some(CryptMode::Encrypt) { |
6ef9bb59 DC |
1205 | bail!("cannot decode '{}' - is encrypted", file_name); |
1206 | } | |
1207 | } | |
1208 | ||
1209 | println!("Download {} from {} ({}/{})", file_name, store, backup_dir, file_name); | |
1210 | ||
1211 | let mut path = datastore.base_path(); | |
1212 | path.push(backup_dir.relative_path()); | |
1213 | path.push(&file_name); | |
1214 | ||
1215 | let extension = file_name.rsplitn(2, '.').next().unwrap(); | |
1216 | ||
1217 | let body = match extension { | |
1218 | "didx" => { | |
1219 | let index = DynamicIndexReader::open(&path) | |
1220 | .map_err(|err| format_err!("unable to read dynamic index '{:?}' - {}", &path, err))?; | |
2d55beec FG |
1221 | let (csum, size) = index.compute_csum(); |
1222 | manifest.verify_file(&file_name, &csum, size)?; | |
6ef9bb59 | 1223 | |
14f6c9cb | 1224 | let chunk_reader = LocalChunkReader::new(datastore, None, CryptMode::None); |
1ef6e8b6 | 1225 | let reader = CachedChunkReader::new(chunk_reader, index, 1).seekable(); |
f386f512 | 1226 | Body::wrap_stream(AsyncReaderStream::new(reader) |
6ef9bb59 DC |
1227 | .map_err(move |err| { |
1228 | eprintln!("error during streaming of '{:?}' - {}", path, err); | |
1229 | err | |
1230 | })) | |
1231 | }, | |
1232 | "fidx" => { | |
1233 | let index = FixedIndexReader::open(&path) | |
1234 | .map_err(|err| format_err!("unable to read fixed index '{:?}' - {}", &path, err))?; | |
1235 | ||
2d55beec FG |
1236 | let (csum, size) = index.compute_csum(); |
1237 | manifest.verify_file(&file_name, &csum, size)?; | |
1238 | ||
14f6c9cb | 1239 | let chunk_reader = LocalChunkReader::new(datastore, None, CryptMode::None); |
1ef6e8b6 | 1240 | let reader = CachedChunkReader::new(chunk_reader, index, 1).seekable(); |
f386f512 | 1241 | Body::wrap_stream(AsyncReaderStream::with_buffer_size(reader, 4*1024*1024) |
6ef9bb59 DC |
1242 | .map_err(move |err| { |
1243 | eprintln!("error during streaming of '{:?}' - {}", path, err); | |
1244 | err | |
1245 | })) | |
1246 | }, | |
1247 | "blob" => { | |
1248 | let file = std::fs::File::open(&path) | |
8aa67ee7 | 1249 | .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?; |
6ef9bb59 | 1250 | |
2d55beec FG |
1251 | // FIXME: load full blob to verify index checksum? |
1252 | ||
6ef9bb59 DC |
1253 | Body::wrap_stream( |
1254 | WrappedReaderStream::new(DataBlobReader::new(file, None)?) | |
1255 | .map_err(move |err| { | |
1256 | eprintln!("error during streaming of '{:?}' - {}", path, err); | |
1257 | err | |
1258 | }) | |
1259 | ) | |
1260 | }, | |
1261 | extension => { | |
1262 | bail!("cannot download '{}' files", extension); | |
1263 | }, | |
1264 | }; | |
1265 | ||
1266 | // fixme: set other headers ? | |
1267 | Ok(Response::builder() | |
1268 | .status(StatusCode::OK) | |
1269 | .header(header::CONTENT_TYPE, "application/octet-stream") | |
1270 | .body(body) | |
1271 | .unwrap()) | |
1272 | }.boxed() | |
1273 | } | |
1274 | ||
552c2259 | 1275 | #[sortable] |
0ab08ac9 DM |
1276 | pub const API_METHOD_UPLOAD_BACKUP_LOG: ApiMethod = ApiMethod::new( |
1277 | &ApiHandler::AsyncHttp(&upload_backup_log), | |
255f378a | 1278 | &ObjectSchema::new( |
54552dda | 1279 | "Upload the client backup log file into a backup snapshot ('client.log.blob').", |
552c2259 | 1280 | &sorted!([ |
66c49c21 | 1281 | ("store", false, &DATASTORE_SCHEMA), |
255f378a | 1282 | ("backup-type", false, &BACKUP_TYPE_SCHEMA), |
0ab08ac9 | 1283 | ("backup-id", false, &BACKUP_ID_SCHEMA), |
255f378a | 1284 | ("backup-time", false, &BACKUP_TIME_SCHEMA), |
552c2259 | 1285 | ]), |
9e47c0a5 | 1286 | ) |
54552dda DM |
1287 | ).access( |
1288 | Some("Only the backup creator/owner is allowed to do this."), | |
1289 | &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_BACKUP, false) | |
1290 | ); | |
9e47c0a5 | 1291 | |
bf78f708 | 1292 | pub fn upload_backup_log( |
07ee2235 DM |
1293 | _parts: Parts, |
1294 | req_body: Body, | |
1295 | param: Value, | |
255f378a | 1296 | _info: &ApiMethod, |
54552dda | 1297 | rpcenv: Box<dyn RpcEnvironment>, |
bb084b9c | 1298 | ) -> ApiResponseFuture { |
07ee2235 | 1299 | |
ad51d02a | 1300 | async move { |
3c8c2827 | 1301 | let store = required_string_param(¶m, "store")?; |
ad51d02a | 1302 | let datastore = DataStore::lookup_datastore(store)?; |
07ee2235 | 1303 | |
96d65fbc | 1304 | let file_name = CLIENT_LOG_BLOB_NAME; |
07ee2235 | 1305 | |
3c8c2827 WB |
1306 | let backup_type = required_string_param(¶m, "backup-type")?; |
1307 | let backup_id = required_string_param(¶m, "backup-id")?; | |
1308 | let backup_time = required_integer_param(¶m, "backup-time")?; | |
07ee2235 | 1309 | |
e0e5b442 | 1310 | let backup_dir = BackupDir::new(backup_type, backup_id, backup_time)?; |
07ee2235 | 1311 | |
e6dc35ac | 1312 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
bff85572 FG |
1313 | let owner = datastore.get_owner(backup_dir.group())?; |
1314 | check_backup_owner(&owner, &auth_id)?; | |
54552dda | 1315 | |
ad51d02a DM |
1316 | let mut path = datastore.base_path(); |
1317 | path.push(backup_dir.relative_path()); | |
1318 | path.push(&file_name); | |
07ee2235 | 1319 | |
ad51d02a DM |
1320 | if path.exists() { |
1321 | bail!("backup already contains a log."); | |
1322 | } | |
e128d4e8 | 1323 | |
ad51d02a | 1324 | println!("Upload backup log to {}/{}/{}/{}/{}", store, |
6a7be83e | 1325 | backup_type, backup_id, backup_dir.backup_time_string(), file_name); |
ad51d02a DM |
1326 | |
1327 | let data = req_body | |
1328 | .map_err(Error::from) | |
1329 | .try_fold(Vec::new(), |mut acc, chunk| { | |
1330 | acc.extend_from_slice(&*chunk); | |
1331 | future::ok::<_, Error>(acc) | |
1332 | }) | |
1333 | .await?; | |
1334 | ||
39f18b30 DM |
1335 | // always verify blob/CRC at server side |
1336 | let blob = DataBlob::load_from_reader(&mut &data[..])?; | |
1337 | ||
e0a19d33 | 1338 | replace_file(&path, blob.raw_data(), CreateOptions::new(), false)?; |
ad51d02a DM |
1339 | |
1340 | // fixme: use correct formatter | |
53daae8e | 1341 | Ok(formatter::JSON_FORMATTER.format_data(Value::Null, &*rpcenv)) |
ad51d02a | 1342 | }.boxed() |
07ee2235 DM |
1343 | } |
1344 | ||
5b1cfa01 DC |
1345 | #[api( |
1346 | input: { | |
1347 | properties: { | |
1348 | store: { | |
1349 | schema: DATASTORE_SCHEMA, | |
1350 | }, | |
1351 | "backup-type": { | |
1352 | schema: BACKUP_TYPE_SCHEMA, | |
1353 | }, | |
1354 | "backup-id": { | |
1355 | schema: BACKUP_ID_SCHEMA, | |
1356 | }, | |
1357 | "backup-time": { | |
1358 | schema: BACKUP_TIME_SCHEMA, | |
1359 | }, | |
1360 | "filepath": { | |
1361 | description: "Base64 encoded path.", | |
1362 | type: String, | |
1363 | } | |
1364 | }, | |
1365 | }, | |
1366 | access: { | |
1367 | permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP, true), | |
1368 | }, | |
1369 | )] | |
1370 | /// Get the entries of the given path of the catalog | |
bf78f708 | 1371 | pub fn catalog( |
5b1cfa01 DC |
1372 | store: String, |
1373 | backup_type: String, | |
1374 | backup_id: String, | |
1375 | backup_time: i64, | |
1376 | filepath: String, | |
5b1cfa01 | 1377 | rpcenv: &mut dyn RpcEnvironment, |
227501c0 | 1378 | ) -> Result<Vec<ArchiveEntry>, Error> { |
5b1cfa01 DC |
1379 | let datastore = DataStore::lookup_datastore(&store)?; |
1380 | ||
e6dc35ac | 1381 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
5b1cfa01 | 1382 | |
e0e5b442 | 1383 | let backup_dir = BackupDir::new(backup_type, backup_id, backup_time)?; |
5b1cfa01 | 1384 | |
bff85572 | 1385 | check_priv_or_backup_owner(&datastore, backup_dir.group(), &auth_id, PRIV_DATASTORE_READ)?; |
5b1cfa01 | 1386 | |
9238cdf5 FG |
1387 | let file_name = CATALOG_NAME; |
1388 | ||
2d55beec | 1389 | let (manifest, files) = read_backup_index(&datastore, &backup_dir)?; |
9238cdf5 FG |
1390 | for file in files { |
1391 | if file.filename == file_name && file.crypt_mode == Some(CryptMode::Encrypt) { | |
1392 | bail!("cannot decode '{}' - is encrypted", file_name); | |
1393 | } | |
1394 | } | |
1395 | ||
5b1cfa01 DC |
1396 | let mut path = datastore.base_path(); |
1397 | path.push(backup_dir.relative_path()); | |
9238cdf5 | 1398 | path.push(file_name); |
5b1cfa01 DC |
1399 | |
1400 | let index = DynamicIndexReader::open(&path) | |
1401 | .map_err(|err| format_err!("unable to read dynamic index '{:?}' - {}", &path, err))?; | |
1402 | ||
2d55beec FG |
1403 | let (csum, size) = index.compute_csum(); |
1404 | manifest.verify_file(&file_name, &csum, size)?; | |
1405 | ||
14f6c9cb | 1406 | let chunk_reader = LocalChunkReader::new(datastore, None, CryptMode::None); |
5b1cfa01 DC |
1407 | let reader = BufferedDynamicReader::new(index, chunk_reader); |
1408 | ||
1409 | let mut catalog_reader = CatalogReader::new(reader); | |
5b1cfa01 | 1410 | |
5279ee74 | 1411 | let path = if filepath != "root" && filepath != "/" { |
227501c0 DC |
1412 | base64::decode(filepath)? |
1413 | } else { | |
1414 | vec![b'/'] | |
1415 | }; | |
5b1cfa01 | 1416 | |
86582454 | 1417 | catalog_reader.list_dir_contents(&path) |
5b1cfa01 DC |
1418 | } |
1419 | ||
d33d8f4e DC |
1420 | #[sortable] |
1421 | pub const API_METHOD_PXAR_FILE_DOWNLOAD: ApiMethod = ApiMethod::new( | |
1422 | &ApiHandler::AsyncHttp(&pxar_file_download), | |
1423 | &ObjectSchema::new( | |
1ffe0301 | 1424 | "Download single file from pxar file of a backup snapshot. Only works if it's not encrypted.", |
d33d8f4e DC |
1425 | &sorted!([ |
1426 | ("store", false, &DATASTORE_SCHEMA), | |
1427 | ("backup-type", false, &BACKUP_TYPE_SCHEMA), | |
1428 | ("backup-id", false, &BACKUP_ID_SCHEMA), | |
1429 | ("backup-time", false, &BACKUP_TIME_SCHEMA), | |
1430 | ("filepath", false, &StringSchema::new("Base64 encoded path").schema()), | |
1431 | ]), | |
1432 | ) | |
1433 | ).access(None, &Permission::Privilege( | |
1434 | &["datastore", "{store}"], | |
1435 | PRIV_DATASTORE_READ | PRIV_DATASTORE_BACKUP, | |
1436 | true) | |
1437 | ); | |
1438 | ||
bf78f708 | 1439 | pub fn pxar_file_download( |
d33d8f4e DC |
1440 | _parts: Parts, |
1441 | _req_body: Body, | |
1442 | param: Value, | |
1443 | _info: &ApiMethod, | |
1444 | rpcenv: Box<dyn RpcEnvironment>, | |
1445 | ) -> ApiResponseFuture { | |
1446 | ||
1447 | async move { | |
3c8c2827 | 1448 | let store = required_string_param(¶m, "store")?; |
d33d8f4e DC |
1449 | let datastore = DataStore::lookup_datastore(&store)?; |
1450 | ||
e6dc35ac | 1451 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
d33d8f4e | 1452 | |
3c8c2827 | 1453 | let filepath = required_string_param(¶m, "filepath")?.to_owned(); |
d33d8f4e | 1454 | |
3c8c2827 WB |
1455 | let backup_type = required_string_param(¶m, "backup-type")?; |
1456 | let backup_id = required_string_param(¶m, "backup-id")?; | |
1457 | let backup_time = required_integer_param(¶m, "backup-time")?; | |
d33d8f4e | 1458 | |
e0e5b442 | 1459 | let backup_dir = BackupDir::new(backup_type, backup_id, backup_time)?; |
d33d8f4e | 1460 | |
bff85572 | 1461 | check_priv_or_backup_owner(&datastore, backup_dir.group(), &auth_id, PRIV_DATASTORE_READ)?; |
d33d8f4e | 1462 | |
d33d8f4e | 1463 | let mut components = base64::decode(&filepath)?; |
3984a5fd | 1464 | if !components.is_empty() && components[0] == b'/' { |
d33d8f4e DC |
1465 | components.remove(0); |
1466 | } | |
1467 | ||
d8d8af98 | 1468 | let mut split = components.splitn(2, |c| *c == b'/'); |
9238cdf5 | 1469 | let pxar_name = std::str::from_utf8(split.next().unwrap())?; |
0dfce17a | 1470 | let file_path = split.next().unwrap_or(b"/"); |
2d55beec | 1471 | let (manifest, files) = read_backup_index(&datastore, &backup_dir)?; |
9238cdf5 FG |
1472 | for file in files { |
1473 | if file.filename == pxar_name && file.crypt_mode == Some(CryptMode::Encrypt) { | |
1474 | bail!("cannot decode '{}' - is encrypted", pxar_name); | |
1475 | } | |
1476 | } | |
d33d8f4e | 1477 | |
9238cdf5 FG |
1478 | let mut path = datastore.base_path(); |
1479 | path.push(backup_dir.relative_path()); | |
1480 | path.push(pxar_name); | |
d33d8f4e DC |
1481 | |
1482 | let index = DynamicIndexReader::open(&path) | |
1483 | .map_err(|err| format_err!("unable to read dynamic index '{:?}' - {}", &path, err))?; | |
1484 | ||
2d55beec FG |
1485 | let (csum, size) = index.compute_csum(); |
1486 | manifest.verify_file(&pxar_name, &csum, size)?; | |
1487 | ||
14f6c9cb | 1488 | let chunk_reader = LocalChunkReader::new(datastore, None, CryptMode::None); |
d33d8f4e DC |
1489 | let reader = BufferedDynamicReader::new(index, chunk_reader); |
1490 | let archive_size = reader.archive_size(); | |
1491 | let reader = LocalDynamicReadAt::new(reader); | |
1492 | ||
1493 | let decoder = Accessor::new(reader, archive_size).await?; | |
1494 | let root = decoder.open_root().await?; | |
2e219481 | 1495 | let path = OsStr::from_bytes(file_path).to_os_string(); |
d33d8f4e | 1496 | let file = root |
2e219481 DC |
1497 | .lookup(&path).await? |
1498 | .ok_or_else(|| format_err!("error opening '{:?}'", path))?; | |
d33d8f4e | 1499 | |
804f6143 DC |
1500 | let body = match file.kind() { |
1501 | EntryKind::File { .. } => Body::wrap_stream( | |
1502 | AsyncReaderStream::new(file.contents().await?).map_err(move |err| { | |
1503 | eprintln!("error during streaming of file '{:?}' - {}", filepath, err); | |
1504 | err | |
1505 | }), | |
1506 | ), | |
1507 | EntryKind::Hardlink(_) => Body::wrap_stream( | |
1508 | AsyncReaderStream::new(decoder.follow_hardlink(&file).await?.contents().await?) | |
1509 | .map_err(move |err| { | |
1510 | eprintln!( | |
1511 | "error during streaming of hardlink '{:?}' - {}", | |
2e219481 | 1512 | path, err |
804f6143 DC |
1513 | ); |
1514 | err | |
1515 | }), | |
1516 | ), | |
1517 | EntryKind::Directory => { | |
1518 | let (sender, receiver) = tokio::sync::mpsc::channel(100); | |
804f6143 | 1519 | let channelwriter = AsyncChannelWriter::new(sender, 1024 * 1024); |
fd6d2438 | 1520 | proxmox_rest_server::spawn_internal_task( |
2e219481 DC |
1521 | create_zip(channelwriter, decoder, path.clone(), false) |
1522 | ); | |
7c667013 | 1523 | Body::wrap_stream(ReceiverStream::new(receiver).map_err(move |err| { |
2e219481 | 1524 | eprintln!("error during streaming of zip '{:?}' - {}", path, err); |
d33d8f4e | 1525 | err |
804f6143 DC |
1526 | })) |
1527 | } | |
1528 | other => bail!("cannot download file of type {:?}", other), | |
1529 | }; | |
d33d8f4e DC |
1530 | |
1531 | // fixme: set other headers ? | |
1532 | Ok(Response::builder() | |
1533 | .status(StatusCode::OK) | |
1534 | .header(header::CONTENT_TYPE, "application/octet-stream") | |
1535 | .body(body) | |
1536 | .unwrap()) | |
1537 | }.boxed() | |
1538 | } | |
1539 | ||
1a0d3d11 DM |
1540 | #[api( |
1541 | input: { | |
1542 | properties: { | |
1543 | store: { | |
1544 | schema: DATASTORE_SCHEMA, | |
1545 | }, | |
1546 | timeframe: { | |
c68fa58a | 1547 | type: RRDTimeFrame, |
1a0d3d11 DM |
1548 | }, |
1549 | cf: { | |
1550 | type: RRDMode, | |
1551 | }, | |
1552 | }, | |
1553 | }, | |
1554 | access: { | |
1555 | permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP, true), | |
1556 | }, | |
1557 | )] | |
1558 | /// Read datastore stats | |
bf78f708 | 1559 | pub fn get_rrd_stats( |
1a0d3d11 | 1560 | store: String, |
c68fa58a | 1561 | timeframe: RRDTimeFrame, |
1a0d3d11 DM |
1562 | cf: RRDMode, |
1563 | _param: Value, | |
1564 | ) -> Result<Value, Error> { | |
1565 | ||
431cc7b1 DC |
1566 | create_value_from_rrd( |
1567 | &format!("datastore/{}", store), | |
1a0d3d11 DM |
1568 | &[ |
1569 | "total", "used", | |
c94e1f65 DM |
1570 | "read_ios", "read_bytes", |
1571 | "write_ios", "write_bytes", | |
1572 | "io_ticks", | |
1a0d3d11 DM |
1573 | ], |
1574 | timeframe, | |
1575 | cf, | |
1576 | ) | |
1577 | } | |
1578 | ||
d6688884 SR |
1579 | #[api( |
1580 | input: { | |
1581 | properties: { | |
1582 | store: { | |
1583 | schema: DATASTORE_SCHEMA, | |
1584 | }, | |
1585 | "backup-type": { | |
1586 | schema: BACKUP_TYPE_SCHEMA, | |
1587 | }, | |
1588 | "backup-id": { | |
1589 | schema: BACKUP_ID_SCHEMA, | |
1590 | }, | |
1591 | }, | |
1592 | }, | |
1593 | access: { | |
1594 | permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP, true), | |
1595 | }, | |
1596 | )] | |
1597 | /// Get "notes" for a backup group | |
1598 | pub fn get_group_notes( | |
1599 | store: String, | |
1600 | backup_type: String, | |
1601 | backup_id: String, | |
1602 | rpcenv: &mut dyn RpcEnvironment, | |
1603 | ) -> Result<String, Error> { | |
1604 | let datastore = DataStore::lookup_datastore(&store)?; | |
1605 | ||
1606 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; | |
1607 | let backup_group = BackupGroup::new(backup_type, backup_id); | |
1608 | ||
1609 | check_priv_or_backup_owner(&datastore, &backup_group, &auth_id, PRIV_DATASTORE_AUDIT)?; | |
1610 | ||
1611 | let note_path = get_group_note_path(&datastore, &backup_group); | |
1612 | Ok(file_read_optional_string(note_path)?.unwrap_or_else(|| "".to_owned())) | |
1613 | } | |
1614 | ||
1615 | #[api( | |
1616 | input: { | |
1617 | properties: { | |
1618 | store: { | |
1619 | schema: DATASTORE_SCHEMA, | |
1620 | }, | |
1621 | "backup-type": { | |
1622 | schema: BACKUP_TYPE_SCHEMA, | |
1623 | }, | |
1624 | "backup-id": { | |
1625 | schema: BACKUP_ID_SCHEMA, | |
1626 | }, | |
1627 | notes: { | |
1628 | description: "A multiline text.", | |
1629 | }, | |
1630 | }, | |
1631 | }, | |
1632 | access: { | |
1633 | permission: &Permission::Privilege(&["datastore", "{store}"], | |
1634 | PRIV_DATASTORE_MODIFY | PRIV_DATASTORE_BACKUP, | |
1635 | true), | |
1636 | }, | |
1637 | )] | |
1638 | /// Set "notes" for a backup group | |
1639 | pub fn set_group_notes( | |
1640 | store: String, | |
1641 | backup_type: String, | |
1642 | backup_id: String, | |
1643 | notes: String, | |
1644 | rpcenv: &mut dyn RpcEnvironment, | |
1645 | ) -> Result<(), Error> { | |
1646 | let datastore = DataStore::lookup_datastore(&store)?; | |
1647 | ||
1648 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; | |
1649 | let backup_group = BackupGroup::new(backup_type, backup_id); | |
1650 | ||
1651 | check_priv_or_backup_owner(&datastore, &backup_group, &auth_id, PRIV_DATASTORE_MODIFY)?; | |
1652 | ||
1653 | let note_path = get_group_note_path(&datastore, &backup_group); | |
e0a19d33 | 1654 | replace_file(note_path, notes.as_bytes(), CreateOptions::new(), false)?; |
d6688884 SR |
1655 | |
1656 | Ok(()) | |
1657 | } | |
1658 | ||
912b3f5b DM |
1659 | #[api( |
1660 | input: { | |
1661 | properties: { | |
1662 | store: { | |
1663 | schema: DATASTORE_SCHEMA, | |
1664 | }, | |
1665 | "backup-type": { | |
1666 | schema: BACKUP_TYPE_SCHEMA, | |
1667 | }, | |
1668 | "backup-id": { | |
1669 | schema: BACKUP_ID_SCHEMA, | |
1670 | }, | |
1671 | "backup-time": { | |
1672 | schema: BACKUP_TIME_SCHEMA, | |
1673 | }, | |
1674 | }, | |
1675 | }, | |
1676 | access: { | |
1401f4be | 1677 | permission: &Permission::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP, true), |
912b3f5b DM |
1678 | }, |
1679 | )] | |
1680 | /// Get "notes" for a specific backup | |
bf78f708 | 1681 | pub fn get_notes( |
912b3f5b DM |
1682 | store: String, |
1683 | backup_type: String, | |
1684 | backup_id: String, | |
1685 | backup_time: i64, | |
1686 | rpcenv: &mut dyn RpcEnvironment, | |
1687 | ) -> Result<String, Error> { | |
1688 | let datastore = DataStore::lookup_datastore(&store)?; | |
1689 | ||
e6dc35ac | 1690 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
e0e5b442 | 1691 | let backup_dir = BackupDir::new(backup_type, backup_id, backup_time)?; |
912b3f5b | 1692 | |
1401f4be | 1693 | check_priv_or_backup_owner(&datastore, backup_dir.group(), &auth_id, PRIV_DATASTORE_AUDIT)?; |
912b3f5b | 1694 | |
883aa6d5 | 1695 | let (manifest, _) = datastore.load_manifest(&backup_dir)?; |
912b3f5b | 1696 | |
883aa6d5 | 1697 | let notes = manifest.unprotected["notes"] |
912b3f5b DM |
1698 | .as_str() |
1699 | .unwrap_or(""); | |
1700 | ||
1701 | Ok(String::from(notes)) | |
1702 | } | |
1703 | ||
1704 | #[api( | |
1705 | input: { | |
1706 | properties: { | |
1707 | store: { | |
1708 | schema: DATASTORE_SCHEMA, | |
1709 | }, | |
1710 | "backup-type": { | |
1711 | schema: BACKUP_TYPE_SCHEMA, | |
1712 | }, | |
1713 | "backup-id": { | |
1714 | schema: BACKUP_ID_SCHEMA, | |
1715 | }, | |
1716 | "backup-time": { | |
1717 | schema: BACKUP_TIME_SCHEMA, | |
1718 | }, | |
1719 | notes: { | |
1720 | description: "A multiline text.", | |
1721 | }, | |
1722 | }, | |
1723 | }, | |
1724 | access: { | |
b728a69e FG |
1725 | permission: &Permission::Privilege(&["datastore", "{store}"], |
1726 | PRIV_DATASTORE_MODIFY | PRIV_DATASTORE_BACKUP, | |
1727 | true), | |
912b3f5b DM |
1728 | }, |
1729 | )] | |
1730 | /// Set "notes" for a specific backup | |
bf78f708 | 1731 | pub fn set_notes( |
912b3f5b DM |
1732 | store: String, |
1733 | backup_type: String, | |
1734 | backup_id: String, | |
1735 | backup_time: i64, | |
1736 | notes: String, | |
1737 | rpcenv: &mut dyn RpcEnvironment, | |
1738 | ) -> Result<(), Error> { | |
1739 | let datastore = DataStore::lookup_datastore(&store)?; | |
1740 | ||
e6dc35ac | 1741 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
e0e5b442 | 1742 | let backup_dir = BackupDir::new(backup_type, backup_id, backup_time)?; |
912b3f5b | 1743 | |
b728a69e | 1744 | check_priv_or_backup_owner(&datastore, backup_dir.group(), &auth_id, PRIV_DATASTORE_MODIFY)?; |
912b3f5b | 1745 | |
1a374fcf SR |
1746 | datastore.update_manifest(&backup_dir,|manifest| { |
1747 | manifest.unprotected["notes"] = notes.into(); | |
1748 | }).map_err(|err| format_err!("unable to update manifest blob - {}", err))?; | |
912b3f5b DM |
1749 | |
1750 | Ok(()) | |
1751 | } | |
1752 | ||
72be0eb1 | 1753 | #[api( |
4940012d | 1754 | input: { |
72be0eb1 DW |
1755 | properties: { |
1756 | store: { | |
1757 | schema: DATASTORE_SCHEMA, | |
1758 | }, | |
1759 | "backup-type": { | |
1760 | schema: BACKUP_TYPE_SCHEMA, | |
1761 | }, | |
1762 | "backup-id": { | |
1763 | schema: BACKUP_ID_SCHEMA, | |
1764 | }, | |
1765 | "new-owner": { | |
e6dc35ac | 1766 | type: Authid, |
72be0eb1 DW |
1767 | }, |
1768 | }, | |
4940012d FG |
1769 | }, |
1770 | access: { | |
bff85572 FG |
1771 | permission: &Permission::Anybody, |
1772 | description: "Datastore.Modify on whole datastore, or changing ownership between user and a user's token for owned backups with Datastore.Backup" | |
4940012d | 1773 | }, |
72be0eb1 DW |
1774 | )] |
1775 | /// Change owner of a backup group | |
bf78f708 | 1776 | pub fn set_backup_owner( |
72be0eb1 DW |
1777 | store: String, |
1778 | backup_type: String, | |
1779 | backup_id: String, | |
e6dc35ac | 1780 | new_owner: Authid, |
bff85572 | 1781 | rpcenv: &mut dyn RpcEnvironment, |
72be0eb1 DW |
1782 | ) -> Result<(), Error> { |
1783 | ||
1784 | let datastore = DataStore::lookup_datastore(&store)?; | |
1785 | ||
1786 | let backup_group = BackupGroup::new(backup_type, backup_id); | |
1787 | ||
bff85572 FG |
1788 | let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?; |
1789 | ||
72be0eb1 DW |
1790 | let user_info = CachedUserInfo::new()?; |
1791 | ||
bff85572 FG |
1792 | let privs = user_info.lookup_privs(&auth_id, &["datastore", &store]); |
1793 | ||
1794 | let allowed = if (privs & PRIV_DATASTORE_MODIFY) != 0 { | |
1795 | // High-privilege user/token | |
1796 | true | |
1797 | } else if (privs & PRIV_DATASTORE_BACKUP) != 0 { | |
1798 | let owner = datastore.get_owner(&backup_group)?; | |
1799 | ||
1800 | match (owner.is_token(), new_owner.is_token()) { | |
1801 | (true, true) => { | |
1802 | // API token to API token, owned by same user | |
1803 | let owner = owner.user(); | |
1804 | let new_owner = new_owner.user(); | |
1805 | owner == new_owner && Authid::from(owner.clone()) == auth_id | |
1806 | }, | |
1807 | (true, false) => { | |
1808 | // API token to API token owner | |
1809 | Authid::from(owner.user().clone()) == auth_id | |
1810 | && new_owner == auth_id | |
1811 | }, | |
1812 | (false, true) => { | |
1813 | // API token owner to API token | |
1814 | owner == auth_id | |
1815 | && Authid::from(new_owner.user().clone()) == auth_id | |
1816 | }, | |
1817 | (false, false) => { | |
1818 | // User to User, not allowed for unprivileged users | |
1819 | false | |
1820 | }, | |
1821 | } | |
1822 | } else { | |
1823 | false | |
1824 | }; | |
1825 | ||
1826 | if !allowed { | |
1827 | return Err(http_err!(UNAUTHORIZED, | |
1828 | "{} does not have permission to change owner of backup group '{}' to {}", | |
1829 | auth_id, | |
1830 | backup_group, | |
1831 | new_owner, | |
1832 | )); | |
1833 | } | |
1834 | ||
e6dc35ac FG |
1835 | if !user_info.is_active_auth_id(&new_owner) { |
1836 | bail!("{} '{}' is inactive or non-existent", | |
1837 | if new_owner.is_token() { | |
1838 | "API token".to_string() | |
1839 | } else { | |
1840 | "user".to_string() | |
1841 | }, | |
1842 | new_owner); | |
72be0eb1 DW |
1843 | } |
1844 | ||
1845 | datastore.set_owner(&backup_group, &new_owner, true)?; | |
1846 | ||
1847 | Ok(()) | |
1848 | } | |
1849 | ||
552c2259 | 1850 | #[sortable] |
255f378a | 1851 | const DATASTORE_INFO_SUBDIRS: SubdirMap = &[ |
5b1cfa01 DC |
1852 | ( |
1853 | "catalog", | |
1854 | &Router::new() | |
1855 | .get(&API_METHOD_CATALOG) | |
1856 | ), | |
72be0eb1 DW |
1857 | ( |
1858 | "change-owner", | |
1859 | &Router::new() | |
1860 | .post(&API_METHOD_SET_BACKUP_OWNER) | |
1861 | ), | |
255f378a DM |
1862 | ( |
1863 | "download", | |
1864 | &Router::new() | |
1865 | .download(&API_METHOD_DOWNLOAD_FILE) | |
1866 | ), | |
6ef9bb59 DC |
1867 | ( |
1868 | "download-decoded", | |
1869 | &Router::new() | |
1870 | .download(&API_METHOD_DOWNLOAD_FILE_DECODED) | |
1871 | ), | |
255f378a DM |
1872 | ( |
1873 | "files", | |
1874 | &Router::new() | |
09b1f7b2 | 1875 | .get(&API_METHOD_LIST_SNAPSHOT_FILES) |
255f378a DM |
1876 | ), |
1877 | ( | |
1878 | "gc", | |
1879 | &Router::new() | |
1880 | .get(&API_METHOD_GARBAGE_COLLECTION_STATUS) | |
1881 | .post(&API_METHOD_START_GARBAGE_COLLECTION) | |
1882 | ), | |
d6688884 SR |
1883 | ( |
1884 | "group-notes", | |
1885 | &Router::new() | |
1886 | .get(&API_METHOD_GET_GROUP_NOTES) | |
1887 | .put(&API_METHOD_SET_GROUP_NOTES) | |
1888 | ), | |
255f378a DM |
1889 | ( |
1890 | "groups", | |
1891 | &Router::new() | |
b31c8019 | 1892 | .get(&API_METHOD_LIST_GROUPS) |
f32791b4 | 1893 | .delete(&API_METHOD_DELETE_GROUP) |
255f378a | 1894 | ), |
912b3f5b DM |
1895 | ( |
1896 | "notes", | |
1897 | &Router::new() | |
1898 | .get(&API_METHOD_GET_NOTES) | |
1899 | .put(&API_METHOD_SET_NOTES) | |
1900 | ), | |
255f378a DM |
1901 | ( |
1902 | "prune", | |
1903 | &Router::new() | |
1904 | .post(&API_METHOD_PRUNE) | |
1905 | ), | |
9805207a DC |
1906 | ( |
1907 | "prune-datastore", | |
1908 | &Router::new() | |
1909 | .post(&API_METHOD_PRUNE_DATASTORE) | |
1910 | ), | |
d33d8f4e DC |
1911 | ( |
1912 | "pxar-file-download", | |
1913 | &Router::new() | |
1914 | .download(&API_METHOD_PXAR_FILE_DOWNLOAD) | |
1915 | ), | |
1a0d3d11 DM |
1916 | ( |
1917 | "rrd", | |
1918 | &Router::new() | |
1919 | .get(&API_METHOD_GET_RRD_STATS) | |
1920 | ), | |
255f378a DM |
1921 | ( |
1922 | "snapshots", | |
1923 | &Router::new() | |
fc189b19 | 1924 | .get(&API_METHOD_LIST_SNAPSHOTS) |
68a6a0ee | 1925 | .delete(&API_METHOD_DELETE_SNAPSHOT) |
255f378a DM |
1926 | ), |
1927 | ( | |
1928 | "status", | |
1929 | &Router::new() | |
1930 | .get(&API_METHOD_STATUS) | |
1931 | ), | |
1932 | ( | |
1933 | "upload-backup-log", | |
1934 | &Router::new() | |
1935 | .upload(&API_METHOD_UPLOAD_BACKUP_LOG) | |
1936 | ), | |
c2009e53 DM |
1937 | ( |
1938 | "verify", | |
1939 | &Router::new() | |
1940 | .post(&API_METHOD_VERIFY) | |
1941 | ), | |
255f378a DM |
1942 | ]; |
1943 | ||
ad51d02a | 1944 | const DATASTORE_INFO_ROUTER: Router = Router::new() |
255f378a DM |
1945 | .get(&list_subdirs_api_method!(DATASTORE_INFO_SUBDIRS)) |
1946 | .subdirs(DATASTORE_INFO_SUBDIRS); | |
1947 | ||
1948 | ||
1949 | pub const ROUTER: Router = Router::new() | |
bb34b589 | 1950 | .get(&API_METHOD_GET_DATASTORE_LIST) |
255f378a | 1951 | .match_all("store", &DATASTORE_INFO_ROUTER); |