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