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