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