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