]> git.proxmox.com Git - proxmox-backup.git/blob - src/bin/proxmox-backup-client.rs
client: use default encryption key if it is available
[proxmox-backup.git] / src / bin / proxmox-backup-client.rs
1 use std::collections::{HashSet, HashMap};
2 use std::io::{self, Write, Seek, SeekFrom};
3 use std::path::{Path, PathBuf};
4 use std::pin::Pin;
5 use std::sync::{Arc, Mutex};
6 use std::task::Context;
7
8 use anyhow::{bail, format_err, Error};
9 use chrono::{Local, DateTime, Utc, TimeZone};
10 use futures::future::FutureExt;
11 use futures::stream::{StreamExt, TryStreamExt};
12 use serde_json::{json, Value};
13 use tokio::sync::mpsc;
14 use xdg::BaseDirectories;
15
16 use pathpatterns::{MatchEntry, MatchType, PatternFlag};
17 use proxmox::tools::fs::{file_get_contents, file_get_json, replace_file, CreateOptions, image_size};
18 use proxmox::api::{ApiHandler, ApiMethod, RpcEnvironment};
19 use proxmox::api::schema::*;
20 use proxmox::api::cli::*;
21 use proxmox::api::api;
22 use pxar::accessor::{MaybeReady, ReadAt, ReadAtOperation};
23
24 use proxmox_backup::tools;
25 use proxmox_backup::api2::types::*;
26 use proxmox_backup::client::*;
27 use proxmox_backup::pxar::catalog::*;
28 use proxmox_backup::backup::{
29 archive_type,
30 load_and_decrypt_key,
31 verify_chunk_size,
32 ArchiveType,
33 AsyncReadChunk,
34 BackupDir,
35 BackupGroup,
36 BackupManifest,
37 BufferedDynamicReader,
38 CatalogReader,
39 CatalogWriter,
40 CATALOG_NAME,
41 ChunkStream,
42 CryptConfig,
43 DataBlob,
44 DynamicIndexReader,
45 FixedChunkStream,
46 FixedIndexReader,
47 IndexFile,
48 MANIFEST_BLOB_NAME,
49 Shell,
50 };
51
52 mod proxmox_backup_client;
53 use proxmox_backup_client::*;
54
55 const ENV_VAR_PBS_FINGERPRINT: &str = "PBS_FINGERPRINT";
56 const ENV_VAR_PBS_PASSWORD: &str = "PBS_PASSWORD";
57
58
59 pub const REPO_URL_SCHEMA: Schema = StringSchema::new("Repository URL.")
60 .format(&BACKUP_REPO_URL)
61 .max_length(256)
62 .schema();
63
64 pub const KEYFILE_SCHEMA: Schema = StringSchema::new(
65 "Path to encryption key. All data will be encrypted using this key.")
66 .schema();
67
68 const CHUNK_SIZE_SCHEMA: Schema = IntegerSchema::new(
69 "Chunk size in KB. Must be a power of 2.")
70 .minimum(64)
71 .maximum(4096)
72 .default(4096)
73 .schema();
74
75 fn get_default_repository() -> Option<String> {
76 std::env::var("PBS_REPOSITORY").ok()
77 }
78
79 pub fn extract_repository_from_value(
80 param: &Value,
81 ) -> Result<BackupRepository, Error> {
82
83 let repo_url = param["repository"]
84 .as_str()
85 .map(String::from)
86 .or_else(get_default_repository)
87 .ok_or_else(|| format_err!("unable to get (default) repository"))?;
88
89 let repo: BackupRepository = repo_url.parse()?;
90
91 Ok(repo)
92 }
93
94 fn extract_repository_from_map(
95 param: &HashMap<String, String>,
96 ) -> Option<BackupRepository> {
97
98 param.get("repository")
99 .map(String::from)
100 .or_else(get_default_repository)
101 .and_then(|repo_url| repo_url.parse::<BackupRepository>().ok())
102 }
103
104 fn record_repository(repo: &BackupRepository) {
105
106 let base = match BaseDirectories::with_prefix("proxmox-backup") {
107 Ok(v) => v,
108 _ => return,
109 };
110
111 // usually $HOME/.cache/proxmox-backup/repo-list
112 let path = match base.place_cache_file("repo-list") {
113 Ok(v) => v,
114 _ => return,
115 };
116
117 let mut data = file_get_json(&path, None).unwrap_or_else(|_| json!({}));
118
119 let repo = repo.to_string();
120
121 data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 };
122
123 let mut map = serde_json::map::Map::new();
124
125 loop {
126 let mut max_used = 0;
127 let mut max_repo = None;
128 for (repo, count) in data.as_object().unwrap() {
129 if map.contains_key(repo) { continue; }
130 if let Some(count) = count.as_i64() {
131 if count > max_used {
132 max_used = count;
133 max_repo = Some(repo);
134 }
135 }
136 }
137 if let Some(repo) = max_repo {
138 map.insert(repo.to_owned(), json!(max_used));
139 } else {
140 break;
141 }
142 if map.len() > 10 { // store max. 10 repos
143 break;
144 }
145 }
146
147 let new_data = json!(map);
148
149 let _ = replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new());
150 }
151
152 pub fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
153
154 let mut result = vec![];
155
156 let base = match BaseDirectories::with_prefix("proxmox-backup") {
157 Ok(v) => v,
158 _ => return result,
159 };
160
161 // usually $HOME/.cache/proxmox-backup/repo-list
162 let path = match base.place_cache_file("repo-list") {
163 Ok(v) => v,
164 _ => return result,
165 };
166
167 let data = file_get_json(&path, None).unwrap_or_else(|_| json!({}));
168
169 if let Some(map) = data.as_object() {
170 for (repo, _count) in map {
171 result.push(repo.to_owned());
172 }
173 }
174
175 result
176 }
177
178 fn connect(server: &str, userid: &str) -> Result<HttpClient, Error> {
179
180 let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
181
182 use std::env::VarError::*;
183 let password = match std::env::var(ENV_VAR_PBS_PASSWORD) {
184 Ok(p) => Some(p),
185 Err(NotUnicode(_)) => bail!(format!("{} contains bad characters", ENV_VAR_PBS_PASSWORD)),
186 Err(NotPresent) => None,
187 };
188
189 let options = HttpClientOptions::new()
190 .prefix(Some("proxmox-backup".to_string()))
191 .password(password)
192 .interactive(true)
193 .fingerprint(fingerprint)
194 .fingerprint_cache(true)
195 .ticket_cache(true);
196
197 HttpClient::new(server, userid, options)
198 }
199
200 async fn view_task_result(
201 client: HttpClient,
202 result: Value,
203 output_format: &str,
204 ) -> Result<(), Error> {
205 let data = &result["data"];
206 if output_format == "text" {
207 if let Some(upid) = data.as_str() {
208 display_task_log(client, upid, true).await?;
209 }
210 } else {
211 format_and_print_result(&data, &output_format);
212 }
213
214 Ok(())
215 }
216
217 async fn api_datastore_list_snapshots(
218 client: &HttpClient,
219 store: &str,
220 group: Option<BackupGroup>,
221 ) -> Result<Value, Error> {
222
223 let path = format!("api2/json/admin/datastore/{}/snapshots", store);
224
225 let mut args = json!({});
226 if let Some(group) = group {
227 args["backup-type"] = group.backup_type().into();
228 args["backup-id"] = group.backup_id().into();
229 }
230
231 let mut result = client.get(&path, Some(args)).await?;
232
233 Ok(result["data"].take())
234 }
235
236 pub async fn api_datastore_latest_snapshot(
237 client: &HttpClient,
238 store: &str,
239 group: BackupGroup,
240 ) -> Result<(String, String, DateTime<Utc>), Error> {
241
242 let list = api_datastore_list_snapshots(client, store, Some(group.clone())).await?;
243 let mut list: Vec<SnapshotListItem> = serde_json::from_value(list)?;
244
245 if list.is_empty() {
246 bail!("backup group {:?} does not contain any snapshots.", group.group_path());
247 }
248
249 list.sort_unstable_by(|a, b| b.backup_time.cmp(&a.backup_time));
250
251 let backup_time = Utc.timestamp(list[0].backup_time, 0);
252
253 Ok((group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time))
254 }
255
256 async fn backup_directory<P: AsRef<Path>>(
257 client: &BackupWriter,
258 previous_manifest: Option<Arc<BackupManifest>>,
259 dir_path: P,
260 archive_name: &str,
261 chunk_size: Option<usize>,
262 device_set: Option<HashSet<u64>>,
263 verbose: bool,
264 skip_lost_and_found: bool,
265 catalog: Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>,
266 exclude_pattern: Vec<MatchEntry>,
267 entries_max: usize,
268 ) -> Result<BackupStats, Error> {
269
270 let pxar_stream = PxarBackupStream::open(
271 dir_path.as_ref(),
272 device_set,
273 verbose,
274 skip_lost_and_found,
275 catalog,
276 exclude_pattern,
277 entries_max,
278 )?;
279 let mut chunk_stream = ChunkStream::new(pxar_stream, chunk_size);
280
281 let (mut tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks
282
283 let stream = rx
284 .map_err(Error::from);
285
286 // spawn chunker inside a separate task so that it can run parallel
287 tokio::spawn(async move {
288 while let Some(v) = chunk_stream.next().await {
289 let _ = tx.send(v).await;
290 }
291 });
292
293 let stats = client
294 .upload_stream(previous_manifest, archive_name, stream, "dynamic", None)
295 .await?;
296
297 Ok(stats)
298 }
299
300 async fn backup_image<P: AsRef<Path>>(
301 client: &BackupWriter,
302 previous_manifest: Option<Arc<BackupManifest>>,
303 image_path: P,
304 archive_name: &str,
305 image_size: u64,
306 chunk_size: Option<usize>,
307 _verbose: bool,
308 ) -> Result<BackupStats, Error> {
309
310 let path = image_path.as_ref().to_owned();
311
312 let file = tokio::fs::File::open(path).await?;
313
314 let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new())
315 .map_err(Error::from);
316
317 let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024));
318
319 let stats = client
320 .upload_stream(previous_manifest, archive_name, stream, "fixed", Some(image_size))
321 .await?;
322
323 Ok(stats)
324 }
325
326 #[api(
327 input: {
328 properties: {
329 repository: {
330 schema: REPO_URL_SCHEMA,
331 optional: true,
332 },
333 "output-format": {
334 schema: OUTPUT_FORMAT,
335 optional: true,
336 },
337 }
338 }
339 )]
340 /// List backup groups.
341 async fn list_backup_groups(param: Value) -> Result<Value, Error> {
342
343 let output_format = get_output_format(&param);
344
345 let repo = extract_repository_from_value(&param)?;
346
347 let client = connect(repo.host(), repo.user())?;
348
349 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
350
351 let mut result = client.get(&path, None).await?;
352
353 record_repository(&repo);
354
355 let render_group_path = |_v: &Value, record: &Value| -> Result<String, Error> {
356 let item: GroupListItem = serde_json::from_value(record.to_owned())?;
357 let group = BackupGroup::new(item.backup_type, item.backup_id);
358 Ok(group.group_path().to_str().unwrap().to_owned())
359 };
360
361 let render_last_backup = |_v: &Value, record: &Value| -> Result<String, Error> {
362 let item: GroupListItem = serde_json::from_value(record.to_owned())?;
363 let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.last_backup);
364 Ok(snapshot.relative_path().to_str().unwrap().to_owned())
365 };
366
367 let render_files = |_v: &Value, record: &Value| -> Result<String, Error> {
368 let item: GroupListItem = serde_json::from_value(record.to_owned())?;
369 Ok(tools::format::render_backup_file_list(&item.files))
370 };
371
372 let options = default_table_format_options()
373 .sortby("backup-type", false)
374 .sortby("backup-id", false)
375 .column(ColumnConfig::new("backup-id").renderer(render_group_path).header("group"))
376 .column(
377 ColumnConfig::new("last-backup")
378 .renderer(render_last_backup)
379 .header("last snapshot")
380 .right_align(false)
381 )
382 .column(ColumnConfig::new("backup-count"))
383 .column(ColumnConfig::new("files").renderer(render_files));
384
385 let mut data: Value = result["data"].take();
386
387 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_GROUPS;
388
389 format_and_print_result_full(&mut data, info, &output_format, &options);
390
391 Ok(Value::Null)
392 }
393
394 #[api(
395 input: {
396 properties: {
397 repository: {
398 schema: REPO_URL_SCHEMA,
399 optional: true,
400 },
401 group: {
402 type: String,
403 description: "Backup group.",
404 optional: true,
405 },
406 "output-format": {
407 schema: OUTPUT_FORMAT,
408 optional: true,
409 },
410 }
411 }
412 )]
413 /// List backup snapshots.
414 async fn list_snapshots(param: Value) -> Result<Value, Error> {
415
416 let repo = extract_repository_from_value(&param)?;
417
418 let output_format = get_output_format(&param);
419
420 let client = connect(repo.host(), repo.user())?;
421
422 let group: Option<BackupGroup> = if let Some(path) = param["group"].as_str() {
423 Some(path.parse()?)
424 } else {
425 None
426 };
427
428 let mut data = api_datastore_list_snapshots(&client, repo.store(), group).await?;
429
430 record_repository(&repo);
431
432 let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> {
433 let item: SnapshotListItem = serde_json::from_value(record.to_owned())?;
434 let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time);
435 Ok(snapshot.relative_path().to_str().unwrap().to_owned())
436 };
437
438 let render_files = |_v: &Value, record: &Value| -> Result<String, Error> {
439 let item: SnapshotListItem = serde_json::from_value(record.to_owned())?;
440 let mut filenames = Vec::new();
441 for file in &item.files {
442 filenames.push(file.filename.to_string());
443 }
444 Ok(tools::format::render_backup_file_list(&filenames[..]))
445 };
446
447 let options = default_table_format_options()
448 .sortby("backup-type", false)
449 .sortby("backup-id", false)
450 .sortby("backup-time", false)
451 .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot"))
452 .column(ColumnConfig::new("size"))
453 .column(ColumnConfig::new("files").renderer(render_files))
454 ;
455
456 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOTS;
457
458 format_and_print_result_full(&mut data, info, &output_format, &options);
459
460 Ok(Value::Null)
461 }
462
463 #[api(
464 input: {
465 properties: {
466 repository: {
467 schema: REPO_URL_SCHEMA,
468 optional: true,
469 },
470 snapshot: {
471 type: String,
472 description: "Snapshot path.",
473 },
474 }
475 }
476 )]
477 /// Forget (remove) backup snapshots.
478 async fn forget_snapshots(param: Value) -> Result<Value, Error> {
479
480 let repo = extract_repository_from_value(&param)?;
481
482 let path = tools::required_string_param(&param, "snapshot")?;
483 let snapshot: BackupDir = path.parse()?;
484
485 let mut client = connect(repo.host(), repo.user())?;
486
487 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
488
489 let result = client.delete(&path, Some(json!({
490 "backup-type": snapshot.group().backup_type(),
491 "backup-id": snapshot.group().backup_id(),
492 "backup-time": snapshot.backup_time().timestamp(),
493 }))).await?;
494
495 record_repository(&repo);
496
497 Ok(result)
498 }
499
500 #[api(
501 input: {
502 properties: {
503 repository: {
504 schema: REPO_URL_SCHEMA,
505 optional: true,
506 },
507 }
508 }
509 )]
510 /// Try to login. If successful, store ticket.
511 async fn api_login(param: Value) -> Result<Value, Error> {
512
513 let repo = extract_repository_from_value(&param)?;
514
515 let client = connect(repo.host(), repo.user())?;
516 client.login().await?;
517
518 record_repository(&repo);
519
520 Ok(Value::Null)
521 }
522
523 #[api(
524 input: {
525 properties: {
526 repository: {
527 schema: REPO_URL_SCHEMA,
528 optional: true,
529 },
530 }
531 }
532 )]
533 /// Logout (delete stored ticket).
534 fn api_logout(param: Value) -> Result<Value, Error> {
535
536 let repo = extract_repository_from_value(&param)?;
537
538 delete_ticket_info("proxmox-backup", repo.host(), repo.user())?;
539
540 Ok(Value::Null)
541 }
542
543
544 #[api(
545 input: {
546 properties: {
547 repository: {
548 schema: REPO_URL_SCHEMA,
549 optional: true,
550 },
551 snapshot: {
552 type: String,
553 description: "Snapshot path.",
554 },
555 "output-format": {
556 schema: OUTPUT_FORMAT,
557 optional: true,
558 },
559 }
560 }
561 )]
562 /// List snapshot files.
563 async fn list_snapshot_files(param: Value) -> Result<Value, Error> {
564
565 let repo = extract_repository_from_value(&param)?;
566
567 let path = tools::required_string_param(&param, "snapshot")?;
568 let snapshot: BackupDir = path.parse()?;
569
570 let output_format = get_output_format(&param);
571
572 let client = connect(repo.host(), repo.user())?;
573
574 let path = format!("api2/json/admin/datastore/{}/files", repo.store());
575
576 let mut result = client.get(&path, Some(json!({
577 "backup-type": snapshot.group().backup_type(),
578 "backup-id": snapshot.group().backup_id(),
579 "backup-time": snapshot.backup_time().timestamp(),
580 }))).await?;
581
582 record_repository(&repo);
583
584 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOT_FILES;
585
586 let mut data: Value = result["data"].take();
587
588 let options = default_table_format_options();
589
590 format_and_print_result_full(&mut data, info, &output_format, &options);
591
592 Ok(Value::Null)
593 }
594
595 #[api(
596 input: {
597 properties: {
598 repository: {
599 schema: REPO_URL_SCHEMA,
600 optional: true,
601 },
602 "output-format": {
603 schema: OUTPUT_FORMAT,
604 optional: true,
605 },
606 },
607 },
608 )]
609 /// Start garbage collection for a specific repository.
610 async fn start_garbage_collection(param: Value) -> Result<Value, Error> {
611
612 let repo = extract_repository_from_value(&param)?;
613
614 let output_format = get_output_format(&param);
615
616 let mut client = connect(repo.host(), repo.user())?;
617
618 let path = format!("api2/json/admin/datastore/{}/gc", repo.store());
619
620 let result = client.post(&path, None).await?;
621
622 record_repository(&repo);
623
624 view_task_result(client, result, &output_format).await?;
625
626 Ok(Value::Null)
627 }
628
629 fn spawn_catalog_upload(
630 client: Arc<BackupWriter>
631 ) -> Result<
632 (
633 Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>,
634 tokio::sync::oneshot::Receiver<Result<BackupStats, Error>>
635 ), Error>
636 {
637 let (catalog_tx, catalog_rx) = std::sync::mpsc::sync_channel(10); // allow to buffer 10 writes
638 let catalog_stream = crate::tools::StdChannelStream(catalog_rx);
639 let catalog_chunk_size = 512*1024;
640 let catalog_chunk_stream = ChunkStream::new(catalog_stream, Some(catalog_chunk_size));
641
642 let catalog = Arc::new(Mutex::new(CatalogWriter::new(crate::tools::StdChannelWriter::new(catalog_tx))?));
643
644 let (catalog_result_tx, catalog_result_rx) = tokio::sync::oneshot::channel();
645
646 tokio::spawn(async move {
647 let catalog_upload_result = client
648 .upload_stream(None, CATALOG_NAME, catalog_chunk_stream, "dynamic", None)
649 .await;
650
651 if let Err(ref err) = catalog_upload_result {
652 eprintln!("catalog upload error - {}", err);
653 client.cancel();
654 }
655
656 let _ = catalog_result_tx.send(catalog_upload_result);
657 });
658
659 Ok((catalog, catalog_result_rx))
660 }
661
662 #[api(
663 input: {
664 properties: {
665 backupspec: {
666 type: Array,
667 description: "List of backup source specifications ([<label.ext>:<path>] ...)",
668 items: {
669 schema: BACKUP_SOURCE_SCHEMA,
670 }
671 },
672 repository: {
673 schema: REPO_URL_SCHEMA,
674 optional: true,
675 },
676 "include-dev": {
677 description: "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.",
678 optional: true,
679 items: {
680 type: String,
681 description: "Path to file.",
682 }
683 },
684 keyfile: {
685 schema: KEYFILE_SCHEMA,
686 optional: true,
687 },
688 "skip-lost-and-found": {
689 type: Boolean,
690 description: "Skip lost+found directory.",
691 optional: true,
692 },
693 "backup-type": {
694 schema: BACKUP_TYPE_SCHEMA,
695 optional: true,
696 },
697 "backup-id": {
698 schema: BACKUP_ID_SCHEMA,
699 optional: true,
700 },
701 "backup-time": {
702 schema: BACKUP_TIME_SCHEMA,
703 optional: true,
704 },
705 "chunk-size": {
706 schema: CHUNK_SIZE_SCHEMA,
707 optional: true,
708 },
709 "exclude": {
710 type: Array,
711 description: "List of paths or patterns for matching files to exclude.",
712 optional: true,
713 items: {
714 type: String,
715 description: "Path or match pattern.",
716 }
717 },
718 "entries-max": {
719 type: Integer,
720 description: "Max number of entries to hold in memory.",
721 optional: true,
722 default: proxmox_backup::pxar::ENCODER_MAX_ENTRIES as isize,
723 },
724 "verbose": {
725 type: Boolean,
726 description: "Verbose output.",
727 optional: true,
728 },
729 }
730 }
731 )]
732 /// Create (host) backup.
733 async fn create_backup(
734 param: Value,
735 _info: &ApiMethod,
736 _rpcenv: &mut dyn RpcEnvironment,
737 ) -> Result<Value, Error> {
738
739 let repo = extract_repository_from_value(&param)?;
740
741 let backupspec_list = tools::required_array_param(&param, "backupspec")?;
742
743 let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false);
744
745 let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false);
746
747 let verbose = param["verbose"].as_bool().unwrap_or(false);
748
749 let backup_time_opt = param["backup-time"].as_i64();
750
751 let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize);
752
753 if let Some(size) = chunk_size_opt {
754 verify_chunk_size(size)?;
755 }
756
757 let keyfile = match param["keyfile"].as_str() {
758 Some(path) => Some(PathBuf::from(path)),
759 None => key::optional_default_key_path()?,
760 };
761
762 let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename());
763
764 let backup_type = param["backup-type"].as_str().unwrap_or("host");
765
766 let include_dev = param["include-dev"].as_array();
767
768 let entries_max = param["entries-max"].as_u64()
769 .unwrap_or(proxmox_backup::pxar::ENCODER_MAX_ENTRIES as u64);
770
771 let empty = Vec::new();
772 let exclude_args = param["exclude"].as_array().unwrap_or(&empty);
773
774 let mut pattern_list = Vec::with_capacity(exclude_args.len());
775 for entry in exclude_args {
776 let entry = entry.as_str().ok_or_else(|| format_err!("Invalid pattern string slice"))?;
777 pattern_list.push(
778 MatchEntry::parse_pattern(entry, PatternFlag::PATH_NAME, MatchType::Exclude)
779 .map_err(|err| format_err!("invalid exclude pattern entry: {}", err))?
780 );
781 }
782
783 let mut devices = if all_file_systems { None } else { Some(HashSet::new()) };
784
785 if let Some(include_dev) = include_dev {
786 if all_file_systems {
787 bail!("option 'all-file-systems' conflicts with option 'include-dev'");
788 }
789
790 let mut set = HashSet::new();
791 for path in include_dev {
792 let path = path.as_str().unwrap();
793 let stat = nix::sys::stat::stat(path)
794 .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?;
795 set.insert(stat.st_dev);
796 }
797 devices = Some(set);
798 }
799
800 let mut upload_list = vec![];
801
802 for backupspec in backupspec_list {
803 let spec = parse_backup_specification(backupspec.as_str().unwrap())?;
804 let filename = &spec.config_string;
805 let target = &spec.archive_name;
806
807 use std::os::unix::fs::FileTypeExt;
808
809 let metadata = std::fs::metadata(filename)
810 .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?;
811 let file_type = metadata.file_type();
812
813 match spec.spec_type {
814 BackupSpecificationType::PXAR => {
815 if !file_type.is_dir() {
816 bail!("got unexpected file type (expected directory)");
817 }
818 upload_list.push((BackupSpecificationType::PXAR, filename.to_owned(), format!("{}.didx", target), 0));
819 }
820 BackupSpecificationType::IMAGE => {
821 if !(file_type.is_file() || file_type.is_block_device()) {
822 bail!("got unexpected file type (expected file or block device)");
823 }
824
825 let size = image_size(&PathBuf::from(filename))?;
826
827 if size == 0 { bail!("got zero-sized file '{}'", filename); }
828
829 upload_list.push((BackupSpecificationType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size));
830 }
831 BackupSpecificationType::CONFIG => {
832 if !file_type.is_file() {
833 bail!("got unexpected file type (expected regular file)");
834 }
835 upload_list.push((BackupSpecificationType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len()));
836 }
837 BackupSpecificationType::LOGFILE => {
838 if !file_type.is_file() {
839 bail!("got unexpected file type (expected regular file)");
840 }
841 upload_list.push((BackupSpecificationType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len()));
842 }
843 }
844 }
845
846 let backup_time = Utc.timestamp(backup_time_opt.unwrap_or_else(|| Utc::now().timestamp()), 0);
847
848 let client = connect(repo.host(), repo.user())?;
849 record_repository(&repo);
850
851 println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time));
852
853 println!("Client name: {}", proxmox::tools::nodename());
854
855 let start_time = Local::now();
856
857 println!("Starting protocol: {}", start_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
858
859 let (crypt_config, rsa_encrypted_key) = match keyfile {
860 None => (None, None),
861 Some(path) => {
862 let (key, created) = load_and_decrypt_key(&path, &key::get_encryption_key_password)?;
863
864 let crypt_config = CryptConfig::new(key)?;
865
866 let path = master_pubkey_path()?;
867 if path.exists() {
868 let pem_data = file_get_contents(&path)?;
869 let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
870 let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?;
871 (Some(Arc::new(crypt_config)), Some(enc_key))
872 } else {
873 (Some(Arc::new(crypt_config)), None)
874 }
875 }
876 };
877
878 let is_encrypted = Some(crypt_config.is_some());
879
880 let client = BackupWriter::start(
881 client,
882 crypt_config.clone(),
883 repo.store(),
884 backup_type,
885 &backup_id,
886 backup_time,
887 verbose,
888 ).await?;
889
890 let previous_manifest = if let Ok(previous_manifest) = client.download_previous_manifest().await {
891 Some(Arc::new(previous_manifest))
892 } else {
893 None
894 };
895
896 let snapshot = BackupDir::new(backup_type, backup_id, backup_time.timestamp());
897 let mut manifest = BackupManifest::new(snapshot);
898
899 let mut catalog = None;
900 let mut catalog_result_tx = None;
901
902 for (backup_type, filename, target, size) in upload_list {
903 match backup_type {
904 BackupSpecificationType::CONFIG => {
905 println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target);
906 let stats = client
907 .upload_blob_from_file(&filename, &target, true, Some(true))
908 .await?;
909 manifest.add_file(target, stats.size, stats.csum, is_encrypted)?;
910 }
911 BackupSpecificationType::LOGFILE => { // fixme: remove - not needed anymore ?
912 println!("Upload log file '{}' to '{:?}' as {}", filename, repo, target);
913 let stats = client
914 .upload_blob_from_file(&filename, &target, true, Some(true))
915 .await?;
916 manifest.add_file(target, stats.size, stats.csum, is_encrypted)?;
917 }
918 BackupSpecificationType::PXAR => {
919 // start catalog upload on first use
920 if catalog.is_none() {
921 let (cat, res) = spawn_catalog_upload(client.clone())?;
922 catalog = Some(cat);
923 catalog_result_tx = Some(res);
924 }
925 let catalog = catalog.as_ref().unwrap();
926
927 println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target);
928 catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?;
929 let stats = backup_directory(
930 &client,
931 previous_manifest.clone(),
932 &filename,
933 &target,
934 chunk_size_opt,
935 devices.clone(),
936 verbose,
937 skip_lost_and_found,
938 catalog.clone(),
939 pattern_list.clone(),
940 entries_max as usize,
941 ).await?;
942 manifest.add_file(target, stats.size, stats.csum, is_encrypted)?;
943 catalog.lock().unwrap().end_directory()?;
944 }
945 BackupSpecificationType::IMAGE => {
946 println!("Upload image '{}' to '{:?}' as {}", filename, repo, target);
947 let stats = backup_image(
948 &client,
949 previous_manifest.clone(),
950 &filename,
951 &target,
952 size,
953 chunk_size_opt,
954 verbose,
955 ).await?;
956 manifest.add_file(target, stats.size, stats.csum, is_encrypted)?;
957 }
958 }
959 }
960
961 // finalize and upload catalog
962 if let Some(catalog) = catalog {
963 let mutex = Arc::try_unwrap(catalog)
964 .map_err(|_| format_err!("unable to get catalog (still used)"))?;
965 let mut catalog = mutex.into_inner().unwrap();
966
967 catalog.finish()?;
968
969 drop(catalog); // close upload stream
970
971 if let Some(catalog_result_rx) = catalog_result_tx {
972 let stats = catalog_result_rx.await??;
973 manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum, is_encrypted)?;
974 }
975 }
976
977 if let Some(rsa_encrypted_key) = rsa_encrypted_key {
978 let target = "rsa-encrypted.key";
979 println!("Upload RSA encoded key to '{:?}' as {}", repo, target);
980 let stats = client
981 .upload_blob_from_data(rsa_encrypted_key, target, false, None)
982 .await?;
983 manifest.add_file(format!("{}.blob", target), stats.size, stats.csum, is_encrypted)?;
984
985 // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t
986 /*
987 let mut buffer2 = vec![0u8; rsa.size() as usize];
988 let pem_data = file_get_contents("master-private.pem")?;
989 let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?;
990 let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?;
991 println!("TEST {} {:?}", len, buffer2);
992 */
993 }
994
995 // create manifest (index.json)
996 let manifest = manifest.into_json();
997
998 println!("Upload index.json to '{:?}'", repo);
999 let manifest = serde_json::to_string_pretty(&manifest)?.into();
1000 client
1001 .upload_blob_from_data(manifest, MANIFEST_BLOB_NAME, true, Some(true))
1002 .await?;
1003
1004 client.finish().await?;
1005
1006 let end_time = Local::now();
1007 let elapsed = end_time.signed_duration_since(start_time);
1008 println!("Duration: {}", elapsed);
1009
1010 println!("End Time: {}", end_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
1011
1012 Ok(Value::Null)
1013 }
1014
1015 fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1016
1017 let mut result = vec![];
1018
1019 let data: Vec<&str> = arg.splitn(2, ':').collect();
1020
1021 if data.len() != 2 {
1022 result.push(String::from("root.pxar:/"));
1023 result.push(String::from("etc.pxar:/etc"));
1024 return result;
1025 }
1026
1027 let files = tools::complete_file_name(data[1], param);
1028
1029 for file in files {
1030 result.push(format!("{}:{}", data[0], file));
1031 }
1032
1033 result
1034 }
1035
1036 async fn dump_image<W: Write>(
1037 client: Arc<BackupReader>,
1038 crypt_config: Option<Arc<CryptConfig>>,
1039 index: FixedIndexReader,
1040 mut writer: W,
1041 verbose: bool,
1042 ) -> Result<(), Error> {
1043
1044 let most_used = index.find_most_used_chunks(8);
1045
1046 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1047
1048 // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy
1049 // and thus slows down reading. Instead, directly use RemoteChunkReader
1050 let mut per = 0;
1051 let mut bytes = 0;
1052 let start_time = std::time::Instant::now();
1053
1054 for pos in 0..index.index_count() {
1055 let digest = index.index_digest(pos).unwrap();
1056 let raw_data = chunk_reader.read_chunk(&digest).await?;
1057 writer.write_all(&raw_data)?;
1058 bytes += raw_data.len();
1059 if verbose {
1060 let next_per = ((pos+1)*100)/index.index_count();
1061 if per != next_per {
1062 eprintln!("progress {}% (read {} bytes, duration {} sec)",
1063 next_per, bytes, start_time.elapsed().as_secs());
1064 per = next_per;
1065 }
1066 }
1067 }
1068
1069 let end_time = std::time::Instant::now();
1070 let elapsed = end_time.duration_since(start_time);
1071 eprintln!("restore image complete (bytes={}, duration={:.2}s, speed={:.2}MB/s)",
1072 bytes,
1073 elapsed.as_secs_f64(),
1074 bytes as f64/(1024.0*1024.0*elapsed.as_secs_f64())
1075 );
1076
1077
1078 Ok(())
1079 }
1080
1081 fn parse_archive_type(name: &str) -> (String, ArchiveType) {
1082 if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") {
1083 (name.into(), archive_type(name).unwrap())
1084 } else if name.ends_with(".pxar") {
1085 (format!("{}.didx", name), ArchiveType::DynamicIndex)
1086 } else if name.ends_with(".img") {
1087 (format!("{}.fidx", name), ArchiveType::FixedIndex)
1088 } else {
1089 (format!("{}.blob", name), ArchiveType::Blob)
1090 }
1091 }
1092
1093 #[api(
1094 input: {
1095 properties: {
1096 repository: {
1097 schema: REPO_URL_SCHEMA,
1098 optional: true,
1099 },
1100 snapshot: {
1101 type: String,
1102 description: "Group/Snapshot path.",
1103 },
1104 "archive-name": {
1105 description: "Backup archive name.",
1106 type: String,
1107 },
1108 target: {
1109 type: String,
1110 description: r###"Target directory path. Use '-' to write to standard output.
1111
1112 We do not extraxt '.pxar' archives when writing to standard output.
1113
1114 "###
1115 },
1116 "allow-existing-dirs": {
1117 type: Boolean,
1118 description: "Do not fail if directories already exists.",
1119 optional: true,
1120 },
1121 keyfile: {
1122 schema: KEYFILE_SCHEMA,
1123 optional: true,
1124 },
1125 }
1126 }
1127 )]
1128 /// Restore backup repository.
1129 async fn restore(param: Value) -> Result<Value, Error> {
1130 let repo = extract_repository_from_value(&param)?;
1131
1132 let verbose = param["verbose"].as_bool().unwrap_or(false);
1133
1134 let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false);
1135
1136 let archive_name = tools::required_string_param(&param, "archive-name")?;
1137
1138 let client = connect(repo.host(), repo.user())?;
1139
1140 record_repository(&repo);
1141
1142 let path = tools::required_string_param(&param, "snapshot")?;
1143
1144 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
1145 let group: BackupGroup = path.parse()?;
1146 api_datastore_latest_snapshot(&client, repo.store(), group).await?
1147 } else {
1148 let snapshot: BackupDir = path.parse()?;
1149 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
1150 };
1151
1152 let target = tools::required_string_param(&param, "target")?;
1153 let target = if target == "-" { None } else { Some(target) };
1154
1155 let keyfile = match param["keyfile"].as_str() {
1156 Some(path) => Some(PathBuf::from(path)),
1157 None => key::optional_default_key_path()?,
1158 };
1159
1160 let crypt_config = match keyfile {
1161 None => None,
1162 Some(path) => {
1163 let (key, _) = load_and_decrypt_key(&path, &key::get_encryption_key_password)?;
1164 Some(Arc::new(CryptConfig::new(key)?))
1165 }
1166 };
1167
1168 let client = BackupReader::start(
1169 client,
1170 crypt_config.clone(),
1171 repo.store(),
1172 &backup_type,
1173 &backup_id,
1174 backup_time,
1175 true,
1176 ).await?;
1177
1178 let manifest = client.download_manifest().await?;
1179
1180 let (archive_name, archive_type) = parse_archive_type(archive_name);
1181
1182 if archive_name == MANIFEST_BLOB_NAME {
1183 let backup_index_data = manifest.into_json().to_string();
1184 if let Some(target) = target {
1185 replace_file(target, backup_index_data.as_bytes(), CreateOptions::new())?;
1186 } else {
1187 let stdout = std::io::stdout();
1188 let mut writer = stdout.lock();
1189 writer.write_all(backup_index_data.as_bytes())
1190 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1191 }
1192
1193 } else if archive_type == ArchiveType::Blob {
1194
1195 let mut reader = client.download_blob(&manifest, &archive_name).await?;
1196
1197 if let Some(target) = target {
1198 let mut writer = std::fs::OpenOptions::new()
1199 .write(true)
1200 .create(true)
1201 .create_new(true)
1202 .open(target)
1203 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
1204 std::io::copy(&mut reader, &mut writer)?;
1205 } else {
1206 let stdout = std::io::stdout();
1207 let mut writer = stdout.lock();
1208 std::io::copy(&mut reader, &mut writer)
1209 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1210 }
1211
1212 } else if archive_type == ArchiveType::DynamicIndex {
1213
1214 let index = client.download_dynamic_index(&manifest, &archive_name).await?;
1215
1216 let most_used = index.find_most_used_chunks(8);
1217
1218 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1219
1220 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
1221
1222 if let Some(target) = target {
1223 proxmox_backup::pxar::extract_archive(
1224 pxar::decoder::Decoder::from_std(reader)?,
1225 Path::new(target),
1226 &[],
1227 proxmox_backup::pxar::Flags::DEFAULT,
1228 allow_existing_dirs,
1229 |path| {
1230 if verbose {
1231 println!("{:?}", path);
1232 }
1233 },
1234 )
1235 .map_err(|err| format_err!("error extracting archive - {}", err))?;
1236 } else {
1237 let mut writer = std::fs::OpenOptions::new()
1238 .write(true)
1239 .open("/dev/stdout")
1240 .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?;
1241
1242 std::io::copy(&mut reader, &mut writer)
1243 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1244 }
1245 } else if archive_type == ArchiveType::FixedIndex {
1246
1247 let index = client.download_fixed_index(&manifest, &archive_name).await?;
1248
1249 let mut writer = if let Some(target) = target {
1250 std::fs::OpenOptions::new()
1251 .write(true)
1252 .create(true)
1253 .create_new(true)
1254 .open(target)
1255 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?
1256 } else {
1257 std::fs::OpenOptions::new()
1258 .write(true)
1259 .open("/dev/stdout")
1260 .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?
1261 };
1262
1263 dump_image(client.clone(), crypt_config.clone(), index, &mut writer, verbose).await?;
1264 }
1265
1266 Ok(Value::Null)
1267 }
1268
1269 #[api(
1270 input: {
1271 properties: {
1272 repository: {
1273 schema: REPO_URL_SCHEMA,
1274 optional: true,
1275 },
1276 snapshot: {
1277 type: String,
1278 description: "Group/Snapshot path.",
1279 },
1280 logfile: {
1281 type: String,
1282 description: "The path to the log file you want to upload.",
1283 },
1284 keyfile: {
1285 schema: KEYFILE_SCHEMA,
1286 optional: true,
1287 },
1288 }
1289 }
1290 )]
1291 /// Upload backup log file.
1292 async fn upload_log(param: Value) -> Result<Value, Error> {
1293
1294 let logfile = tools::required_string_param(&param, "logfile")?;
1295 let repo = extract_repository_from_value(&param)?;
1296
1297 let snapshot = tools::required_string_param(&param, "snapshot")?;
1298 let snapshot: BackupDir = snapshot.parse()?;
1299
1300 let mut client = connect(repo.host(), repo.user())?;
1301
1302 let keyfile = match param["keyfile"].as_str() {
1303 Some(path) => Some(PathBuf::from(path)),
1304 None => key::optional_default_key_path()?,
1305 };
1306
1307 let crypt_config = match keyfile {
1308 None => None,
1309 Some(path) => {
1310 let (key, _created) = load_and_decrypt_key(&path, &key::get_encryption_key_password)?;
1311 let crypt_config = CryptConfig::new(key)?;
1312 Some(Arc::new(crypt_config))
1313 }
1314 };
1315
1316 let data = file_get_contents(logfile)?;
1317
1318 let blob = DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?;
1319
1320 let raw_data = blob.into_inner();
1321
1322 let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store());
1323
1324 let args = json!({
1325 "backup-type": snapshot.group().backup_type(),
1326 "backup-id": snapshot.group().backup_id(),
1327 "backup-time": snapshot.backup_time().timestamp(),
1328 });
1329
1330 let body = hyper::Body::from(raw_data);
1331
1332 client.upload("application/octet-stream", body, &path, Some(args)).await
1333 }
1334
1335 const API_METHOD_PRUNE: ApiMethod = ApiMethod::new(
1336 &ApiHandler::Async(&prune),
1337 &ObjectSchema::new(
1338 "Prune a backup repository.",
1339 &proxmox_backup::add_common_prune_prameters!([
1340 ("dry-run", true, &BooleanSchema::new(
1341 "Just show what prune would do, but do not delete anything.")
1342 .schema()),
1343 ("group", false, &StringSchema::new("Backup group.").schema()),
1344 ], [
1345 ("output-format", true, &OUTPUT_FORMAT),
1346 (
1347 "quiet",
1348 true,
1349 &BooleanSchema::new("Minimal output - only show removals.")
1350 .schema()
1351 ),
1352 ("repository", true, &REPO_URL_SCHEMA),
1353 ])
1354 )
1355 );
1356
1357 fn prune<'a>(
1358 param: Value,
1359 _info: &ApiMethod,
1360 _rpcenv: &'a mut dyn RpcEnvironment,
1361 ) -> proxmox::api::ApiFuture<'a> {
1362 async move {
1363 prune_async(param).await
1364 }.boxed()
1365 }
1366
1367 async fn prune_async(mut param: Value) -> Result<Value, Error> {
1368 let repo = extract_repository_from_value(&param)?;
1369
1370 let mut client = connect(repo.host(), repo.user())?;
1371
1372 let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
1373
1374 let group = tools::required_string_param(&param, "group")?;
1375 let group: BackupGroup = group.parse()?;
1376
1377 let output_format = get_output_format(&param);
1378
1379 let quiet = param["quiet"].as_bool().unwrap_or(false);
1380
1381 param.as_object_mut().unwrap().remove("repository");
1382 param.as_object_mut().unwrap().remove("group");
1383 param.as_object_mut().unwrap().remove("output-format");
1384 param.as_object_mut().unwrap().remove("quiet");
1385
1386 param["backup-type"] = group.backup_type().into();
1387 param["backup-id"] = group.backup_id().into();
1388
1389 let mut result = client.post(&path, Some(param)).await?;
1390
1391 record_repository(&repo);
1392
1393 let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> {
1394 let item: PruneListItem = serde_json::from_value(record.to_owned())?;
1395 let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time);
1396 Ok(snapshot.relative_path().to_str().unwrap().to_owned())
1397 };
1398
1399 let render_prune_action = |v: &Value, _record: &Value| -> Result<String, Error> {
1400 Ok(match v.as_bool() {
1401 Some(true) => "keep",
1402 Some(false) => "remove",
1403 None => "unknown",
1404 }.to_string())
1405 };
1406
1407 let options = default_table_format_options()
1408 .sortby("backup-type", false)
1409 .sortby("backup-id", false)
1410 .sortby("backup-time", false)
1411 .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot"))
1412 .column(ColumnConfig::new("backup-time").renderer(tools::format::render_epoch).header("date"))
1413 .column(ColumnConfig::new("keep").renderer(render_prune_action).header("action"))
1414 ;
1415
1416 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_PRUNE;
1417
1418 let mut data = result["data"].take();
1419
1420 if quiet {
1421 let list: Vec<Value> = data.as_array().unwrap().iter().filter(|item| {
1422 item["keep"].as_bool() == Some(false)
1423 }).map(|v| v.clone()).collect();
1424 data = list.into();
1425 }
1426
1427 format_and_print_result_full(&mut data, info, &output_format, &options);
1428
1429 Ok(Value::Null)
1430 }
1431
1432 #[api(
1433 input: {
1434 properties: {
1435 repository: {
1436 schema: REPO_URL_SCHEMA,
1437 optional: true,
1438 },
1439 "output-format": {
1440 schema: OUTPUT_FORMAT,
1441 optional: true,
1442 },
1443 }
1444 }
1445 )]
1446 /// Get repository status.
1447 async fn status(param: Value) -> Result<Value, Error> {
1448
1449 let repo = extract_repository_from_value(&param)?;
1450
1451 let output_format = get_output_format(&param);
1452
1453 let client = connect(repo.host(), repo.user())?;
1454
1455 let path = format!("api2/json/admin/datastore/{}/status", repo.store());
1456
1457 let mut result = client.get(&path, None).await?;
1458 let mut data = result["data"].take();
1459
1460 record_repository(&repo);
1461
1462 let render_total_percentage = |v: &Value, record: &Value| -> Result<String, Error> {
1463 let v = v.as_u64().unwrap();
1464 let total = record["total"].as_u64().unwrap();
1465 let roundup = total/200;
1466 let per = ((v+roundup)*100)/total;
1467 let info = format!(" ({} %)", per);
1468 Ok(format!("{} {:>8}", v, info))
1469 };
1470
1471 let options = default_table_format_options()
1472 .noheader(true)
1473 .column(ColumnConfig::new("total").renderer(render_total_percentage))
1474 .column(ColumnConfig::new("used").renderer(render_total_percentage))
1475 .column(ColumnConfig::new("avail").renderer(render_total_percentage));
1476
1477 let schema = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_STATUS;
1478
1479 format_and_print_result_full(&mut data, schema, &output_format, &options);
1480
1481 Ok(Value::Null)
1482 }
1483
1484 // like get, but simply ignore errors and return Null instead
1485 async fn try_get(repo: &BackupRepository, url: &str) -> Value {
1486
1487 let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
1488 let password = std::env::var(ENV_VAR_PBS_PASSWORD).ok();
1489
1490 let options = HttpClientOptions::new()
1491 .prefix(Some("proxmox-backup".to_string()))
1492 .password(password)
1493 .interactive(false)
1494 .fingerprint(fingerprint)
1495 .fingerprint_cache(true)
1496 .ticket_cache(true);
1497
1498 let client = match HttpClient::new(repo.host(), repo.user(), options) {
1499 Ok(v) => v,
1500 _ => return Value::Null,
1501 };
1502
1503 let mut resp = match client.get(url, None).await {
1504 Ok(v) => v,
1505 _ => return Value::Null,
1506 };
1507
1508 if let Some(map) = resp.as_object_mut() {
1509 if let Some(data) = map.remove("data") {
1510 return data;
1511 }
1512 }
1513 Value::Null
1514 }
1515
1516 fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1517 proxmox_backup::tools::runtime::main(async { complete_backup_group_do(param).await })
1518 }
1519
1520 async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> {
1521
1522 let mut result = vec![];
1523
1524 let repo = match extract_repository_from_map(param) {
1525 Some(v) => v,
1526 _ => return result,
1527 };
1528
1529 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
1530
1531 let data = try_get(&repo, &path).await;
1532
1533 if let Some(list) = data.as_array() {
1534 for item in list {
1535 if let (Some(backup_id), Some(backup_type)) =
1536 (item["backup-id"].as_str(), item["backup-type"].as_str())
1537 {
1538 result.push(format!("{}/{}", backup_type, backup_id));
1539 }
1540 }
1541 }
1542
1543 result
1544 }
1545
1546 pub fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1547 proxmox_backup::tools::runtime::main(async { complete_group_or_snapshot_do(arg, param).await })
1548 }
1549
1550 async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1551
1552 if arg.matches('/').count() < 2 {
1553 let groups = complete_backup_group_do(param).await;
1554 let mut result = vec![];
1555 for group in groups {
1556 result.push(group.to_string());
1557 result.push(format!("{}/", group));
1558 }
1559 return result;
1560 }
1561
1562 complete_backup_snapshot_do(param).await
1563 }
1564
1565 fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1566 proxmox_backup::tools::runtime::main(async { complete_backup_snapshot_do(param).await })
1567 }
1568
1569 async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> {
1570
1571 let mut result = vec![];
1572
1573 let repo = match extract_repository_from_map(param) {
1574 Some(v) => v,
1575 _ => return result,
1576 };
1577
1578 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
1579
1580 let data = try_get(&repo, &path).await;
1581
1582 if let Some(list) = data.as_array() {
1583 for item in list {
1584 if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
1585 (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64())
1586 {
1587 let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
1588 result.push(snapshot.relative_path().to_str().unwrap().to_owned());
1589 }
1590 }
1591 }
1592
1593 result
1594 }
1595
1596 fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1597 proxmox_backup::tools::runtime::main(async { complete_server_file_name_do(param).await })
1598 }
1599
1600 async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> {
1601
1602 let mut result = vec![];
1603
1604 let repo = match extract_repository_from_map(param) {
1605 Some(v) => v,
1606 _ => return result,
1607 };
1608
1609 let snapshot: BackupDir = match param.get("snapshot") {
1610 Some(path) => {
1611 match path.parse() {
1612 Ok(v) => v,
1613 _ => return result,
1614 }
1615 }
1616 _ => return result,
1617 };
1618
1619 let query = tools::json_object_to_query(json!({
1620 "backup-type": snapshot.group().backup_type(),
1621 "backup-id": snapshot.group().backup_id(),
1622 "backup-time": snapshot.backup_time().timestamp(),
1623 })).unwrap();
1624
1625 let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query);
1626
1627 let data = try_get(&repo, &path).await;
1628
1629 if let Some(list) = data.as_array() {
1630 for item in list {
1631 if let Some(filename) = item["filename"].as_str() {
1632 result.push(filename.to_owned());
1633 }
1634 }
1635 }
1636
1637 result
1638 }
1639
1640 fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1641 complete_server_file_name(arg, param)
1642 .iter()
1643 .map(|v| tools::format::strip_server_file_expenstion(&v))
1644 .collect()
1645 }
1646
1647 pub fn complete_pxar_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1648 complete_server_file_name(arg, param)
1649 .iter()
1650 .filter_map(|v| {
1651 let name = tools::format::strip_server_file_expenstion(&v);
1652 if name.ends_with(".pxar") {
1653 Some(name)
1654 } else {
1655 None
1656 }
1657 })
1658 .collect()
1659 }
1660
1661 fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
1662
1663 let mut result = vec![];
1664
1665 let mut size = 64;
1666 loop {
1667 result.push(size.to_string());
1668 size *= 2;
1669 if size > 4096 { break; }
1670 }
1671
1672 result
1673 }
1674
1675 fn master_pubkey_path() -> Result<PathBuf, Error> {
1676 let base = BaseDirectories::with_prefix("proxmox-backup")?;
1677
1678 // usually $HOME/.config/proxmox-backup/master-public.pem
1679 let path = base.place_config_file("master-public.pem")?;
1680
1681 Ok(path)
1682 }
1683
1684 use proxmox_backup::client::RemoteChunkReader;
1685 /// This is a workaround until we have cleaned up the chunk/reader/... infrastructure for better
1686 /// async use!
1687 ///
1688 /// Ideally BufferedDynamicReader gets replaced so the LruCache maps to `BroadcastFuture<Chunk>`,
1689 /// so that we can properly access it from multiple threads simultaneously while not issuing
1690 /// duplicate simultaneous reads over http.
1691 pub struct BufferedDynamicReadAt {
1692 inner: Mutex<BufferedDynamicReader<RemoteChunkReader>>,
1693 }
1694
1695 impl BufferedDynamicReadAt {
1696 fn new(inner: BufferedDynamicReader<RemoteChunkReader>) -> Self {
1697 Self {
1698 inner: Mutex::new(inner),
1699 }
1700 }
1701 }
1702
1703 impl ReadAt for BufferedDynamicReadAt {
1704 fn start_read_at<'a>(
1705 self: Pin<&'a Self>,
1706 _cx: &mut Context,
1707 buf: &'a mut [u8],
1708 offset: u64,
1709 ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> {
1710 use std::io::Read;
1711 MaybeReady::Ready(tokio::task::block_in_place(move || {
1712 let mut reader = self.inner.lock().unwrap();
1713 reader.seek(SeekFrom::Start(offset))?;
1714 Ok(reader.read(buf)?)
1715 }))
1716 }
1717
1718 fn poll_complete<'a>(
1719 self: Pin<&'a Self>,
1720 _op: ReadAtOperation<'a>,
1721 ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> {
1722 panic!("LocalDynamicReadAt::start_read_at returned Pending");
1723 }
1724 }
1725
1726 fn main() {
1727
1728 let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP)
1729 .arg_param(&["backupspec"])
1730 .completion_cb("repository", complete_repository)
1731 .completion_cb("backupspec", complete_backup_source)
1732 .completion_cb("keyfile", tools::complete_file_name)
1733 .completion_cb("chunk-size", complete_chunk_size);
1734
1735 let benchmark_cmd_def = CliCommand::new(&API_METHOD_BENCHMARK)
1736 .completion_cb("repository", complete_repository)
1737 .completion_cb("keyfile", tools::complete_file_name);
1738
1739 let upload_log_cmd_def = CliCommand::new(&API_METHOD_UPLOAD_LOG)
1740 .arg_param(&["snapshot", "logfile"])
1741 .completion_cb("snapshot", complete_backup_snapshot)
1742 .completion_cb("logfile", tools::complete_file_name)
1743 .completion_cb("keyfile", tools::complete_file_name)
1744 .completion_cb("repository", complete_repository);
1745
1746 let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS)
1747 .completion_cb("repository", complete_repository);
1748
1749 let snapshots_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOTS)
1750 .arg_param(&["group"])
1751 .completion_cb("group", complete_backup_group)
1752 .completion_cb("repository", complete_repository);
1753
1754 let forget_cmd_def = CliCommand::new(&API_METHOD_FORGET_SNAPSHOTS)
1755 .arg_param(&["snapshot"])
1756 .completion_cb("repository", complete_repository)
1757 .completion_cb("snapshot", complete_backup_snapshot);
1758
1759 let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
1760 .completion_cb("repository", complete_repository);
1761
1762 let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE)
1763 .arg_param(&["snapshot", "archive-name", "target"])
1764 .completion_cb("repository", complete_repository)
1765 .completion_cb("snapshot", complete_group_or_snapshot)
1766 .completion_cb("archive-name", complete_archive_name)
1767 .completion_cb("target", tools::complete_file_name);
1768
1769 let files_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOT_FILES)
1770 .arg_param(&["snapshot"])
1771 .completion_cb("repository", complete_repository)
1772 .completion_cb("snapshot", complete_backup_snapshot);
1773
1774 let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE)
1775 .arg_param(&["group"])
1776 .completion_cb("group", complete_backup_group)
1777 .completion_cb("repository", complete_repository);
1778
1779 let status_cmd_def = CliCommand::new(&API_METHOD_STATUS)
1780 .completion_cb("repository", complete_repository);
1781
1782 let login_cmd_def = CliCommand::new(&API_METHOD_API_LOGIN)
1783 .completion_cb("repository", complete_repository);
1784
1785 let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT)
1786 .completion_cb("repository", complete_repository);
1787
1788 let cmd_def = CliCommandMap::new()
1789 .insert("backup", backup_cmd_def)
1790 .insert("upload-log", upload_log_cmd_def)
1791 .insert("forget", forget_cmd_def)
1792 .insert("garbage-collect", garbage_collect_cmd_def)
1793 .insert("list", list_cmd_def)
1794 .insert("login", login_cmd_def)
1795 .insert("logout", logout_cmd_def)
1796 .insert("prune", prune_cmd_def)
1797 .insert("restore", restore_cmd_def)
1798 .insert("snapshots", snapshots_cmd_def)
1799 .insert("files", files_cmd_def)
1800 .insert("status", status_cmd_def)
1801 .insert("key", key::cli())
1802 .insert("mount", mount_cmd_def())
1803 .insert("catalog", catalog_mgmt_cli())
1804 .insert("task", task_mgmt_cli())
1805 .insert("benchmark", benchmark_cmd_def);
1806
1807 let rpcenv = CliEnvironment::new();
1808 run_cli_command(cmd_def, rpcenv, Some(|future| {
1809 proxmox_backup::tools::runtime::main(future)
1810 }));
1811 }