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