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