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