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