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