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