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