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