]>
Commit | Line | Data |
---|---|---|
ff5d3707 | 1 | use failure::*; |
70235f72 CE |
2 | use nix::unistd::{fork, ForkResult, pipe}; |
3 | use std::os::unix::io::RawFd; | |
fa5d6977 | 4 | use chrono::{Local, Utc, TimeZone}; |
e9c9409a | 5 | use std::path::{Path, PathBuf}; |
2eeaacb9 | 6 | use std::collections::{HashSet, HashMap}; |
70235f72 | 7 | use std::ffi::OsStr; |
bb19af73 | 8 | use std::io::{Write, Seek, SeekFrom}; |
2761d6a4 DM |
9 | use std::os::unix::fs::OpenOptionsExt; |
10 | ||
552c2259 | 11 | use proxmox::{sortable, identity}; |
feaa1ad3 | 12 | use proxmox::tools::fs::{file_get_contents, file_get_json, replace_file, CreateOptions, image_size}; |
a47a02ae | 13 | use proxmox::api::{ApiHandler, ApiMethod, RpcEnvironment}; |
3d482025 | 14 | use proxmox::api::schema::*; |
7eea56ca | 15 | use proxmox::api::cli::*; |
5830c205 | 16 | use proxmox::api::api; |
ff5d3707 | 17 | |
fe0e04c6 | 18 | use proxmox_backup::tools; |
bbf9e7e9 | 19 | use proxmox_backup::api2::types::*; |
151c6ce2 | 20 | use proxmox_backup::client::*; |
247cdbce | 21 | use proxmox_backup::backup::*; |
7926a3a1 | 22 | use proxmox_backup::pxar::{ self, catalog::* }; |
86eda3eb | 23 | |
fe0e04c6 DM |
24 | //use proxmox_backup::backup::image_index::*; |
25 | //use proxmox_backup::config::datastore; | |
8968258b | 26 | //use proxmox_backup::pxar::encoder::*; |
728797d0 | 27 | //use proxmox_backup::backup::datastore::*; |
23bb8780 | 28 | |
f5f13ebc | 29 | use serde_json::{json, Value}; |
1c0472e8 | 30 | //use hyper::Body; |
2761d6a4 | 31 | use std::sync::{Arc, Mutex}; |
255f378a | 32 | //use regex::Regex; |
d0a03d40 | 33 | use xdg::BaseDirectories; |
ae0be2dd | 34 | |
5a2df000 | 35 | use futures::*; |
c4ff3dce | 36 | use tokio::sync::mpsc; |
ae0be2dd | 37 | |
3d482025 | 38 | proxmox::api::const_regex! { |
255f378a | 39 | BACKUPSPEC_REGEX = r"^([a-zA-Z0-9_-]+\.(?:pxar|img|conf|log)):(.+)$"; |
ae0be2dd | 40 | } |
33d64b81 | 41 | |
255f378a DM |
42 | const REPO_URL_SCHEMA: Schema = StringSchema::new("Repository URL.") |
43 | .format(&BACKUP_REPO_URL) | |
44 | .max_length(256) | |
45 | .schema(); | |
d0a03d40 | 46 | |
a47a02ae DM |
47 | const BACKUP_SOURCE_SCHEMA: Schema = StringSchema::new( |
48 | "Backup source specification ([<label>:<path>]).") | |
49 | .format(&ApiStringFormat::Pattern(&BACKUPSPEC_REGEX)) | |
50 | .schema(); | |
51 | ||
52 | const KEYFILE_SCHEMA: Schema = StringSchema::new( | |
53 | "Path to encryption key. All data will be encrypted using this key.") | |
54 | .schema(); | |
55 | ||
56 | const CHUNK_SIZE_SCHEMA: Schema = IntegerSchema::new( | |
57 | "Chunk size in KB. Must be a power of 2.") | |
58 | .minimum(64) | |
59 | .maximum(4096) | |
60 | .default(4096) | |
61 | .schema(); | |
62 | ||
2665cef7 DM |
63 | fn get_default_repository() -> Option<String> { |
64 | std::env::var("PBS_REPOSITORY").ok() | |
65 | } | |
66 | ||
67 | fn extract_repository_from_value( | |
68 | param: &Value, | |
69 | ) -> Result<BackupRepository, Error> { | |
70 | ||
71 | let repo_url = param["repository"] | |
72 | .as_str() | |
73 | .map(String::from) | |
74 | .or_else(get_default_repository) | |
75 | .ok_or_else(|| format_err!("unable to get (default) repository"))?; | |
76 | ||
77 | let repo: BackupRepository = repo_url.parse()?; | |
78 | ||
79 | Ok(repo) | |
80 | } | |
81 | ||
82 | fn extract_repository_from_map( | |
83 | param: &HashMap<String, String>, | |
84 | ) -> Option<BackupRepository> { | |
85 | ||
86 | param.get("repository") | |
87 | .map(String::from) | |
88 | .or_else(get_default_repository) | |
89 | .and_then(|repo_url| repo_url.parse::<BackupRepository>().ok()) | |
90 | } | |
91 | ||
d0a03d40 DM |
92 | fn record_repository(repo: &BackupRepository) { |
93 | ||
94 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
95 | Ok(v) => v, | |
96 | _ => return, | |
97 | }; | |
98 | ||
99 | // usually $HOME/.cache/proxmox-backup/repo-list | |
100 | let path = match base.place_cache_file("repo-list") { | |
101 | Ok(v) => v, | |
102 | _ => return, | |
103 | }; | |
104 | ||
11377a47 | 105 | let mut data = file_get_json(&path, None).unwrap_or_else(|_| json!({})); |
d0a03d40 DM |
106 | |
107 | let repo = repo.to_string(); | |
108 | ||
109 | data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 }; | |
110 | ||
111 | let mut map = serde_json::map::Map::new(); | |
112 | ||
113 | loop { | |
114 | let mut max_used = 0; | |
115 | let mut max_repo = None; | |
116 | for (repo, count) in data.as_object().unwrap() { | |
117 | if map.contains_key(repo) { continue; } | |
118 | if let Some(count) = count.as_i64() { | |
119 | if count > max_used { | |
120 | max_used = count; | |
121 | max_repo = Some(repo); | |
122 | } | |
123 | } | |
124 | } | |
125 | if let Some(repo) = max_repo { | |
126 | map.insert(repo.to_owned(), json!(max_used)); | |
127 | } else { | |
128 | break; | |
129 | } | |
130 | if map.len() > 10 { // store max. 10 repos | |
131 | break; | |
132 | } | |
133 | } | |
134 | ||
135 | let new_data = json!(map); | |
136 | ||
feaa1ad3 | 137 | let _ = replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new()); |
d0a03d40 DM |
138 | } |
139 | ||
49811347 | 140 | fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
d0a03d40 DM |
141 | |
142 | let mut result = vec![]; | |
143 | ||
144 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
145 | Ok(v) => v, | |
146 | _ => return result, | |
147 | }; | |
148 | ||
149 | // usually $HOME/.cache/proxmox-backup/repo-list | |
150 | let path = match base.place_cache_file("repo-list") { | |
151 | Ok(v) => v, | |
152 | _ => return result, | |
153 | }; | |
154 | ||
11377a47 | 155 | let data = file_get_json(&path, None).unwrap_or_else(|_| json!({})); |
d0a03d40 DM |
156 | |
157 | if let Some(map) = data.as_object() { | |
49811347 | 158 | for (repo, _count) in map { |
d0a03d40 DM |
159 | result.push(repo.to_owned()); |
160 | } | |
161 | } | |
162 | ||
163 | result | |
164 | } | |
165 | ||
d105176f DM |
166 | async fn view_task_result( |
167 | client: HttpClient, | |
168 | result: Value, | |
169 | output_format: &str, | |
170 | ) -> Result<(), Error> { | |
171 | let data = &result["data"]; | |
172 | if output_format == "text" { | |
173 | if let Some(upid) = data.as_str() { | |
174 | display_task_log(client, upid, true).await?; | |
175 | } | |
176 | } else { | |
177 | format_and_print_result(&data, &output_format); | |
178 | } | |
179 | ||
180 | Ok(()) | |
181 | } | |
182 | ||
42af4b8f DM |
183 | async fn api_datastore_list_snapshots( |
184 | client: &HttpClient, | |
185 | store: &str, | |
186 | group: Option<BackupGroup>, | |
187 | ) -> Result<Vec<SnapshotListItem>, Error> { | |
188 | ||
189 | let path = format!("api2/json/admin/datastore/{}/snapshots", store); | |
190 | ||
191 | let mut args = json!({}); | |
192 | if let Some(group) = group { | |
193 | args["backup-type"] = group.backup_type().into(); | |
194 | args["backup-id"] = group.backup_id().into(); | |
195 | } | |
196 | ||
197 | let mut result = client.get(&path, Some(args)).await?; | |
198 | ||
199 | let list: Vec<SnapshotListItem> = serde_json::from_value(result["data"].take())?; | |
200 | ||
201 | Ok(list) | |
202 | } | |
203 | ||
e9722f8b | 204 | async fn backup_directory<P: AsRef<Path>>( |
cf9271e2 | 205 | client: &BackupWriter, |
17d6979a | 206 | dir_path: P, |
247cdbce | 207 | archive_name: &str, |
36898ffc | 208 | chunk_size: Option<usize>, |
2eeaacb9 | 209 | device_set: Option<HashSet<u64>>, |
219ef0e6 | 210 | verbose: bool, |
5b72c9b4 | 211 | skip_lost_and_found: bool, |
f98ac774 | 212 | crypt_config: Option<Arc<CryptConfig>>, |
bf6e3217 | 213 | catalog: Arc<Mutex<CatalogWriter<SenderWriter>>>, |
2c3891d1 | 214 | ) -> Result<BackupStats, Error> { |
33d64b81 | 215 | |
2761d6a4 | 216 | let pxar_stream = PxarBackupStream::open(dir_path.as_ref(), device_set, verbose, skip_lost_and_found, catalog)?; |
e9722f8b | 217 | let mut chunk_stream = ChunkStream::new(pxar_stream, chunk_size); |
ff3d3100 | 218 | |
e9722f8b | 219 | let (mut tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks |
5e7a09be | 220 | |
c4ff3dce | 221 | let stream = rx |
e9722f8b | 222 | .map_err(Error::from); |
17d6979a | 223 | |
c4ff3dce | 224 | // spawn chunker inside a separate task so that it can run parallel |
e9722f8b | 225 | tokio::spawn(async move { |
db0cb9ce WB |
226 | while let Some(v) = chunk_stream.next().await { |
227 | let _ = tx.send(v).await; | |
228 | } | |
e9722f8b | 229 | }); |
17d6979a | 230 | |
e9722f8b WB |
231 | let stats = client |
232 | .upload_stream(archive_name, stream, "dynamic", None, crypt_config) | |
233 | .await?; | |
bcd879cf | 234 | |
2c3891d1 | 235 | Ok(stats) |
bcd879cf DM |
236 | } |
237 | ||
e9722f8b | 238 | async fn backup_image<P: AsRef<Path>>( |
cf9271e2 | 239 | client: &BackupWriter, |
6af905c1 DM |
240 | image_path: P, |
241 | archive_name: &str, | |
242 | image_size: u64, | |
36898ffc | 243 | chunk_size: Option<usize>, |
1c0472e8 | 244 | _verbose: bool, |
f98ac774 | 245 | crypt_config: Option<Arc<CryptConfig>>, |
2c3891d1 | 246 | ) -> Result<BackupStats, Error> { |
6af905c1 | 247 | |
6af905c1 DM |
248 | let path = image_path.as_ref().to_owned(); |
249 | ||
e9722f8b | 250 | let file = tokio::fs::File::open(path).await?; |
6af905c1 | 251 | |
db0cb9ce | 252 | let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new()) |
6af905c1 DM |
253 | .map_err(Error::from); |
254 | ||
36898ffc | 255 | let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024)); |
6af905c1 | 256 | |
e9722f8b WB |
257 | let stats = client |
258 | .upload_stream(archive_name, stream, "fixed", Some(image_size), crypt_config) | |
259 | .await?; | |
6af905c1 | 260 | |
2c3891d1 | 261 | Ok(stats) |
6af905c1 DM |
262 | } |
263 | ||
52c171e4 DM |
264 | fn strip_server_file_expenstion(name: &str) -> String { |
265 | ||
11377a47 DM |
266 | if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") { |
267 | name[..name.len()-5].to_owned() | |
52c171e4 | 268 | } else { |
11377a47 | 269 | name.to_owned() // should not happen |
8e39232a | 270 | } |
8e39232a DM |
271 | } |
272 | ||
a47a02ae DM |
273 | #[api( |
274 | input: { | |
275 | properties: { | |
276 | repository: { | |
277 | schema: REPO_URL_SCHEMA, | |
278 | optional: true, | |
279 | }, | |
280 | "output-format": { | |
281 | schema: OUTPUT_FORMAT, | |
282 | optional: true, | |
283 | }, | |
284 | } | |
285 | } | |
286 | )] | |
287 | /// List backup groups. | |
288 | async fn list_backup_groups(param: Value) -> Result<Value, Error> { | |
812c6f87 | 289 | |
2665cef7 | 290 | let repo = extract_repository_from_value(¶m)?; |
812c6f87 | 291 | |
cc2ce4a9 | 292 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
812c6f87 | 293 | |
d0a03d40 | 294 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
812c6f87 | 295 | |
8a8a4703 | 296 | let mut result = client.get(&path, None).await?; |
812c6f87 | 297 | |
d0a03d40 DM |
298 | record_repository(&repo); |
299 | ||
812c6f87 | 300 | // fixme: implement and use output formatter instead .. |
80822b95 DM |
301 | let list = result["data"].as_array_mut().unwrap(); |
302 | ||
303 | list.sort_unstable_by(|a, b| { | |
304 | let a_id = a["backup-id"].as_str().unwrap(); | |
305 | let a_backup_type = a["backup-type"].as_str().unwrap(); | |
306 | let b_id = b["backup-id"].as_str().unwrap(); | |
307 | let b_backup_type = b["backup-type"].as_str().unwrap(); | |
308 | ||
309 | let type_order = a_backup_type.cmp(b_backup_type); | |
310 | if type_order == std::cmp::Ordering::Equal { | |
311 | a_id.cmp(b_id) | |
312 | } else { | |
313 | type_order | |
314 | } | |
315 | }); | |
812c6f87 | 316 | |
34a816cc DM |
317 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); |
318 | ||
319 | let mut result = vec![]; | |
320 | ||
812c6f87 DM |
321 | for item in list { |
322 | ||
ad20d198 DM |
323 | let id = item["backup-id"].as_str().unwrap(); |
324 | let btype = item["backup-type"].as_str().unwrap(); | |
325 | let epoch = item["last-backup"].as_i64().unwrap(); | |
fa5d6977 | 326 | let last_backup = Utc.timestamp(epoch, 0); |
ad20d198 | 327 | let backup_count = item["backup-count"].as_u64().unwrap(); |
812c6f87 | 328 | |
1e9a94e5 | 329 | let group = BackupGroup::new(btype, id); |
812c6f87 DM |
330 | |
331 | let path = group.group_path().to_str().unwrap().to_owned(); | |
ad20d198 | 332 | |
52c171e4 DM |
333 | let files = item["files"].as_array().unwrap().iter() |
334 | .map(|v| strip_server_file_expenstion(v.as_str().unwrap())).collect(); | |
ad20d198 | 335 | |
34a816cc | 336 | if output_format == "text" { |
fa5d6977 DM |
337 | println!( |
338 | "{:20} | {} | {:5} | {}", | |
339 | path, | |
340 | BackupDir::backup_time_to_string(last_backup), | |
341 | backup_count, | |
342 | tools::join(&files, ' '), | |
343 | ); | |
34a816cc DM |
344 | } else { |
345 | result.push(json!({ | |
346 | "backup-type": btype, | |
347 | "backup-id": id, | |
348 | "last-backup": epoch, | |
349 | "backup-count": backup_count, | |
350 | "files": files, | |
351 | })); | |
352 | } | |
812c6f87 DM |
353 | } |
354 | ||
9aa3f682 | 355 | if output_format != "text" { format_and_print_result(&result.into(), &output_format); } |
34a816cc | 356 | |
812c6f87 DM |
357 | Ok(Value::Null) |
358 | } | |
359 | ||
a47a02ae DM |
360 | #[api( |
361 | input: { | |
362 | properties: { | |
363 | repository: { | |
364 | schema: REPO_URL_SCHEMA, | |
365 | optional: true, | |
366 | }, | |
367 | group: { | |
368 | type: String, | |
369 | description: "Backup group.", | |
370 | optional: true, | |
371 | }, | |
372 | "output-format": { | |
373 | schema: OUTPUT_FORMAT, | |
374 | optional: true, | |
375 | }, | |
376 | } | |
377 | } | |
378 | )] | |
379 | /// List backup snapshots. | |
380 | async fn list_snapshots(param: Value) -> Result<Value, Error> { | |
184f17af | 381 | |
2665cef7 | 382 | let repo = extract_repository_from_value(¶m)?; |
184f17af | 383 | |
34a816cc DM |
384 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); |
385 | ||
cc2ce4a9 | 386 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
184f17af | 387 | |
42af4b8f DM |
388 | let group = if let Some(path) = param["group"].as_str() { |
389 | Some(BackupGroup::parse(path)?) | |
390 | } else { | |
391 | None | |
392 | }; | |
184f17af | 393 | |
42af4b8f | 394 | let mut list = api_datastore_list_snapshots(&client, repo.store(), group).await?; |
15c847f1 | 395 | |
42af4b8f | 396 | list.sort_unstable_by(|a, b| a.backup_time.cmp(&b.backup_time)); |
184f17af | 397 | |
d0a03d40 DM |
398 | record_repository(&repo); |
399 | ||
af9d4afc | 400 | if output_format != "text" { |
42af4b8f | 401 | format_and_print_result(&serde_json::to_value(list)?, &output_format); |
af9d4afc DM |
402 | return Ok(Value::Null); |
403 | } | |
184f17af DM |
404 | |
405 | for item in list { | |
406 | ||
af9d4afc | 407 | let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time); |
184f17af DM |
408 | |
409 | let path = snapshot.relative_path().to_str().unwrap().to_owned(); | |
410 | ||
af9d4afc DM |
411 | let files = item.files.iter() |
412 | .map(|v| strip_server_file_expenstion(&v)) | |
413 | .collect(); | |
184f17af | 414 | |
af9d4afc DM |
415 | let size_str = if let Some(size) = item.size { |
416 | size.to_string() | |
34a816cc | 417 | } else { |
af9d4afc DM |
418 | String::from("-") |
419 | }; | |
420 | println!("{} | {} | {}", path, size_str, tools::join(&files, ' ')); | |
184f17af DM |
421 | } |
422 | ||
423 | Ok(Value::Null) | |
424 | } | |
425 | ||
a47a02ae DM |
426 | #[api( |
427 | input: { | |
428 | properties: { | |
429 | repository: { | |
430 | schema: REPO_URL_SCHEMA, | |
431 | optional: true, | |
432 | }, | |
433 | snapshot: { | |
434 | type: String, | |
435 | description: "Snapshot path.", | |
436 | }, | |
437 | } | |
438 | } | |
439 | )] | |
440 | /// Forget (remove) backup snapshots. | |
441 | async fn forget_snapshots(param: Value) -> Result<Value, Error> { | |
6f62c924 | 442 | |
2665cef7 | 443 | let repo = extract_repository_from_value(¶m)?; |
6f62c924 DM |
444 | |
445 | let path = tools::required_string_param(¶m, "snapshot")?; | |
446 | let snapshot = BackupDir::parse(path)?; | |
447 | ||
cc2ce4a9 | 448 | let mut client = HttpClient::new(repo.host(), repo.user(), None)?; |
6f62c924 | 449 | |
9e391bb7 | 450 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
6f62c924 | 451 | |
8a8a4703 DM |
452 | let result = client.delete(&path, Some(json!({ |
453 | "backup-type": snapshot.group().backup_type(), | |
454 | "backup-id": snapshot.group().backup_id(), | |
455 | "backup-time": snapshot.backup_time().timestamp(), | |
456 | }))).await?; | |
6f62c924 | 457 | |
d0a03d40 DM |
458 | record_repository(&repo); |
459 | ||
6f62c924 DM |
460 | Ok(result) |
461 | } | |
462 | ||
a47a02ae DM |
463 | #[api( |
464 | input: { | |
465 | properties: { | |
466 | repository: { | |
467 | schema: REPO_URL_SCHEMA, | |
468 | optional: true, | |
469 | }, | |
470 | } | |
471 | } | |
472 | )] | |
473 | /// Try to login. If successful, store ticket. | |
474 | async fn api_login(param: Value) -> Result<Value, Error> { | |
e240d8be DM |
475 | |
476 | let repo = extract_repository_from_value(¶m)?; | |
477 | ||
cc2ce4a9 | 478 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
8a8a4703 | 479 | client.login().await?; |
e240d8be DM |
480 | |
481 | record_repository(&repo); | |
482 | ||
483 | Ok(Value::Null) | |
484 | } | |
485 | ||
a47a02ae DM |
486 | #[api( |
487 | input: { | |
488 | properties: { | |
489 | repository: { | |
490 | schema: REPO_URL_SCHEMA, | |
491 | optional: true, | |
492 | }, | |
493 | } | |
494 | } | |
495 | )] | |
496 | /// Logout (delete stored ticket). | |
497 | fn api_logout(param: Value) -> Result<Value, Error> { | |
e240d8be DM |
498 | |
499 | let repo = extract_repository_from_value(¶m)?; | |
500 | ||
501 | delete_ticket_info(repo.host(), repo.user())?; | |
502 | ||
503 | Ok(Value::Null) | |
504 | } | |
505 | ||
a47a02ae DM |
506 | #[api( |
507 | input: { | |
508 | properties: { | |
509 | repository: { | |
510 | schema: REPO_URL_SCHEMA, | |
511 | optional: true, | |
512 | }, | |
513 | snapshot: { | |
514 | type: String, | |
515 | description: "Snapshot path.", | |
516 | }, | |
517 | } | |
518 | } | |
519 | )] | |
520 | /// Dump catalog. | |
521 | async fn dump_catalog(param: Value) -> Result<Value, Error> { | |
9049a8cf DM |
522 | |
523 | let repo = extract_repository_from_value(¶m)?; | |
524 | ||
525 | let path = tools::required_string_param(¶m, "snapshot")?; | |
526 | let snapshot = BackupDir::parse(path)?; | |
527 | ||
11377a47 | 528 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); |
9049a8cf DM |
529 | |
530 | let crypt_config = match keyfile { | |
531 | None => None, | |
532 | Some(path) => { | |
a8f10f84 | 533 | let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
9025312a | 534 | Some(Arc::new(CryptConfig::new(key)?)) |
9049a8cf DM |
535 | } |
536 | }; | |
537 | ||
cc2ce4a9 | 538 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
9049a8cf | 539 | |
8a8a4703 DM |
540 | let client = BackupReader::start( |
541 | client, | |
542 | crypt_config.clone(), | |
543 | repo.store(), | |
544 | &snapshot.group().backup_type(), | |
545 | &snapshot.group().backup_id(), | |
546 | snapshot.backup_time(), | |
547 | true, | |
548 | ).await?; | |
9049a8cf | 549 | |
8a8a4703 | 550 | let manifest = client.download_manifest().await?; |
d2267b11 | 551 | |
8a8a4703 | 552 | let index = client.download_dynamic_index(&manifest, CATALOG_NAME).await?; |
bf6e3217 | 553 | |
8a8a4703 | 554 | let most_used = index.find_most_used_chunks(8); |
bf6e3217 | 555 | |
8a8a4703 | 556 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); |
bf6e3217 | 557 | |
8a8a4703 | 558 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); |
9049a8cf | 559 | |
8a8a4703 DM |
560 | let mut catalogfile = std::fs::OpenOptions::new() |
561 | .write(true) | |
562 | .read(true) | |
563 | .custom_flags(libc::O_TMPFILE) | |
564 | .open("/tmp")?; | |
d2267b11 | 565 | |
8a8a4703 DM |
566 | std::io::copy(&mut reader, &mut catalogfile) |
567 | .map_err(|err| format_err!("unable to download catalog - {}", err))?; | |
a84ef4c2 | 568 | |
8a8a4703 | 569 | catalogfile.seek(SeekFrom::Start(0))?; |
9049a8cf | 570 | |
8a8a4703 | 571 | let mut catalog_reader = CatalogReader::new(catalogfile); |
9049a8cf | 572 | |
8a8a4703 | 573 | catalog_reader.dump()?; |
e9722f8b | 574 | |
8a8a4703 | 575 | record_repository(&repo); |
9049a8cf DM |
576 | |
577 | Ok(Value::Null) | |
578 | } | |
579 | ||
a47a02ae DM |
580 | #[api( |
581 | input: { | |
582 | properties: { | |
583 | repository: { | |
584 | schema: REPO_URL_SCHEMA, | |
585 | optional: true, | |
586 | }, | |
587 | snapshot: { | |
588 | type: String, | |
589 | description: "Snapshot path.", | |
590 | }, | |
591 | "output-format": { | |
592 | schema: OUTPUT_FORMAT, | |
593 | optional: true, | |
594 | }, | |
595 | } | |
596 | } | |
597 | )] | |
598 | /// List snapshot files. | |
599 | async fn list_snapshot_files(param: Value) -> Result<Value, Error> { | |
52c171e4 DM |
600 | |
601 | let repo = extract_repository_from_value(¶m)?; | |
602 | ||
603 | let path = tools::required_string_param(¶m, "snapshot")?; | |
604 | let snapshot = BackupDir::parse(path)?; | |
605 | ||
606 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); | |
607 | ||
cc2ce4a9 | 608 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
52c171e4 DM |
609 | |
610 | let path = format!("api2/json/admin/datastore/{}/files", repo.store()); | |
611 | ||
8a8a4703 DM |
612 | let mut result = client.get(&path, Some(json!({ |
613 | "backup-type": snapshot.group().backup_type(), | |
614 | "backup-id": snapshot.group().backup_id(), | |
615 | "backup-time": snapshot.backup_time().timestamp(), | |
616 | }))).await?; | |
52c171e4 DM |
617 | |
618 | record_repository(&repo); | |
619 | ||
8c70e3eb | 620 | let list: Value = result["data"].take(); |
52c171e4 DM |
621 | |
622 | if output_format == "text" { | |
8c70e3eb DM |
623 | for item in list.as_array().unwrap().iter() { |
624 | println!( | |
625 | "{} {}", | |
626 | strip_server_file_expenstion(item["filename"].as_str().unwrap()), | |
627 | item["size"].as_u64().unwrap_or(0), | |
628 | ); | |
52c171e4 DM |
629 | } |
630 | } else { | |
8c70e3eb | 631 | format_and_print_result(&list, &output_format); |
52c171e4 DM |
632 | } |
633 | ||
634 | Ok(Value::Null) | |
635 | } | |
636 | ||
a47a02ae | 637 | #[api( |
94913f35 | 638 | input: { |
a47a02ae DM |
639 | properties: { |
640 | repository: { | |
641 | schema: REPO_URL_SCHEMA, | |
642 | optional: true, | |
643 | }, | |
94913f35 DM |
644 | "output-format": { |
645 | schema: OUTPUT_FORMAT, | |
646 | optional: true, | |
647 | }, | |
648 | }, | |
649 | }, | |
a47a02ae DM |
650 | )] |
651 | /// Start garbage collection for a specific repository. | |
652 | async fn start_garbage_collection(param: Value) -> Result<Value, Error> { | |
8cc0d6af | 653 | |
2665cef7 | 654 | let repo = extract_repository_from_value(¶m)?; |
e5f7def4 | 655 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); |
8cc0d6af | 656 | |
cc2ce4a9 | 657 | let mut client = HttpClient::new(repo.host(), repo.user(), None)?; |
8cc0d6af | 658 | |
d0a03d40 | 659 | let path = format!("api2/json/admin/datastore/{}/gc", repo.store()); |
8cc0d6af | 660 | |
8a8a4703 | 661 | let result = client.post(&path, None).await?; |
8cc0d6af | 662 | |
8a8a4703 | 663 | record_repository(&repo); |
d0a03d40 | 664 | |
8a8a4703 | 665 | view_task_result(client, result, &output_format).await?; |
e5f7def4 | 666 | |
e5f7def4 | 667 | Ok(Value::Null) |
8cc0d6af | 668 | } |
33d64b81 | 669 | |
ae0be2dd DM |
670 | fn parse_backupspec(value: &str) -> Result<(&str, &str), Error> { |
671 | ||
255f378a | 672 | if let Some(caps) = (BACKUPSPEC_REGEX.regex_obj)().captures(value) { |
ae0be2dd DM |
673 | return Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str())); |
674 | } | |
675 | bail!("unable to parse directory specification '{}'", value); | |
676 | } | |
677 | ||
bf6e3217 DM |
678 | fn spawn_catalog_upload( |
679 | client: Arc<BackupWriter>, | |
680 | crypt_config: Option<Arc<CryptConfig>>, | |
681 | ) -> Result< | |
682 | ( | |
683 | Arc<Mutex<CatalogWriter<SenderWriter>>>, | |
684 | tokio::sync::oneshot::Receiver<Result<BackupStats, Error>> | |
685 | ), Error> | |
686 | { | |
687 | let (catalog_tx, catalog_rx) = mpsc::channel(10); // allow to buffer 10 writes | |
688 | let catalog_stream = catalog_rx.map_err(Error::from); | |
689 | let catalog_chunk_size = 512*1024; | |
690 | let catalog_chunk_stream = ChunkStream::new(catalog_stream, Some(catalog_chunk_size)); | |
691 | ||
692 | let catalog = Arc::new(Mutex::new(CatalogWriter::new(SenderWriter::new(catalog_tx))?)); | |
693 | ||
694 | let (catalog_result_tx, catalog_result_rx) = tokio::sync::oneshot::channel(); | |
695 | ||
696 | tokio::spawn(async move { | |
697 | let catalog_upload_result = client | |
698 | .upload_stream(CATALOG_NAME, catalog_chunk_stream, "dynamic", None, crypt_config) | |
699 | .await; | |
700 | ||
701 | if let Err(ref err) = catalog_upload_result { | |
702 | eprintln!("catalog upload error - {}", err); | |
703 | client.cancel(); | |
704 | } | |
705 | ||
706 | let _ = catalog_result_tx.send(catalog_upload_result); | |
707 | }); | |
708 | ||
709 | Ok((catalog, catalog_result_rx)) | |
710 | } | |
711 | ||
a47a02ae DM |
712 | #[api( |
713 | input: { | |
714 | properties: { | |
715 | backupspec: { | |
716 | type: Array, | |
717 | description: "List of backup source specifications ([<label.ext>:<path>] ...)", | |
718 | items: { | |
719 | schema: BACKUP_SOURCE_SCHEMA, | |
720 | } | |
721 | }, | |
722 | repository: { | |
723 | schema: REPO_URL_SCHEMA, | |
724 | optional: true, | |
725 | }, | |
726 | "include-dev": { | |
727 | description: "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.", | |
728 | optional: true, | |
729 | items: { | |
730 | type: String, | |
731 | description: "Path to file.", | |
732 | } | |
733 | }, | |
734 | keyfile: { | |
735 | schema: KEYFILE_SCHEMA, | |
736 | optional: true, | |
737 | }, | |
738 | "skip-lost-and-found": { | |
739 | type: Boolean, | |
740 | description: "Skip lost+found directory.", | |
741 | optional: true, | |
742 | }, | |
743 | "backup-type": { | |
744 | schema: BACKUP_TYPE_SCHEMA, | |
745 | optional: true, | |
746 | }, | |
747 | "backup-id": { | |
748 | schema: BACKUP_ID_SCHEMA, | |
749 | optional: true, | |
750 | }, | |
751 | "backup-time": { | |
752 | schema: BACKUP_TIME_SCHEMA, | |
753 | optional: true, | |
754 | }, | |
755 | "chunk-size": { | |
756 | schema: CHUNK_SIZE_SCHEMA, | |
757 | optional: true, | |
758 | }, | |
759 | } | |
760 | } | |
761 | )] | |
762 | /// Create (host) backup. | |
763 | async fn create_backup( | |
6049b71f DM |
764 | param: Value, |
765 | _info: &ApiMethod, | |
dd5495d6 | 766 | _rpcenv: &mut dyn RpcEnvironment, |
6049b71f | 767 | ) -> Result<Value, Error> { |
ff5d3707 | 768 | |
2665cef7 | 769 | let repo = extract_repository_from_value(¶m)?; |
ae0be2dd DM |
770 | |
771 | let backupspec_list = tools::required_array_param(¶m, "backupspec")?; | |
a914a774 | 772 | |
eed6db39 DM |
773 | let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false); |
774 | ||
5b72c9b4 DM |
775 | let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false); |
776 | ||
219ef0e6 DM |
777 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
778 | ||
ca5d0b61 DM |
779 | let backup_time_opt = param["backup-time"].as_i64(); |
780 | ||
36898ffc | 781 | let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize); |
2d9d143a | 782 | |
247cdbce DM |
783 | if let Some(size) = chunk_size_opt { |
784 | verify_chunk_size(size)?; | |
2d9d143a DM |
785 | } |
786 | ||
11377a47 | 787 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); |
6d0983db | 788 | |
f69adc81 | 789 | let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename()); |
fba30411 | 790 | |
bbf9e7e9 | 791 | let backup_type = param["backup-type"].as_str().unwrap_or("host"); |
ca5d0b61 | 792 | |
2eeaacb9 DM |
793 | let include_dev = param["include-dev"].as_array(); |
794 | ||
795 | let mut devices = if all_file_systems { None } else { Some(HashSet::new()) }; | |
796 | ||
797 | if let Some(include_dev) = include_dev { | |
798 | if all_file_systems { | |
799 | bail!("option 'all-file-systems' conflicts with option 'include-dev'"); | |
800 | } | |
801 | ||
802 | let mut set = HashSet::new(); | |
803 | for path in include_dev { | |
804 | let path = path.as_str().unwrap(); | |
805 | let stat = nix::sys::stat::stat(path) | |
806 | .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?; | |
807 | set.insert(stat.st_dev); | |
808 | } | |
809 | devices = Some(set); | |
810 | } | |
811 | ||
ae0be2dd | 812 | let mut upload_list = vec![]; |
a914a774 | 813 | |
79679c2d | 814 | enum BackupType { PXAR, IMAGE, CONFIG, LOGFILE }; |
6af905c1 | 815 | |
bf6e3217 DM |
816 | let mut upload_catalog = false; |
817 | ||
ae0be2dd DM |
818 | for backupspec in backupspec_list { |
819 | let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?; | |
bcd879cf | 820 | |
eb1804c5 DM |
821 | use std::os::unix::fs::FileTypeExt; |
822 | ||
3fa71727 CE |
823 | let metadata = std::fs::metadata(filename) |
824 | .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?; | |
eb1804c5 | 825 | let file_type = metadata.file_type(); |
23bb8780 | 826 | |
4af0ee05 | 827 | let extension = target.rsplit('.').next() |
11377a47 | 828 | .ok_or_else(|| format_err!("missing target file extenion '{}'", target))?; |
bcd879cf | 829 | |
ec8a9bb9 DM |
830 | match extension { |
831 | "pxar" => { | |
832 | if !file_type.is_dir() { | |
833 | bail!("got unexpected file type (expected directory)"); | |
834 | } | |
4af0ee05 | 835 | upload_list.push((BackupType::PXAR, filename.to_owned(), format!("{}.didx", target), 0)); |
bf6e3217 | 836 | upload_catalog = true; |
ec8a9bb9 DM |
837 | } |
838 | "img" => { | |
eb1804c5 | 839 | |
ec8a9bb9 DM |
840 | if !(file_type.is_file() || file_type.is_block_device()) { |
841 | bail!("got unexpected file type (expected file or block device)"); | |
842 | } | |
eb1804c5 | 843 | |
e18a6c9e | 844 | let size = image_size(&PathBuf::from(filename))?; |
23bb8780 | 845 | |
ec8a9bb9 | 846 | if size == 0 { bail!("got zero-sized file '{}'", filename); } |
ae0be2dd | 847 | |
4af0ee05 | 848 | upload_list.push((BackupType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size)); |
ec8a9bb9 DM |
849 | } |
850 | "conf" => { | |
851 | if !file_type.is_file() { | |
852 | bail!("got unexpected file type (expected regular file)"); | |
853 | } | |
4af0ee05 | 854 | upload_list.push((BackupType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len())); |
ec8a9bb9 | 855 | } |
79679c2d DM |
856 | "log" => { |
857 | if !file_type.is_file() { | |
858 | bail!("got unexpected file type (expected regular file)"); | |
859 | } | |
4af0ee05 | 860 | upload_list.push((BackupType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len())); |
79679c2d | 861 | } |
ec8a9bb9 DM |
862 | _ => { |
863 | bail!("got unknown archive extension '{}'", extension); | |
864 | } | |
ae0be2dd DM |
865 | } |
866 | } | |
867 | ||
11377a47 | 868 | let backup_time = Utc.timestamp(backup_time_opt.unwrap_or_else(|| Utc::now().timestamp()), 0); |
ae0be2dd | 869 | |
cc2ce4a9 | 870 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
d0a03d40 DM |
871 | record_repository(&repo); |
872 | ||
ca5d0b61 DM |
873 | println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time)); |
874 | ||
f69adc81 | 875 | println!("Client name: {}", proxmox::tools::nodename()); |
ca5d0b61 DM |
876 | |
877 | let start_time = Local::now(); | |
878 | ||
7a6cfbd9 | 879 | println!("Starting protocol: {}", start_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false)); |
51144821 | 880 | |
bb823140 DM |
881 | let (crypt_config, rsa_encrypted_key) = match keyfile { |
882 | None => (None, None), | |
6d0983db | 883 | Some(path) => { |
a8f10f84 | 884 | let (key, created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
bb823140 DM |
885 | |
886 | let crypt_config = CryptConfig::new(key)?; | |
887 | ||
888 | let path = master_pubkey_path()?; | |
889 | if path.exists() { | |
e18a6c9e | 890 | let pem_data = file_get_contents(&path)?; |
bb823140 DM |
891 | let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?; |
892 | let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?; | |
893 | (Some(Arc::new(crypt_config)), Some(enc_key)) | |
894 | } else { | |
895 | (Some(Arc::new(crypt_config)), None) | |
896 | } | |
6d0983db DM |
897 | } |
898 | }; | |
f98ac774 | 899 | |
8a8a4703 DM |
900 | let client = BackupWriter::start( |
901 | client, | |
902 | repo.store(), | |
903 | backup_type, | |
904 | &backup_id, | |
905 | backup_time, | |
906 | verbose, | |
907 | ).await?; | |
908 | ||
909 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time.timestamp()); | |
910 | let mut manifest = BackupManifest::new(snapshot); | |
911 | ||
912 | let (catalog, catalog_result_rx) = spawn_catalog_upload(client.clone(), crypt_config.clone())?; | |
913 | ||
914 | for (backup_type, filename, target, size) in upload_list { | |
915 | match backup_type { | |
916 | BackupType::CONFIG => { | |
917 | println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target); | |
918 | let stats = client | |
919 | .upload_blob_from_file(&filename, &target, crypt_config.clone(), true) | |
920 | .await?; | |
1e8da0a7 | 921 | manifest.add_file(target, stats.size, stats.csum)?; |
8a8a4703 DM |
922 | } |
923 | BackupType::LOGFILE => { // fixme: remove - not needed anymore ? | |
924 | println!("Upload log file '{}' to '{:?}' as {}", filename, repo, target); | |
925 | let stats = client | |
926 | .upload_blob_from_file(&filename, &target, crypt_config.clone(), true) | |
927 | .await?; | |
1e8da0a7 | 928 | manifest.add_file(target, stats.size, stats.csum)?; |
8a8a4703 DM |
929 | } |
930 | BackupType::PXAR => { | |
931 | println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target); | |
932 | catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?; | |
933 | let stats = backup_directory( | |
934 | &client, | |
935 | &filename, | |
936 | &target, | |
937 | chunk_size_opt, | |
938 | devices.clone(), | |
939 | verbose, | |
940 | skip_lost_and_found, | |
941 | crypt_config.clone(), | |
942 | catalog.clone(), | |
943 | ).await?; | |
1e8da0a7 | 944 | manifest.add_file(target, stats.size, stats.csum)?; |
8a8a4703 DM |
945 | catalog.lock().unwrap().end_directory()?; |
946 | } | |
947 | BackupType::IMAGE => { | |
948 | println!("Upload image '{}' to '{:?}' as {}", filename, repo, target); | |
949 | let stats = backup_image( | |
950 | &client, | |
951 | &filename, | |
952 | &target, | |
953 | size, | |
954 | chunk_size_opt, | |
955 | verbose, | |
956 | crypt_config.clone(), | |
957 | ).await?; | |
1e8da0a7 | 958 | manifest.add_file(target, stats.size, stats.csum)?; |
6af905c1 DM |
959 | } |
960 | } | |
8a8a4703 | 961 | } |
4818c8b6 | 962 | |
8a8a4703 DM |
963 | // finalize and upload catalog |
964 | if upload_catalog { | |
965 | let mutex = Arc::try_unwrap(catalog) | |
966 | .map_err(|_| format_err!("unable to get catalog (still used)"))?; | |
967 | let mut catalog = mutex.into_inner().unwrap(); | |
bf6e3217 | 968 | |
8a8a4703 | 969 | catalog.finish()?; |
2761d6a4 | 970 | |
8a8a4703 | 971 | drop(catalog); // close upload stream |
2761d6a4 | 972 | |
8a8a4703 | 973 | let stats = catalog_result_rx.await??; |
9d135fe6 | 974 | |
1e8da0a7 | 975 | manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum)?; |
8a8a4703 | 976 | } |
2761d6a4 | 977 | |
8a8a4703 DM |
978 | if let Some(rsa_encrypted_key) = rsa_encrypted_key { |
979 | let target = "rsa-encrypted.key"; | |
980 | println!("Upload RSA encoded key to '{:?}' as {}", repo, target); | |
981 | let stats = client | |
982 | .upload_blob_from_data(rsa_encrypted_key, target, None, false, false) | |
983 | .await?; | |
1e8da0a7 | 984 | manifest.add_file(format!("{}.blob", target), stats.size, stats.csum)?; |
8a8a4703 DM |
985 | |
986 | // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t | |
987 | /* | |
988 | let mut buffer2 = vec![0u8; rsa.size() as usize]; | |
989 | let pem_data = file_get_contents("master-private.pem")?; | |
990 | let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?; | |
991 | let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?; | |
992 | println!("TEST {} {:?}", len, buffer2); | |
993 | */ | |
994 | } | |
9f46c7de | 995 | |
8a8a4703 DM |
996 | // create manifest (index.json) |
997 | let manifest = manifest.into_json(); | |
2c3891d1 | 998 | |
8a8a4703 DM |
999 | println!("Upload index.json to '{:?}'", repo); |
1000 | let manifest = serde_json::to_string_pretty(&manifest)?.into(); | |
1001 | client | |
1002 | .upload_blob_from_data(manifest, MANIFEST_BLOB_NAME, crypt_config.clone(), true, true) | |
1003 | .await?; | |
2c3891d1 | 1004 | |
8a8a4703 | 1005 | client.finish().await?; |
c4ff3dce | 1006 | |
8a8a4703 DM |
1007 | let end_time = Local::now(); |
1008 | let elapsed = end_time.signed_duration_since(start_time); | |
1009 | println!("Duration: {}", elapsed); | |
3ec3ec3f | 1010 | |
8a8a4703 | 1011 | println!("End Time: {}", end_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false)); |
3d5c11e5 | 1012 | |
8a8a4703 | 1013 | Ok(Value::Null) |
f98ea63d DM |
1014 | } |
1015 | ||
d0a03d40 | 1016 | fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
f98ea63d DM |
1017 | |
1018 | let mut result = vec![]; | |
1019 | ||
1020 | let data: Vec<&str> = arg.splitn(2, ':').collect(); | |
1021 | ||
bff11030 | 1022 | if data.len() != 2 { |
8968258b DM |
1023 | result.push(String::from("root.pxar:/")); |
1024 | result.push(String::from("etc.pxar:/etc")); | |
bff11030 DM |
1025 | return result; |
1026 | } | |
f98ea63d | 1027 | |
496a6784 | 1028 | let files = tools::complete_file_name(data[1], param); |
f98ea63d DM |
1029 | |
1030 | for file in files { | |
1031 | result.push(format!("{}:{}", data[0], file)); | |
1032 | } | |
1033 | ||
1034 | result | |
ff5d3707 | 1035 | } |
1036 | ||
88892ea8 DM |
1037 | fn dump_image<W: Write>( |
1038 | client: Arc<BackupReader>, | |
1039 | crypt_config: Option<Arc<CryptConfig>>, | |
1040 | index: FixedIndexReader, | |
1041 | mut writer: W, | |
fd04ca7a | 1042 | verbose: bool, |
88892ea8 DM |
1043 | ) -> Result<(), Error> { |
1044 | ||
1045 | let most_used = index.find_most_used_chunks(8); | |
1046 | ||
1047 | let mut chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
1048 | ||
1049 | // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy | |
1050 | // and thus slows down reading. Instead, directly use RemoteChunkReader | |
fd04ca7a DM |
1051 | let mut per = 0; |
1052 | let mut bytes = 0; | |
1053 | let start_time = std::time::Instant::now(); | |
1054 | ||
88892ea8 DM |
1055 | for pos in 0..index.index_count() { |
1056 | let digest = index.index_digest(pos).unwrap(); | |
1057 | let raw_data = chunk_reader.read_chunk(&digest)?; | |
1058 | writer.write_all(&raw_data)?; | |
fd04ca7a DM |
1059 | bytes += raw_data.len(); |
1060 | if verbose { | |
1061 | let next_per = ((pos+1)*100)/index.index_count(); | |
1062 | if per != next_per { | |
1063 | eprintln!("progress {}% (read {} bytes, duration {} sec)", | |
1064 | next_per, bytes, start_time.elapsed().as_secs()); | |
1065 | per = next_per; | |
1066 | } | |
1067 | } | |
88892ea8 DM |
1068 | } |
1069 | ||
fd04ca7a DM |
1070 | let end_time = std::time::Instant::now(); |
1071 | let elapsed = end_time.duration_since(start_time); | |
1072 | eprintln!("restore image complete (bytes={}, duration={:.2}s, speed={:.2}MB/s)", | |
1073 | bytes, | |
1074 | elapsed.as_secs_f64(), | |
1075 | bytes as f64/(1024.0*1024.0*elapsed.as_secs_f64()) | |
1076 | ); | |
1077 | ||
1078 | ||
88892ea8 DM |
1079 | Ok(()) |
1080 | } | |
1081 | ||
a47a02ae DM |
1082 | #[api( |
1083 | input: { | |
1084 | properties: { | |
1085 | repository: { | |
1086 | schema: REPO_URL_SCHEMA, | |
1087 | optional: true, | |
1088 | }, | |
1089 | snapshot: { | |
1090 | type: String, | |
1091 | description: "Group/Snapshot path.", | |
1092 | }, | |
1093 | "archive-name": { | |
1094 | description: "Backup archive name.", | |
1095 | type: String, | |
1096 | }, | |
1097 | target: { | |
1098 | type: String, | |
1099 | description: r###"Target directory path. Use '-' to write to stdandard output. | |
8a8a4703 | 1100 | |
a47a02ae | 1101 | We do not extraxt '.pxar' archives when writing to stdandard output. |
8a8a4703 | 1102 | |
a47a02ae DM |
1103 | "### |
1104 | }, | |
1105 | "allow-existing-dirs": { | |
1106 | type: Boolean, | |
1107 | description: "Do not fail if directories already exists.", | |
1108 | optional: true, | |
1109 | }, | |
1110 | keyfile: { | |
1111 | schema: KEYFILE_SCHEMA, | |
1112 | optional: true, | |
1113 | }, | |
1114 | } | |
1115 | } | |
1116 | )] | |
1117 | /// Restore backup repository. | |
1118 | async fn restore(param: Value) -> Result<Value, Error> { | |
2665cef7 | 1119 | let repo = extract_repository_from_value(¶m)?; |
9f912493 | 1120 | |
86eda3eb DM |
1121 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
1122 | ||
46d5aa0a DM |
1123 | let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false); |
1124 | ||
d5c34d98 DM |
1125 | let archive_name = tools::required_string_param(¶m, "archive-name")?; |
1126 | ||
cc2ce4a9 | 1127 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
d0a03d40 | 1128 | |
d0a03d40 | 1129 | record_repository(&repo); |
d5c34d98 | 1130 | |
9f912493 | 1131 | let path = tools::required_string_param(¶m, "snapshot")?; |
9f912493 | 1132 | |
86eda3eb | 1133 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { |
d5c34d98 | 1134 | let group = BackupGroup::parse(path)?; |
9f912493 | 1135 | |
42af4b8f | 1136 | let mut list = api_datastore_list_snapshots(&client, repo.store(), Some(group.clone())).await?; |
9f912493 | 1137 | |
11377a47 | 1138 | if list.is_empty() { |
d5c34d98 DM |
1139 | bail!("backup group '{}' does not contain any snapshots:", path); |
1140 | } | |
af9d4afc DM |
1141 | list.sort_unstable_by(|a, b| b.backup_time.cmp(&a.backup_time)); |
1142 | ||
1143 | let backup_time = Utc.timestamp(list[0].backup_time, 0); | |
9f912493 | 1144 | |
86eda3eb | 1145 | (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time) |
d5c34d98 DM |
1146 | } else { |
1147 | let snapshot = BackupDir::parse(path)?; | |
86eda3eb DM |
1148 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) |
1149 | }; | |
9f912493 | 1150 | |
d5c34d98 | 1151 | let target = tools::required_string_param(¶m, "target")?; |
bf125261 | 1152 | let target = if target == "-" { None } else { Some(target) }; |
2ae7d196 | 1153 | |
11377a47 | 1154 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); |
2ae7d196 | 1155 | |
86eda3eb DM |
1156 | let crypt_config = match keyfile { |
1157 | None => None, | |
1158 | Some(path) => { | |
a8f10f84 | 1159 | let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
86eda3eb DM |
1160 | Some(Arc::new(CryptConfig::new(key)?)) |
1161 | } | |
1162 | }; | |
d5c34d98 | 1163 | |
afb4cd28 DM |
1164 | let server_archive_name = if archive_name.ends_with(".pxar") { |
1165 | format!("{}.didx", archive_name) | |
1166 | } else if archive_name.ends_with(".img") { | |
1167 | format!("{}.fidx", archive_name) | |
1168 | } else { | |
f8100e96 | 1169 | format!("{}.blob", archive_name) |
afb4cd28 | 1170 | }; |
9f912493 | 1171 | |
296c50ba DM |
1172 | let client = BackupReader::start( |
1173 | client, | |
1174 | crypt_config.clone(), | |
1175 | repo.store(), | |
1176 | &backup_type, | |
1177 | &backup_id, | |
1178 | backup_time, | |
1179 | true, | |
1180 | ).await?; | |
86eda3eb | 1181 | |
f06b820a | 1182 | let manifest = client.download_manifest().await?; |
02fcf372 | 1183 | |
ad6e5a6f | 1184 | if server_archive_name == MANIFEST_BLOB_NAME { |
f06b820a | 1185 | let backup_index_data = manifest.into_json().to_string(); |
02fcf372 | 1186 | if let Some(target) = target { |
feaa1ad3 | 1187 | replace_file(target, backup_index_data.as_bytes(), CreateOptions::new())?; |
02fcf372 DM |
1188 | } else { |
1189 | let stdout = std::io::stdout(); | |
1190 | let mut writer = stdout.lock(); | |
296c50ba | 1191 | writer.write_all(backup_index_data.as_bytes()) |
02fcf372 DM |
1192 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1193 | } | |
1194 | ||
1195 | } else if server_archive_name.ends_with(".blob") { | |
d2267b11 | 1196 | |
bb19af73 | 1197 | let mut reader = client.download_blob(&manifest, &server_archive_name).await?; |
f8100e96 | 1198 | |
bf125261 | 1199 | if let Some(target) = target { |
0d986280 DM |
1200 | let mut writer = std::fs::OpenOptions::new() |
1201 | .write(true) | |
1202 | .create(true) | |
1203 | .create_new(true) | |
1204 | .open(target) | |
1205 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?; | |
1206 | std::io::copy(&mut reader, &mut writer)?; | |
bf125261 DM |
1207 | } else { |
1208 | let stdout = std::io::stdout(); | |
1209 | let mut writer = stdout.lock(); | |
0d986280 | 1210 | std::io::copy(&mut reader, &mut writer) |
bf125261 DM |
1211 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1212 | } | |
f8100e96 DM |
1213 | |
1214 | } else if server_archive_name.ends_with(".didx") { | |
86eda3eb | 1215 | |
c3d84a22 | 1216 | let index = client.download_dynamic_index(&manifest, &server_archive_name).await?; |
df65bd3d | 1217 | |
f4bf7dfc DM |
1218 | let most_used = index.find_most_used_chunks(8); |
1219 | ||
1220 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
1221 | ||
afb4cd28 | 1222 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); |
86eda3eb | 1223 | |
bf125261 | 1224 | if let Some(target) = target { |
86eda3eb | 1225 | |
47651f95 | 1226 | let feature_flags = pxar::flags::DEFAULT; |
f701d033 DM |
1227 | let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags); |
1228 | decoder.set_callback(move |path| { | |
bf125261 | 1229 | if verbose { |
fd04ca7a | 1230 | eprintln!("{:?}", path); |
bf125261 DM |
1231 | } |
1232 | Ok(()) | |
1233 | }); | |
6a879109 CE |
1234 | decoder.set_allow_existing_dirs(allow_existing_dirs); |
1235 | ||
fa7e957c | 1236 | decoder.restore(Path::new(target), &Vec::new())?; |
bf125261 | 1237 | } else { |
88892ea8 DM |
1238 | let mut writer = std::fs::OpenOptions::new() |
1239 | .write(true) | |
1240 | .open("/dev/stdout") | |
1241 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?; | |
afb4cd28 | 1242 | |
bf125261 DM |
1243 | std::io::copy(&mut reader, &mut writer) |
1244 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
1245 | } | |
afb4cd28 | 1246 | } else if server_archive_name.ends_with(".fidx") { |
afb4cd28 | 1247 | |
72050500 | 1248 | let index = client.download_fixed_index(&manifest, &server_archive_name).await?; |
df65bd3d | 1249 | |
88892ea8 DM |
1250 | let mut writer = if let Some(target) = target { |
1251 | std::fs::OpenOptions::new() | |
bf125261 DM |
1252 | .write(true) |
1253 | .create(true) | |
1254 | .create_new(true) | |
1255 | .open(target) | |
88892ea8 | 1256 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))? |
bf125261 | 1257 | } else { |
88892ea8 DM |
1258 | std::fs::OpenOptions::new() |
1259 | .write(true) | |
1260 | .open("/dev/stdout") | |
1261 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))? | |
1262 | }; | |
afb4cd28 | 1263 | |
fd04ca7a | 1264 | dump_image(client.clone(), crypt_config.clone(), index, &mut writer, verbose)?; |
88892ea8 DM |
1265 | |
1266 | } else { | |
f8100e96 | 1267 | bail!("unknown archive file extension (expected .pxar of .img)"); |
3031e44c | 1268 | } |
fef44d4f DM |
1269 | |
1270 | Ok(Value::Null) | |
45db6f89 DM |
1271 | } |
1272 | ||
a47a02ae DM |
1273 | #[api( |
1274 | input: { | |
1275 | properties: { | |
1276 | repository: { | |
1277 | schema: REPO_URL_SCHEMA, | |
1278 | optional: true, | |
1279 | }, | |
1280 | snapshot: { | |
1281 | type: String, | |
1282 | description: "Group/Snapshot path.", | |
1283 | }, | |
1284 | logfile: { | |
1285 | type: String, | |
1286 | description: "The path to the log file you want to upload.", | |
1287 | }, | |
1288 | keyfile: { | |
1289 | schema: KEYFILE_SCHEMA, | |
1290 | optional: true, | |
1291 | }, | |
1292 | } | |
1293 | } | |
1294 | )] | |
1295 | /// Upload backup log file. | |
1296 | async fn upload_log(param: Value) -> Result<Value, Error> { | |
ec34f7eb DM |
1297 | |
1298 | let logfile = tools::required_string_param(¶m, "logfile")?; | |
1299 | let repo = extract_repository_from_value(¶m)?; | |
1300 | ||
1301 | let snapshot = tools::required_string_param(¶m, "snapshot")?; | |
1302 | let snapshot = BackupDir::parse(snapshot)?; | |
1303 | ||
cc2ce4a9 | 1304 | let mut client = HttpClient::new(repo.host(), repo.user(), None)?; |
ec34f7eb | 1305 | |
11377a47 | 1306 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); |
ec34f7eb DM |
1307 | |
1308 | let crypt_config = match keyfile { | |
1309 | None => None, | |
1310 | Some(path) => { | |
a8f10f84 | 1311 | let (key, _created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
ec34f7eb | 1312 | let crypt_config = CryptConfig::new(key)?; |
9025312a | 1313 | Some(Arc::new(crypt_config)) |
ec34f7eb DM |
1314 | } |
1315 | }; | |
1316 | ||
e18a6c9e | 1317 | let data = file_get_contents(logfile)?; |
ec34f7eb | 1318 | |
7123ff7d | 1319 | let blob = DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?; |
ec34f7eb DM |
1320 | |
1321 | let raw_data = blob.into_inner(); | |
1322 | ||
1323 | let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store()); | |
1324 | ||
1325 | let args = json!({ | |
1326 | "backup-type": snapshot.group().backup_type(), | |
1327 | "backup-id": snapshot.group().backup_id(), | |
1328 | "backup-time": snapshot.backup_time().timestamp(), | |
1329 | }); | |
1330 | ||
1331 | let body = hyper::Body::from(raw_data); | |
1332 | ||
8a8a4703 | 1333 | client.upload("application/octet-stream", body, &path, Some(args)).await |
ec34f7eb DM |
1334 | } |
1335 | ||
a47a02ae DM |
1336 | #[api( |
1337 | input: { | |
1338 | properties: { | |
1339 | repository: { | |
1340 | schema: REPO_URL_SCHEMA, | |
1341 | optional: true, | |
1342 | }, | |
1343 | group: { | |
1344 | type: String, | |
1345 | description: "Backup group.", | |
1346 | }, | |
1347 | "output-format": { | |
1348 | schema: OUTPUT_FORMAT, | |
1349 | optional: true, | |
1350 | }, | |
1351 | "dry-run": { | |
1352 | type: Boolean, | |
1353 | description: "Just show what prune would do, but do not delete anything.", | |
1354 | optional: true, | |
1355 | }, | |
1356 | } | |
1357 | } | |
1358 | )] | |
1359 | /// Prune a backup repository. | |
1360 | async fn prune(mut param: Value) -> Result<Value, Error> { | |
83b7db02 | 1361 | |
2665cef7 | 1362 | let repo = extract_repository_from_value(¶m)?; |
83b7db02 | 1363 | |
cc2ce4a9 | 1364 | let mut client = HttpClient::new(repo.host(), repo.user(), None)?; |
83b7db02 | 1365 | |
d0a03d40 | 1366 | let path = format!("api2/json/admin/datastore/{}/prune", repo.store()); |
83b7db02 | 1367 | |
9fdc3ef4 DM |
1368 | let group = tools::required_string_param(¶m, "group")?; |
1369 | let group = BackupGroup::parse(group)?; | |
163e9bbe | 1370 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); |
9fdc3ef4 | 1371 | |
ea7a7ef2 DM |
1372 | param.as_object_mut().unwrap().remove("repository"); |
1373 | param.as_object_mut().unwrap().remove("group"); | |
163e9bbe | 1374 | param.as_object_mut().unwrap().remove("output-format"); |
ea7a7ef2 DM |
1375 | |
1376 | param["backup-type"] = group.backup_type().into(); | |
1377 | param["backup-id"] = group.backup_id().into(); | |
83b7db02 | 1378 | |
87c42375 | 1379 | let result = client.post(&path, Some(param)).await?; |
74fa81b8 | 1380 | |
87c42375 | 1381 | record_repository(&repo); |
3b03abfe | 1382 | |
87c42375 | 1383 | view_task_result(client, result, &output_format).await?; |
d0a03d40 | 1384 | |
43a406fd | 1385 | Ok(Value::Null) |
83b7db02 DM |
1386 | } |
1387 | ||
a47a02ae DM |
1388 | #[api( |
1389 | input: { | |
1390 | properties: { | |
1391 | repository: { | |
1392 | schema: REPO_URL_SCHEMA, | |
1393 | optional: true, | |
1394 | }, | |
1395 | "output-format": { | |
1396 | schema: OUTPUT_FORMAT, | |
1397 | optional: true, | |
1398 | }, | |
1399 | } | |
1400 | } | |
1401 | )] | |
1402 | /// Get repository status. | |
1403 | async fn status(param: Value) -> Result<Value, Error> { | |
34a816cc DM |
1404 | |
1405 | let repo = extract_repository_from_value(¶m)?; | |
1406 | ||
1407 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); | |
1408 | ||
cc2ce4a9 | 1409 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
34a816cc DM |
1410 | |
1411 | let path = format!("api2/json/admin/datastore/{}/status", repo.store()); | |
1412 | ||
87c42375 | 1413 | let result = client.get(&path, None).await?; |
34a816cc DM |
1414 | let data = &result["data"]; |
1415 | ||
1416 | record_repository(&repo); | |
1417 | ||
1418 | if output_format == "text" { | |
1419 | let total = data["total"].as_u64().unwrap(); | |
1420 | let used = data["used"].as_u64().unwrap(); | |
1421 | let avail = data["avail"].as_u64().unwrap(); | |
1422 | let roundup = total/200; | |
1423 | ||
1424 | println!( | |
1425 | "total: {} used: {} ({} %) available: {}", | |
1426 | total, | |
1427 | used, | |
1428 | ((used+roundup)*100)/total, | |
1429 | avail, | |
1430 | ); | |
1431 | } else { | |
f6ede796 | 1432 | format_and_print_result(data, &output_format); |
34a816cc DM |
1433 | } |
1434 | ||
1435 | Ok(Value::Null) | |
1436 | } | |
1437 | ||
5a2df000 | 1438 | // like get, but simply ignore errors and return Null instead |
e9722f8b | 1439 | async fn try_get(repo: &BackupRepository, url: &str) -> Value { |
024f11bb | 1440 | |
cc2ce4a9 | 1441 | let client = match HttpClient::new(repo.host(), repo.user(), None) { |
45cdce06 DM |
1442 | Ok(v) => v, |
1443 | _ => return Value::Null, | |
1444 | }; | |
b2388518 | 1445 | |
e9722f8b | 1446 | let mut resp = match client.get(url, None).await { |
b2388518 DM |
1447 | Ok(v) => v, |
1448 | _ => return Value::Null, | |
1449 | }; | |
1450 | ||
1451 | if let Some(map) = resp.as_object_mut() { | |
1452 | if let Some(data) = map.remove("data") { | |
1453 | return data; | |
1454 | } | |
1455 | } | |
1456 | Value::Null | |
1457 | } | |
1458 | ||
b2388518 | 1459 | fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
e9722f8b WB |
1460 | async_main(async { complete_backup_group_do(param).await }) |
1461 | } | |
1462 | ||
1463 | async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> { | |
024f11bb | 1464 | |
b2388518 DM |
1465 | let mut result = vec![]; |
1466 | ||
2665cef7 | 1467 | let repo = match extract_repository_from_map(param) { |
b2388518 | 1468 | Some(v) => v, |
024f11bb DM |
1469 | _ => return result, |
1470 | }; | |
1471 | ||
b2388518 DM |
1472 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
1473 | ||
e9722f8b | 1474 | let data = try_get(&repo, &path).await; |
b2388518 DM |
1475 | |
1476 | if let Some(list) = data.as_array() { | |
024f11bb | 1477 | for item in list { |
98f0b972 DM |
1478 | if let (Some(backup_id), Some(backup_type)) = |
1479 | (item["backup-id"].as_str(), item["backup-type"].as_str()) | |
1480 | { | |
1481 | result.push(format!("{}/{}", backup_type, backup_id)); | |
024f11bb DM |
1482 | } |
1483 | } | |
1484 | } | |
1485 | ||
1486 | result | |
1487 | } | |
1488 | ||
b2388518 | 1489 | fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
e9722f8b WB |
1490 | async_main(async { complete_group_or_snapshot_do(arg, param).await }) |
1491 | } | |
1492 | ||
1493 | async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
b2388518 | 1494 | |
b2388518 | 1495 | if arg.matches('/').count() < 2 { |
e9722f8b | 1496 | let groups = complete_backup_group_do(param).await; |
543a260f | 1497 | let mut result = vec![]; |
b2388518 DM |
1498 | for group in groups { |
1499 | result.push(group.to_string()); | |
1500 | result.push(format!("{}/", group)); | |
1501 | } | |
1502 | return result; | |
1503 | } | |
1504 | ||
e9722f8b | 1505 | complete_backup_snapshot_do(param).await |
543a260f | 1506 | } |
b2388518 | 1507 | |
3fb53e07 | 1508 | fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
e9722f8b WB |
1509 | async_main(async { complete_backup_snapshot_do(param).await }) |
1510 | } | |
1511 | ||
1512 | async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> { | |
543a260f DM |
1513 | |
1514 | let mut result = vec![]; | |
1515 | ||
1516 | let repo = match extract_repository_from_map(param) { | |
1517 | Some(v) => v, | |
1518 | _ => return result, | |
1519 | }; | |
1520 | ||
1521 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); | |
b2388518 | 1522 | |
e9722f8b | 1523 | let data = try_get(&repo, &path).await; |
b2388518 DM |
1524 | |
1525 | if let Some(list) = data.as_array() { | |
1526 | for item in list { | |
1527 | if let (Some(backup_id), Some(backup_type), Some(backup_time)) = | |
1528 | (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64()) | |
1529 | { | |
1530 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time); | |
1531 | result.push(snapshot.relative_path().to_str().unwrap().to_owned()); | |
1532 | } | |
1533 | } | |
1534 | } | |
1535 | ||
1536 | result | |
1537 | } | |
1538 | ||
45db6f89 | 1539 | fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
e9722f8b WB |
1540 | async_main(async { complete_server_file_name_do(param).await }) |
1541 | } | |
1542 | ||
1543 | async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> { | |
08dc340a DM |
1544 | |
1545 | let mut result = vec![]; | |
1546 | ||
2665cef7 | 1547 | let repo = match extract_repository_from_map(param) { |
08dc340a DM |
1548 | Some(v) => v, |
1549 | _ => return result, | |
1550 | }; | |
1551 | ||
1552 | let snapshot = match param.get("snapshot") { | |
1553 | Some(path) => { | |
1554 | match BackupDir::parse(path) { | |
1555 | Ok(v) => v, | |
1556 | _ => return result, | |
1557 | } | |
1558 | } | |
1559 | _ => return result, | |
1560 | }; | |
1561 | ||
1562 | let query = tools::json_object_to_query(json!({ | |
1563 | "backup-type": snapshot.group().backup_type(), | |
1564 | "backup-id": snapshot.group().backup_id(), | |
1565 | "backup-time": snapshot.backup_time().timestamp(), | |
1566 | })).unwrap(); | |
1567 | ||
1568 | let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query); | |
1569 | ||
e9722f8b | 1570 | let data = try_get(&repo, &path).await; |
08dc340a DM |
1571 | |
1572 | if let Some(list) = data.as_array() { | |
1573 | for item in list { | |
c4f025eb | 1574 | if let Some(filename) = item["filename"].as_str() { |
08dc340a DM |
1575 | result.push(filename.to_owned()); |
1576 | } | |
1577 | } | |
1578 | } | |
1579 | ||
45db6f89 DM |
1580 | result |
1581 | } | |
1582 | ||
1583 | fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
52c171e4 | 1584 | complete_server_file_name(arg, param) |
e9722f8b WB |
1585 | .iter() |
1586 | .map(|v| strip_server_file_expenstion(&v)) | |
1587 | .collect() | |
08dc340a DM |
1588 | } |
1589 | ||
0ec9e1b0 DM |
1590 | fn complete_pxar_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
1591 | complete_server_file_name(arg, param) | |
1592 | .iter() | |
1593 | .filter_map(|v| { | |
1594 | let name = strip_server_file_expenstion(&v); | |
1595 | if name.ends_with(".pxar") { | |
1596 | Some(name) | |
1597 | } else { | |
1598 | None | |
1599 | } | |
1600 | }) | |
1601 | .collect() | |
1602 | } | |
1603 | ||
49811347 DM |
1604 | fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
1605 | ||
1606 | let mut result = vec![]; | |
1607 | ||
1608 | let mut size = 64; | |
1609 | loop { | |
1610 | result.push(size.to_string()); | |
11377a47 | 1611 | size *= 2; |
49811347 DM |
1612 | if size > 4096 { break; } |
1613 | } | |
1614 | ||
1615 | result | |
1616 | } | |
1617 | ||
826f309b | 1618 | fn get_encryption_key_password() -> Result<Vec<u8>, Error> { |
ff5d3707 | 1619 | |
f2401311 DM |
1620 | // fixme: implement other input methods |
1621 | ||
1622 | use std::env::VarError::*; | |
1623 | match std::env::var("PBS_ENCRYPTION_PASSWORD") { | |
826f309b | 1624 | Ok(p) => return Ok(p.as_bytes().to_vec()), |
f2401311 DM |
1625 | Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"), |
1626 | Err(NotPresent) => { | |
1627 | // Try another method | |
1628 | } | |
1629 | } | |
1630 | ||
1631 | // If we're on a TTY, query the user for a password | |
1632 | if crate::tools::tty::stdin_isatty() { | |
826f309b | 1633 | return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?); |
f2401311 DM |
1634 | } |
1635 | ||
1636 | bail!("no password input mechanism available"); | |
1637 | } | |
1638 | ||
ac716234 DM |
1639 | fn key_create( |
1640 | param: Value, | |
1641 | _info: &ApiMethod, | |
1642 | _rpcenv: &mut dyn RpcEnvironment, | |
1643 | ) -> Result<Value, Error> { | |
1644 | ||
9b06db45 DM |
1645 | let path = tools::required_string_param(¶m, "path")?; |
1646 | let path = PathBuf::from(path); | |
ac716234 | 1647 | |
181f097a | 1648 | let kdf = param["kdf"].as_str().unwrap_or("scrypt"); |
ac716234 DM |
1649 | |
1650 | let key = proxmox::sys::linux::random_data(32)?; | |
1651 | ||
181f097a DM |
1652 | if kdf == "scrypt" { |
1653 | // always read passphrase from tty | |
1654 | if !crate::tools::tty::stdin_isatty() { | |
1655 | bail!("unable to read passphrase - no tty"); | |
1656 | } | |
ac716234 | 1657 | |
181f097a DM |
1658 | let password = crate::tools::tty::read_password("Encryption Key Password: ")?; |
1659 | ||
ab44acff | 1660 | let key_config = encrypt_key_with_passphrase(&key, &password)?; |
37c5a175 | 1661 | |
ab44acff | 1662 | store_key_config(&path, false, key_config)?; |
181f097a DM |
1663 | |
1664 | Ok(Value::Null) | |
1665 | } else if kdf == "none" { | |
1666 | let created = Local.timestamp(Local::now().timestamp(), 0); | |
1667 | ||
1668 | store_key_config(&path, false, KeyConfig { | |
1669 | kdf: None, | |
1670 | created, | |
ab44acff | 1671 | modified: created, |
181f097a DM |
1672 | data: key, |
1673 | })?; | |
1674 | ||
1675 | Ok(Value::Null) | |
1676 | } else { | |
1677 | unreachable!(); | |
1678 | } | |
ac716234 DM |
1679 | } |
1680 | ||
9f46c7de DM |
1681 | fn master_pubkey_path() -> Result<PathBuf, Error> { |
1682 | let base = BaseDirectories::with_prefix("proxmox-backup")?; | |
1683 | ||
1684 | // usually $HOME/.config/proxmox-backup/master-public.pem | |
1685 | let path = base.place_config_file("master-public.pem")?; | |
1686 | ||
1687 | Ok(path) | |
1688 | } | |
1689 | ||
3ea8bfc9 DM |
1690 | fn key_import_master_pubkey( |
1691 | param: Value, | |
1692 | _info: &ApiMethod, | |
1693 | _rpcenv: &mut dyn RpcEnvironment, | |
1694 | ) -> Result<Value, Error> { | |
1695 | ||
1696 | let path = tools::required_string_param(¶m, "path")?; | |
1697 | let path = PathBuf::from(path); | |
1698 | ||
e18a6c9e | 1699 | let pem_data = file_get_contents(&path)?; |
3ea8bfc9 DM |
1700 | |
1701 | if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) { | |
1702 | bail!("Unable to decode PEM data - {}", err); | |
1703 | } | |
1704 | ||
9f46c7de | 1705 | let target_path = master_pubkey_path()?; |
3ea8bfc9 | 1706 | |
feaa1ad3 | 1707 | replace_file(&target_path, &pem_data, CreateOptions::new())?; |
3ea8bfc9 DM |
1708 | |
1709 | println!("Imported public master key to {:?}", target_path); | |
1710 | ||
1711 | Ok(Value::Null) | |
1712 | } | |
1713 | ||
37c5a175 DM |
1714 | fn key_create_master_key( |
1715 | _param: Value, | |
1716 | _info: &ApiMethod, | |
1717 | _rpcenv: &mut dyn RpcEnvironment, | |
1718 | ) -> Result<Value, Error> { | |
1719 | ||
1720 | // we need a TTY to query the new password | |
1721 | if !crate::tools::tty::stdin_isatty() { | |
1722 | bail!("unable to create master key - no tty"); | |
1723 | } | |
1724 | ||
1725 | let rsa = openssl::rsa::Rsa::generate(4096)?; | |
1726 | let pkey = openssl::pkey::PKey::from_rsa(rsa)?; | |
1727 | ||
1728 | let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?; | |
1729 | let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?; | |
1730 | ||
1731 | if new_pw != verify_pw { | |
1732 | bail!("Password verification fail!"); | |
1733 | } | |
1734 | ||
1735 | if new_pw.len() < 5 { | |
1736 | bail!("Password is too short!"); | |
1737 | } | |
1738 | ||
1739 | let pub_key: Vec<u8> = pkey.public_key_to_pem()?; | |
1740 | let filename_pub = "master-public.pem"; | |
1741 | println!("Writing public master key to {}", filename_pub); | |
feaa1ad3 | 1742 | replace_file(filename_pub, pub_key.as_slice(), CreateOptions::new())?; |
37c5a175 DM |
1743 | |
1744 | let cipher = openssl::symm::Cipher::aes_256_cbc(); | |
1745 | let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?; | |
1746 | ||
1747 | let filename_priv = "master-private.pem"; | |
1748 | println!("Writing private master key to {}", filename_priv); | |
feaa1ad3 | 1749 | replace_file(filename_priv, priv_key.as_slice(), CreateOptions::new())?; |
37c5a175 DM |
1750 | |
1751 | Ok(Value::Null) | |
1752 | } | |
ac716234 DM |
1753 | |
1754 | fn key_change_passphrase( | |
1755 | param: Value, | |
1756 | _info: &ApiMethod, | |
1757 | _rpcenv: &mut dyn RpcEnvironment, | |
1758 | ) -> Result<Value, Error> { | |
1759 | ||
9b06db45 DM |
1760 | let path = tools::required_string_param(¶m, "path")?; |
1761 | let path = PathBuf::from(path); | |
ac716234 | 1762 | |
181f097a DM |
1763 | let kdf = param["kdf"].as_str().unwrap_or("scrypt"); |
1764 | ||
ac716234 DM |
1765 | // we need a TTY to query the new password |
1766 | if !crate::tools::tty::stdin_isatty() { | |
1767 | bail!("unable to change passphrase - no tty"); | |
1768 | } | |
1769 | ||
a8f10f84 | 1770 | let (key, created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
ac716234 | 1771 | |
181f097a | 1772 | if kdf == "scrypt" { |
ac716234 | 1773 | |
181f097a DM |
1774 | let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?; |
1775 | let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?; | |
ac716234 | 1776 | |
181f097a DM |
1777 | if new_pw != verify_pw { |
1778 | bail!("Password verification fail!"); | |
1779 | } | |
1780 | ||
1781 | if new_pw.len() < 5 { | |
1782 | bail!("Password is too short!"); | |
1783 | } | |
ac716234 | 1784 | |
ab44acff DM |
1785 | let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?; |
1786 | new_key_config.created = created; // keep original value | |
1787 | ||
1788 | store_key_config(&path, true, new_key_config)?; | |
ac716234 | 1789 | |
181f097a DM |
1790 | Ok(Value::Null) |
1791 | } else if kdf == "none" { | |
ab44acff | 1792 | let modified = Local.timestamp(Local::now().timestamp(), 0); |
181f097a DM |
1793 | |
1794 | store_key_config(&path, true, KeyConfig { | |
1795 | kdf: None, | |
ab44acff DM |
1796 | created, // keep original value |
1797 | modified, | |
6d0983db | 1798 | data: key.to_vec(), |
181f097a DM |
1799 | })?; |
1800 | ||
1801 | Ok(Value::Null) | |
1802 | } else { | |
1803 | unreachable!(); | |
1804 | } | |
f2401311 DM |
1805 | } |
1806 | ||
1807 | fn key_mgmt_cli() -> CliCommandMap { | |
1808 | ||
255f378a | 1809 | const KDF_SCHEMA: Schema = |
181f097a | 1810 | StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.") |
255f378a DM |
1811 | .format(&ApiStringFormat::Enum(&["scrypt", "none"])) |
1812 | .default("scrypt") | |
1813 | .schema(); | |
1814 | ||
552c2259 | 1815 | #[sortable] |
255f378a DM |
1816 | const API_METHOD_KEY_CREATE: ApiMethod = ApiMethod::new( |
1817 | &ApiHandler::Sync(&key_create), | |
1818 | &ObjectSchema::new( | |
1819 | "Create a new encryption key.", | |
552c2259 | 1820 | &sorted!([ |
255f378a DM |
1821 | ("path", false, &StringSchema::new("File system path.").schema()), |
1822 | ("kdf", true, &KDF_SCHEMA), | |
552c2259 | 1823 | ]), |
255f378a | 1824 | ) |
181f097a | 1825 | ); |
7074a0b3 | 1826 | |
255f378a | 1827 | let key_create_cmd_def = CliCommand::new(&API_METHOD_KEY_CREATE) |
49fddd98 | 1828 | .arg_param(&["path"]) |
9b06db45 | 1829 | .completion_cb("path", tools::complete_file_name); |
f2401311 | 1830 | |
552c2259 | 1831 | #[sortable] |
255f378a DM |
1832 | const API_METHOD_KEY_CHANGE_PASSPHRASE: ApiMethod = ApiMethod::new( |
1833 | &ApiHandler::Sync(&key_change_passphrase), | |
1834 | &ObjectSchema::new( | |
1835 | "Change the passphrase required to decrypt the key.", | |
552c2259 | 1836 | &sorted!([ |
255f378a DM |
1837 | ("path", false, &StringSchema::new("File system path.").schema()), |
1838 | ("kdf", true, &KDF_SCHEMA), | |
552c2259 | 1839 | ]), |
255f378a DM |
1840 | ) |
1841 | ); | |
7074a0b3 | 1842 | |
255f378a | 1843 | let key_change_passphrase_cmd_def = CliCommand::new(&API_METHOD_KEY_CHANGE_PASSPHRASE) |
49fddd98 | 1844 | .arg_param(&["path"]) |
9b06db45 | 1845 | .completion_cb("path", tools::complete_file_name); |
ac716234 | 1846 | |
255f378a DM |
1847 | const API_METHOD_KEY_CREATE_MASTER_KEY: ApiMethod = ApiMethod::new( |
1848 | &ApiHandler::Sync(&key_create_master_key), | |
1849 | &ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.", &[]) | |
1850 | ); | |
7074a0b3 | 1851 | |
255f378a DM |
1852 | let key_create_master_key_cmd_def = CliCommand::new(&API_METHOD_KEY_CREATE_MASTER_KEY); |
1853 | ||
552c2259 | 1854 | #[sortable] |
255f378a DM |
1855 | const API_METHOD_KEY_IMPORT_MASTER_PUBKEY: ApiMethod = ApiMethod::new( |
1856 | &ApiHandler::Sync(&key_import_master_pubkey), | |
1857 | &ObjectSchema::new( | |
1858 | "Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.", | |
552c2259 | 1859 | &sorted!([ ("path", false, &StringSchema::new("File system path.").schema()) ]), |
255f378a DM |
1860 | ) |
1861 | ); | |
7074a0b3 | 1862 | |
255f378a | 1863 | let key_import_master_pubkey_cmd_def = CliCommand::new(&API_METHOD_KEY_IMPORT_MASTER_PUBKEY) |
49fddd98 | 1864 | .arg_param(&["path"]) |
3ea8bfc9 DM |
1865 | .completion_cb("path", tools::complete_file_name); |
1866 | ||
11377a47 | 1867 | CliCommandMap::new() |
48ef3c33 DM |
1868 | .insert("create", key_create_cmd_def) |
1869 | .insert("create-master-key", key_create_master_key_cmd_def) | |
1870 | .insert("import-master-pubkey", key_import_master_pubkey_cmd_def) | |
1871 | .insert("change-passphrase", key_change_passphrase_cmd_def) | |
f2401311 DM |
1872 | } |
1873 | ||
70235f72 CE |
1874 | fn mount( |
1875 | param: Value, | |
1876 | _info: &ApiMethod, | |
1877 | _rpcenv: &mut dyn RpcEnvironment, | |
1878 | ) -> Result<Value, Error> { | |
1879 | let verbose = param["verbose"].as_bool().unwrap_or(false); | |
1880 | if verbose { | |
1881 | // This will stay in foreground with debug output enabled as None is | |
1882 | // passed for the RawFd. | |
1883 | return async_main(mount_do(param, None)); | |
1884 | } | |
1885 | ||
1886 | // Process should be deamonized. | |
1887 | // Make sure to fork before the async runtime is instantiated to avoid troubles. | |
1888 | let pipe = pipe()?; | |
1889 | match fork() { | |
11377a47 | 1890 | Ok(ForkResult::Parent { .. }) => { |
70235f72 CE |
1891 | nix::unistd::close(pipe.1).unwrap(); |
1892 | // Blocks the parent process until we are ready to go in the child | |
1893 | let _res = nix::unistd::read(pipe.0, &mut [0]).unwrap(); | |
1894 | Ok(Value::Null) | |
1895 | } | |
1896 | Ok(ForkResult::Child) => { | |
1897 | nix::unistd::close(pipe.0).unwrap(); | |
1898 | nix::unistd::setsid().unwrap(); | |
1899 | async_main(mount_do(param, Some(pipe.1))) | |
1900 | } | |
1901 | Err(_) => bail!("failed to daemonize process"), | |
1902 | } | |
1903 | } | |
1904 | ||
1905 | async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> { | |
1906 | let repo = extract_repository_from_value(¶m)?; | |
1907 | let archive_name = tools::required_string_param(¶m, "archive-name")?; | |
1908 | let target = tools::required_string_param(¶m, "target")?; | |
1909 | let client = HttpClient::new(repo.host(), repo.user(), None)?; | |
1910 | ||
1911 | record_repository(&repo); | |
1912 | ||
1913 | let path = tools::required_string_param(¶m, "snapshot")?; | |
1914 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { | |
1915 | let group = BackupGroup::parse(path)?; | |
1916 | ||
42af4b8f | 1917 | let mut list = api_datastore_list_snapshots(&client, repo.store(), Some(group.clone())).await?; |
70235f72 | 1918 | |
11377a47 | 1919 | if list.is_empty() { |
70235f72 CE |
1920 | bail!("backup group '{}' does not contain any snapshots:", path); |
1921 | } | |
1922 | ||
42af4b8f DM |
1923 | list.sort_unstable_by(|a, b| b.backup_time.cmp(&a.backup_time)); |
1924 | ||
1925 | let backup_time = Utc.timestamp(list[0].backup_time, 0); | |
1926 | ||
70235f72 CE |
1927 | (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time) |
1928 | } else { | |
1929 | let snapshot = BackupDir::parse(path)?; | |
1930 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) | |
1931 | }; | |
1932 | ||
11377a47 | 1933 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); |
70235f72 CE |
1934 | let crypt_config = match keyfile { |
1935 | None => None, | |
1936 | Some(path) => { | |
a8f10f84 | 1937 | let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
70235f72 CE |
1938 | Some(Arc::new(CryptConfig::new(key)?)) |
1939 | } | |
1940 | }; | |
1941 | ||
1942 | let server_archive_name = if archive_name.ends_with(".pxar") { | |
1943 | format!("{}.didx", archive_name) | |
1944 | } else { | |
1945 | bail!("Can only mount pxar archives."); | |
1946 | }; | |
1947 | ||
296c50ba DM |
1948 | let client = BackupReader::start( |
1949 | client, | |
1950 | crypt_config.clone(), | |
1951 | repo.store(), | |
1952 | &backup_type, | |
1953 | &backup_id, | |
1954 | backup_time, | |
1955 | true, | |
1956 | ).await?; | |
70235f72 | 1957 | |
f06b820a | 1958 | let manifest = client.download_manifest().await?; |
296c50ba | 1959 | |
70235f72 | 1960 | if server_archive_name.ends_with(".didx") { |
c3d84a22 | 1961 | let index = client.download_dynamic_index(&manifest, &server_archive_name).await?; |
70235f72 CE |
1962 | let most_used = index.find_most_used_chunks(8); |
1963 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
1964 | let reader = BufferedDynamicReader::new(index, chunk_reader); | |
f701d033 | 1965 | let decoder = pxar::Decoder::new(reader)?; |
70235f72 | 1966 | let options = OsStr::new("ro,default_permissions"); |
2a111910 | 1967 | let mut session = pxar::fuse::Session::new(decoder, &options, pipe.is_none()) |
70235f72 CE |
1968 | .map_err(|err| format_err!("pxar mount failed: {}", err))?; |
1969 | ||
1970 | // Mount the session but not call fuse deamonize as this will cause | |
1971 | // issues with the runtime after the fork | |
1972 | let deamonize = false; | |
1973 | session.mount(&Path::new(target), deamonize)?; | |
1974 | ||
1975 | if let Some(pipe) = pipe { | |
1976 | nix::unistd::chdir(Path::new("/")).unwrap(); | |
1977 | // Finish creation of deamon by redirecting filedescriptors. | |
1978 | let nullfd = nix::fcntl::open( | |
1979 | "/dev/null", | |
1980 | nix::fcntl::OFlag::O_RDWR, | |
1981 | nix::sys::stat::Mode::empty(), | |
1982 | ).unwrap(); | |
1983 | nix::unistd::dup2(nullfd, 0).unwrap(); | |
1984 | nix::unistd::dup2(nullfd, 1).unwrap(); | |
1985 | nix::unistd::dup2(nullfd, 2).unwrap(); | |
1986 | if nullfd > 2 { | |
1987 | nix::unistd::close(nullfd).unwrap(); | |
1988 | } | |
1989 | // Signal the parent process that we are done with the setup and it can | |
1990 | // terminate. | |
11377a47 | 1991 | nix::unistd::write(pipe, &[0u8])?; |
70235f72 CE |
1992 | nix::unistd::close(pipe).unwrap(); |
1993 | } | |
1994 | ||
1995 | let multithreaded = true; | |
1996 | session.run_loop(multithreaded)?; | |
1997 | } else { | |
1998 | bail!("unknown archive file extension (expected .pxar)"); | |
1999 | } | |
2000 | ||
2001 | Ok(Value::Null) | |
2002 | } | |
2003 | ||
78d54360 WB |
2004 | #[api( |
2005 | input: { | |
2006 | properties: { | |
2007 | "snapshot": { | |
2008 | type: String, | |
2009 | description: "Group/Snapshot path.", | |
2010 | }, | |
2011 | "archive-name": { | |
2012 | type: String, | |
2013 | description: "Backup archive name.", | |
2014 | }, | |
2015 | "repository": { | |
2016 | optional: true, | |
2017 | schema: REPO_URL_SCHEMA, | |
2018 | }, | |
2019 | "keyfile": { | |
2020 | optional: true, | |
2021 | type: String, | |
2022 | description: "Path to encryption key.", | |
2023 | }, | |
2024 | }, | |
2025 | }, | |
2026 | )] | |
2027 | /// Shell to interactively inspect and restore snapshots. | |
2028 | async fn catalog_shell(param: Value) -> Result<(), Error> { | |
3cf73c4e CE |
2029 | let repo = extract_repository_from_value(¶m)?; |
2030 | let client = HttpClient::new(repo.host(), repo.user(), None)?; | |
2031 | let path = tools::required_string_param(¶m, "snapshot")?; | |
2032 | let archive_name = tools::required_string_param(¶m, "archive-name")?; | |
2033 | ||
2034 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { | |
2035 | let group = BackupGroup::parse(path)?; | |
2036 | ||
42af4b8f | 2037 | let mut list = api_datastore_list_snapshots(&client, repo.store(), Some(group.clone())).await?; |
3cf73c4e | 2038 | |
314bb358 | 2039 | if list.is_empty() { |
3cf73c4e CE |
2040 | bail!("backup group '{}' does not contain any snapshots:", path); |
2041 | } | |
2042 | ||
af9d4afc DM |
2043 | list.sort_unstable_by(|a, b| b.backup_time.cmp(&a.backup_time)); |
2044 | ||
2045 | let backup_time = Utc.timestamp(list[0].backup_time, 0); | |
2046 | ||
3cf73c4e CE |
2047 | (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time) |
2048 | } else { | |
2049 | let snapshot = BackupDir::parse(path)?; | |
2050 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) | |
2051 | }; | |
2052 | ||
2053 | let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p)); | |
2054 | let crypt_config = match keyfile { | |
2055 | None => None, | |
2056 | Some(path) => { | |
2057 | let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; | |
2058 | Some(Arc::new(CryptConfig::new(key)?)) | |
2059 | } | |
2060 | }; | |
2061 | ||
2062 | let server_archive_name = if archive_name.ends_with(".pxar") { | |
2063 | format!("{}.didx", archive_name) | |
2064 | } else { | |
2065 | bail!("Can only mount pxar archives."); | |
2066 | }; | |
2067 | ||
2068 | let client = BackupReader::start( | |
2069 | client, | |
2070 | crypt_config.clone(), | |
2071 | repo.store(), | |
2072 | &backup_type, | |
2073 | &backup_id, | |
2074 | backup_time, | |
2075 | true, | |
2076 | ).await?; | |
2077 | ||
2078 | let tmpfile = std::fs::OpenOptions::new() | |
2079 | .write(true) | |
2080 | .read(true) | |
2081 | .custom_flags(libc::O_TMPFILE) | |
2082 | .open("/tmp")?; | |
2083 | ||
2084 | let manifest = client.download_manifest().await?; | |
2085 | ||
2086 | let index = client.download_dynamic_index(&manifest, &server_archive_name).await?; | |
2087 | let most_used = index.find_most_used_chunks(8); | |
2088 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config.clone(), most_used); | |
2089 | let reader = BufferedDynamicReader::new(index, chunk_reader); | |
f701d033 DM |
2090 | let mut decoder = pxar::Decoder::new(reader)?; |
2091 | decoder.set_callback(|path| { | |
2092 | println!("{:?}", path); | |
2093 | Ok(()) | |
2094 | }); | |
3cf73c4e CE |
2095 | |
2096 | let tmpfile = client.download(CATALOG_NAME, tmpfile).await?; | |
2097 | let index = DynamicIndexReader::new(tmpfile) | |
2098 | .map_err(|err| format_err!("unable to read catalog index - {}", err))?; | |
2099 | ||
2100 | // Note: do not use values stored in index (not trusted) - instead, computed them again | |
2101 | let (csum, size) = index.compute_csum(); | |
2102 | manifest.verify_file(CATALOG_NAME, &csum, size)?; | |
2103 | ||
2104 | let most_used = index.find_most_used_chunks(8); | |
2105 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
2106 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); | |
2107 | let mut catalogfile = std::fs::OpenOptions::new() | |
2108 | .write(true) | |
2109 | .read(true) | |
2110 | .custom_flags(libc::O_TMPFILE) | |
2111 | .open("/tmp")?; | |
2112 | ||
2113 | std::io::copy(&mut reader, &mut catalogfile) | |
2114 | .map_err(|err| format_err!("unable to download catalog - {}", err))?; | |
2115 | ||
2116 | catalogfile.seek(SeekFrom::Start(0))?; | |
2117 | let catalog_reader = CatalogReader::new(catalogfile); | |
2118 | let state = Shell::new( | |
2119 | catalog_reader, | |
2120 | &server_archive_name, | |
2121 | decoder, | |
2122 | )?; | |
2123 | ||
2124 | println!("Starting interactive shell"); | |
2125 | state.shell()?; | |
2126 | ||
2127 | record_repository(&repo); | |
2128 | ||
78d54360 | 2129 | Ok(()) |
3cf73c4e CE |
2130 | } |
2131 | ||
1c6ad6ef | 2132 | fn catalog_mgmt_cli() -> CliCommandMap { |
78d54360 | 2133 | let catalog_shell_cmd_def = CliCommand::new(&API_METHOD_CATALOG_SHELL) |
1c6ad6ef DM |
2134 | .arg_param(&["snapshot", "archive-name"]) |
2135 | .completion_cb("repository", complete_repository) | |
0ec9e1b0 | 2136 | .completion_cb("archive-name", complete_pxar_archive_name) |
1c6ad6ef DM |
2137 | .completion_cb("snapshot", complete_group_or_snapshot); |
2138 | ||
1c6ad6ef DM |
2139 | let catalog_dump_cmd_def = CliCommand::new(&API_METHOD_DUMP_CATALOG) |
2140 | .arg_param(&["snapshot"]) | |
2141 | .completion_cb("repository", complete_repository) | |
2142 | .completion_cb("snapshot", complete_backup_snapshot); | |
2143 | ||
2144 | CliCommandMap::new() | |
48ef3c33 DM |
2145 | .insert("dump", catalog_dump_cmd_def) |
2146 | .insert("shell", catalog_shell_cmd_def) | |
1c6ad6ef DM |
2147 | } |
2148 | ||
5830c205 DM |
2149 | #[api( |
2150 | input: { | |
2151 | properties: { | |
2152 | repository: { | |
2153 | schema: REPO_URL_SCHEMA, | |
2154 | optional: true, | |
2155 | }, | |
2156 | limit: { | |
2157 | description: "The maximal number of tasks to list.", | |
2158 | type: Integer, | |
2159 | optional: true, | |
2160 | minimum: 1, | |
2161 | maximum: 1000, | |
2162 | default: 50, | |
2163 | }, | |
2164 | "output-format": { | |
2165 | schema: OUTPUT_FORMAT, | |
2166 | optional: true, | |
2167 | }, | |
2168 | } | |
2169 | } | |
2170 | )] | |
2171 | /// List running server tasks for this repo user | |
d6c4a119 | 2172 | async fn task_list(param: Value) -> Result<Value, Error> { |
5830c205 | 2173 | |
d6c4a119 DM |
2174 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); |
2175 | let repo = extract_repository_from_value(¶m)?; | |
2176 | let client = HttpClient::new(repo.host(), repo.user(), None)?; | |
5830c205 | 2177 | |
d6c4a119 | 2178 | let limit = param["limit"].as_u64().unwrap_or(50) as usize; |
5830c205 | 2179 | |
d6c4a119 DM |
2180 | let args = json!({ |
2181 | "running": true, | |
2182 | "start": 0, | |
2183 | "limit": limit, | |
2184 | "userfilter": repo.user(), | |
2185 | "store": repo.store(), | |
2186 | }); | |
2187 | let result = client.get("api2/json/nodes/localhost/tasks", Some(args)).await?; | |
5830c205 | 2188 | |
d6c4a119 | 2189 | let data = &result["data"]; |
5830c205 | 2190 | |
d6c4a119 DM |
2191 | if output_format == "text" { |
2192 | for item in data.as_array().unwrap() { | |
2193 | println!( | |
2194 | "{} {}", | |
2195 | item["upid"].as_str().unwrap(), | |
2196 | item["status"].as_str().unwrap_or("running"), | |
2197 | ); | |
5830c205 | 2198 | } |
d6c4a119 DM |
2199 | } else { |
2200 | format_and_print_result(data, &output_format); | |
2201 | } | |
5830c205 DM |
2202 | |
2203 | Ok(Value::Null) | |
2204 | } | |
2205 | ||
2206 | #[api( | |
2207 | input: { | |
2208 | properties: { | |
2209 | repository: { | |
2210 | schema: REPO_URL_SCHEMA, | |
2211 | optional: true, | |
2212 | }, | |
2213 | upid: { | |
2214 | schema: UPID_SCHEMA, | |
2215 | }, | |
2216 | } | |
2217 | } | |
2218 | )] | |
2219 | /// Display the task log. | |
d6c4a119 | 2220 | async fn task_log(param: Value) -> Result<Value, Error> { |
5830c205 | 2221 | |
d6c4a119 DM |
2222 | let repo = extract_repository_from_value(¶m)?; |
2223 | let upid = tools::required_string_param(¶m, "upid")?; | |
5830c205 | 2224 | |
d6c4a119 | 2225 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
5830c205 | 2226 | |
d6c4a119 | 2227 | display_task_log(client, upid, true).await?; |
5830c205 DM |
2228 | |
2229 | Ok(Value::Null) | |
2230 | } | |
2231 | ||
3f1020b7 DM |
2232 | #[api( |
2233 | input: { | |
2234 | properties: { | |
2235 | repository: { | |
2236 | schema: REPO_URL_SCHEMA, | |
2237 | optional: true, | |
2238 | }, | |
2239 | upid: { | |
2240 | schema: UPID_SCHEMA, | |
2241 | }, | |
2242 | } | |
2243 | } | |
2244 | )] | |
2245 | /// Try to stop a specific task. | |
d6c4a119 | 2246 | async fn task_stop(param: Value) -> Result<Value, Error> { |
3f1020b7 | 2247 | |
d6c4a119 DM |
2248 | let repo = extract_repository_from_value(¶m)?; |
2249 | let upid_str = tools::required_string_param(¶m, "upid")?; | |
3f1020b7 | 2250 | |
d6c4a119 | 2251 | let mut client = HttpClient::new(repo.host(), repo.user(), None)?; |
3f1020b7 | 2252 | |
d6c4a119 DM |
2253 | let path = format!("api2/json/nodes/localhost/tasks/{}", upid_str); |
2254 | let _ = client.delete(&path, None).await?; | |
3f1020b7 DM |
2255 | |
2256 | Ok(Value::Null) | |
2257 | } | |
2258 | ||
5830c205 DM |
2259 | fn task_mgmt_cli() -> CliCommandMap { |
2260 | ||
2261 | let task_list_cmd_def = CliCommand::new(&API_METHOD_TASK_LIST) | |
2262 | .completion_cb("repository", complete_repository); | |
2263 | ||
2264 | let task_log_cmd_def = CliCommand::new(&API_METHOD_TASK_LOG) | |
2265 | .arg_param(&["upid"]); | |
2266 | ||
3f1020b7 DM |
2267 | let task_stop_cmd_def = CliCommand::new(&API_METHOD_TASK_STOP) |
2268 | .arg_param(&["upid"]); | |
2269 | ||
5830c205 DM |
2270 | CliCommandMap::new() |
2271 | .insert("log", task_log_cmd_def) | |
2272 | .insert("list", task_list_cmd_def) | |
3f1020b7 | 2273 | .insert("stop", task_stop_cmd_def) |
5830c205 | 2274 | } |
1c6ad6ef | 2275 | |
f2401311 | 2276 | fn main() { |
33d64b81 | 2277 | |
255f378a | 2278 | let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP) |
49fddd98 | 2279 | .arg_param(&["backupspec"]) |
d0a03d40 | 2280 | .completion_cb("repository", complete_repository) |
49811347 | 2281 | .completion_cb("backupspec", complete_backup_source) |
6d0983db | 2282 | .completion_cb("keyfile", tools::complete_file_name) |
49811347 | 2283 | .completion_cb("chunk-size", complete_chunk_size); |
f8838fe9 | 2284 | |
255f378a | 2285 | let upload_log_cmd_def = CliCommand::new(&API_METHOD_UPLOAD_LOG) |
49fddd98 | 2286 | .arg_param(&["snapshot", "logfile"]) |
543a260f | 2287 | .completion_cb("snapshot", complete_backup_snapshot) |
ec34f7eb DM |
2288 | .completion_cb("logfile", tools::complete_file_name) |
2289 | .completion_cb("keyfile", tools::complete_file_name) | |
2290 | .completion_cb("repository", complete_repository); | |
2291 | ||
255f378a | 2292 | let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS) |
d0a03d40 | 2293 | .completion_cb("repository", complete_repository); |
41c039e1 | 2294 | |
255f378a | 2295 | let snapshots_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOTS) |
49fddd98 | 2296 | .arg_param(&["group"]) |
024f11bb | 2297 | .completion_cb("group", complete_backup_group) |
d0a03d40 | 2298 | .completion_cb("repository", complete_repository); |
184f17af | 2299 | |
255f378a | 2300 | let forget_cmd_def = CliCommand::new(&API_METHOD_FORGET_SNAPSHOTS) |
49fddd98 | 2301 | .arg_param(&["snapshot"]) |
b2388518 | 2302 | .completion_cb("repository", complete_repository) |
543a260f | 2303 | .completion_cb("snapshot", complete_backup_snapshot); |
6f62c924 | 2304 | |
255f378a | 2305 | let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION) |
d0a03d40 | 2306 | .completion_cb("repository", complete_repository); |
8cc0d6af | 2307 | |
255f378a | 2308 | let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE) |
49fddd98 | 2309 | .arg_param(&["snapshot", "archive-name", "target"]) |
b2388518 | 2310 | .completion_cb("repository", complete_repository) |
08dc340a DM |
2311 | .completion_cb("snapshot", complete_group_or_snapshot) |
2312 | .completion_cb("archive-name", complete_archive_name) | |
2313 | .completion_cb("target", tools::complete_file_name); | |
9f912493 | 2314 | |
255f378a | 2315 | let files_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOT_FILES) |
49fddd98 | 2316 | .arg_param(&["snapshot"]) |
52c171e4 | 2317 | .completion_cb("repository", complete_repository) |
543a260f | 2318 | .completion_cb("snapshot", complete_backup_snapshot); |
52c171e4 | 2319 | |
255f378a | 2320 | let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE) |
49fddd98 | 2321 | .arg_param(&["group"]) |
9fdc3ef4 | 2322 | .completion_cb("group", complete_backup_group) |
d0a03d40 | 2323 | .completion_cb("repository", complete_repository); |
9f912493 | 2324 | |
255f378a | 2325 | let status_cmd_def = CliCommand::new(&API_METHOD_STATUS) |
34a816cc DM |
2326 | .completion_cb("repository", complete_repository); |
2327 | ||
255f378a | 2328 | let login_cmd_def = CliCommand::new(&API_METHOD_API_LOGIN) |
e240d8be DM |
2329 | .completion_cb("repository", complete_repository); |
2330 | ||
255f378a | 2331 | let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT) |
e240d8be | 2332 | .completion_cb("repository", complete_repository); |
32efac1c | 2333 | |
552c2259 | 2334 | #[sortable] |
255f378a DM |
2335 | const API_METHOD_MOUNT: ApiMethod = ApiMethod::new( |
2336 | &ApiHandler::Sync(&mount), | |
2337 | &ObjectSchema::new( | |
2338 | "Mount pxar archive.", | |
552c2259 | 2339 | &sorted!([ |
255f378a DM |
2340 | ("snapshot", false, &StringSchema::new("Group/Snapshot path.").schema()), |
2341 | ("archive-name", false, &StringSchema::new("Backup archive name.").schema()), | |
2342 | ("target", false, &StringSchema::new("Target directory path.").schema()), | |
2343 | ("repository", true, &REPO_URL_SCHEMA), | |
2344 | ("keyfile", true, &StringSchema::new("Path to encryption key.").schema()), | |
2345 | ("verbose", true, &BooleanSchema::new("Verbose output.").default(false).schema()), | |
552c2259 | 2346 | ]), |
255f378a DM |
2347 | ) |
2348 | ); | |
7074a0b3 | 2349 | |
255f378a | 2350 | let mount_cmd_def = CliCommand::new(&API_METHOD_MOUNT) |
49fddd98 | 2351 | .arg_param(&["snapshot", "archive-name", "target"]) |
70235f72 CE |
2352 | .completion_cb("repository", complete_repository) |
2353 | .completion_cb("snapshot", complete_group_or_snapshot) | |
0ec9e1b0 | 2354 | .completion_cb("archive-name", complete_pxar_archive_name) |
70235f72 | 2355 | .completion_cb("target", tools::complete_file_name); |
e240d8be | 2356 | |
3cf73c4e | 2357 | |
41c039e1 | 2358 | let cmd_def = CliCommandMap::new() |
48ef3c33 DM |
2359 | .insert("backup", backup_cmd_def) |
2360 | .insert("upload-log", upload_log_cmd_def) | |
2361 | .insert("forget", forget_cmd_def) | |
2362 | .insert("garbage-collect", garbage_collect_cmd_def) | |
2363 | .insert("list", list_cmd_def) | |
2364 | .insert("login", login_cmd_def) | |
2365 | .insert("logout", logout_cmd_def) | |
2366 | .insert("prune", prune_cmd_def) | |
2367 | .insert("restore", restore_cmd_def) | |
2368 | .insert("snapshots", snapshots_cmd_def) | |
2369 | .insert("files", files_cmd_def) | |
2370 | .insert("status", status_cmd_def) | |
2371 | .insert("key", key_mgmt_cli()) | |
2372 | .insert("mount", mount_cmd_def) | |
5830c205 DM |
2373 | .insert("catalog", catalog_mgmt_cli()) |
2374 | .insert("task", task_mgmt_cli()); | |
48ef3c33 DM |
2375 | |
2376 | run_cli_command(cmd_def); | |
e9722f8b | 2377 | } |
496a6784 | 2378 | |
e9722f8b | 2379 | fn async_main<F: Future>(fut: F) -> <F as Future>::Output { |
db0cb9ce | 2380 | let mut rt = tokio::runtime::Runtime::new().unwrap(); |
e9722f8b | 2381 | let ret = rt.block_on(fut); |
db0cb9ce WB |
2382 | // This does not exist anymore. We need to actually stop our runaways instead... |
2383 | // rt.shutdown_now(); | |
e9722f8b | 2384 | ret |
ff5d3707 | 2385 | } |