]> git.proxmox.com Git - proxmox-backup.git/blob - src/bin/proxmox-backup-client.rs
src/bin/proxmox-backup-manager.rs: avoid compiler warning
[proxmox-backup.git] / src / bin / proxmox-backup-client.rs
1 use failure::*;
2 use nix::unistd::{fork, ForkResult, pipe};
3 use std::os::unix::io::RawFd;
4 use chrono::{Local, DateTime, Utc, TimeZone};
5 use std::path::{Path, PathBuf};
6 use std::collections::{HashSet, HashMap};
7 use std::ffi::OsStr;
8 use std::io::{Write, Seek, SeekFrom};
9 use std::os::unix::fs::OpenOptionsExt;
10
11 use proxmox::{sortable, identity};
12 use proxmox::tools::fs::{file_get_contents, file_get_json, replace_file, CreateOptions, image_size};
13 use proxmox::sys::linux::tty;
14 use proxmox::api::{ApiHandler, ApiMethod, RpcEnvironment};
15 use proxmox::api::schema::*;
16 use proxmox::api::cli::*;
17 use proxmox::api::api;
18
19 use proxmox_backup::tools;
20 use proxmox_backup::api2::types::*;
21 use proxmox_backup::client::*;
22 use proxmox_backup::backup::*;
23 use proxmox_backup::pxar::{ self, catalog::* };
24
25 //use proxmox_backup::backup::image_index::*;
26 //use proxmox_backup::config::datastore;
27 //use proxmox_backup::pxar::encoder::*;
28 //use proxmox_backup::backup::datastore::*;
29
30 use serde_json::{json, Value};
31 //use hyper::Body;
32 use std::sync::{Arc, Mutex};
33 //use regex::Regex;
34 use xdg::BaseDirectories;
35
36 use futures::*;
37 use tokio::sync::mpsc;
38
39 const ENV_VAR_PBS_FINGERPRINT: &str = "PBS_FINGERPRINT";
40 const ENV_VAR_PBS_PASSWORD: &str = "PBS_PASSWORD";
41
42 proxmox::const_regex! {
43 BACKUPSPEC_REGEX = r"^([a-zA-Z0-9_-]+\.(?:pxar|img|conf|log)):(.+)$";
44 }
45
46 const REPO_URL_SCHEMA: Schema = StringSchema::new("Repository URL.")
47 .format(&BACKUP_REPO_URL)
48 .max_length(256)
49 .schema();
50
51 const BACKUP_SOURCE_SCHEMA: Schema = StringSchema::new(
52 "Backup source specification ([<label>:<path>]).")
53 .format(&ApiStringFormat::Pattern(&BACKUPSPEC_REGEX))
54 .schema();
55
56 const KEYFILE_SCHEMA: Schema = StringSchema::new(
57 "Path to encryption key. All data will be encrypted using this key.")
58 .schema();
59
60 const CHUNK_SIZE_SCHEMA: Schema = IntegerSchema::new(
61 "Chunk size in KB. Must be a power of 2.")
62 .minimum(64)
63 .maximum(4096)
64 .default(4096)
65 .schema();
66
67 fn get_default_repository() -> Option<String> {
68 std::env::var("PBS_REPOSITORY").ok()
69 }
70
71 fn extract_repository_from_value(
72 param: &Value,
73 ) -> Result<BackupRepository, Error> {
74
75 let repo_url = param["repository"]
76 .as_str()
77 .map(String::from)
78 .or_else(get_default_repository)
79 .ok_or_else(|| format_err!("unable to get (default) repository"))?;
80
81 let repo: BackupRepository = repo_url.parse()?;
82
83 Ok(repo)
84 }
85
86 fn extract_repository_from_map(
87 param: &HashMap<String, String>,
88 ) -> Option<BackupRepository> {
89
90 param.get("repository")
91 .map(String::from)
92 .or_else(get_default_repository)
93 .and_then(|repo_url| repo_url.parse::<BackupRepository>().ok())
94 }
95
96 fn record_repository(repo: &BackupRepository) {
97
98 let base = match BaseDirectories::with_prefix("proxmox-backup") {
99 Ok(v) => v,
100 _ => return,
101 };
102
103 // usually $HOME/.cache/proxmox-backup/repo-list
104 let path = match base.place_cache_file("repo-list") {
105 Ok(v) => v,
106 _ => return,
107 };
108
109 let mut data = file_get_json(&path, None).unwrap_or_else(|_| json!({}));
110
111 let repo = repo.to_string();
112
113 data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 };
114
115 let mut map = serde_json::map::Map::new();
116
117 loop {
118 let mut max_used = 0;
119 let mut max_repo = None;
120 for (repo, count) in data.as_object().unwrap() {
121 if map.contains_key(repo) { continue; }
122 if let Some(count) = count.as_i64() {
123 if count > max_used {
124 max_used = count;
125 max_repo = Some(repo);
126 }
127 }
128 }
129 if let Some(repo) = max_repo {
130 map.insert(repo.to_owned(), json!(max_used));
131 } else {
132 break;
133 }
134 if map.len() > 10 { // store max. 10 repos
135 break;
136 }
137 }
138
139 let new_data = json!(map);
140
141 let _ = replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new());
142 }
143
144 fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
145
146 let mut result = vec![];
147
148 let base = match BaseDirectories::with_prefix("proxmox-backup") {
149 Ok(v) => v,
150 _ => return result,
151 };
152
153 // usually $HOME/.cache/proxmox-backup/repo-list
154 let path = match base.place_cache_file("repo-list") {
155 Ok(v) => v,
156 _ => return result,
157 };
158
159 let data = file_get_json(&path, None).unwrap_or_else(|_| json!({}));
160
161 if let Some(map) = data.as_object() {
162 for (repo, _count) in map {
163 result.push(repo.to_owned());
164 }
165 }
166
167 result
168 }
169
170 fn connect(server: &str, userid: &str) -> Result<HttpClient, Error> {
171
172 let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
173
174 use std::env::VarError::*;
175 let password = match std::env::var(ENV_VAR_PBS_PASSWORD) {
176 Ok(p) => Some(p),
177 Err(NotUnicode(_)) => bail!(format!("{} contains bad characters", ENV_VAR_PBS_PASSWORD)),
178 Err(NotPresent) => None,
179 };
180
181 let options = HttpClientOptions::new()
182 .prefix(Some("proxmox-backup".to_string()))
183 .password(password)
184 .interactive(true)
185 .fingerprint(fingerprint)
186 .fingerprint_cache(true)
187 .ticket_cache(true);
188
189 HttpClient::new(server, userid, options)
190 }
191
192 async fn view_task_result(
193 client: HttpClient,
194 result: Value,
195 output_format: &str,
196 ) -> Result<(), Error> {
197 let data = &result["data"];
198 if output_format == "text" {
199 if let Some(upid) = data.as_str() {
200 display_task_log(client, upid, true).await?;
201 }
202 } else {
203 format_and_print_result(&data, &output_format);
204 }
205
206 Ok(())
207 }
208
209 async fn api_datastore_list_snapshots(
210 client: &HttpClient,
211 store: &str,
212 group: Option<BackupGroup>,
213 ) -> Result<Value, Error> {
214
215 let path = format!("api2/json/admin/datastore/{}/snapshots", store);
216
217 let mut args = json!({});
218 if let Some(group) = group {
219 args["backup-type"] = group.backup_type().into();
220 args["backup-id"] = group.backup_id().into();
221 }
222
223 let mut result = client.get(&path, Some(args)).await?;
224
225 Ok(result["data"].take())
226 }
227
228 async fn api_datastore_latest_snapshot(
229 client: &HttpClient,
230 store: &str,
231 group: BackupGroup,
232 ) -> Result<(String, String, DateTime<Utc>), Error> {
233
234 let list = api_datastore_list_snapshots(client, store, Some(group.clone())).await?;
235 let mut list: Vec<SnapshotListItem> = serde_json::from_value(list)?;
236
237 if list.is_empty() {
238 bail!("backup group {:?} does not contain any snapshots.", group.group_path());
239 }
240
241 list.sort_unstable_by(|a, b| b.backup_time.cmp(&a.backup_time));
242
243 let backup_time = Utc.timestamp(list[0].backup_time, 0);
244
245 Ok((group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time))
246 }
247
248
249 async fn backup_directory<P: AsRef<Path>>(
250 client: &BackupWriter,
251 dir_path: P,
252 archive_name: &str,
253 chunk_size: Option<usize>,
254 device_set: Option<HashSet<u64>>,
255 verbose: bool,
256 skip_lost_and_found: bool,
257 crypt_config: Option<Arc<CryptConfig>>,
258 catalog: Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>,
259 exclude_pattern: Vec<pxar::MatchPattern>,
260 entries_max: usize,
261 ) -> Result<BackupStats, Error> {
262
263 let pxar_stream = PxarBackupStream::open(
264 dir_path.as_ref(),
265 device_set,
266 verbose,
267 skip_lost_and_found,
268 catalog,
269 exclude_pattern,
270 entries_max,
271 )?;
272 let mut chunk_stream = ChunkStream::new(pxar_stream, chunk_size);
273
274 let (mut tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks
275
276 let stream = rx
277 .map_err(Error::from);
278
279 // spawn chunker inside a separate task so that it can run parallel
280 tokio::spawn(async move {
281 while let Some(v) = chunk_stream.next().await {
282 let _ = tx.send(v).await;
283 }
284 });
285
286 let stats = client
287 .upload_stream(archive_name, stream, "dynamic", None, crypt_config)
288 .await?;
289
290 Ok(stats)
291 }
292
293 async fn backup_image<P: AsRef<Path>>(
294 client: &BackupWriter,
295 image_path: P,
296 archive_name: &str,
297 image_size: u64,
298 chunk_size: Option<usize>,
299 _verbose: bool,
300 crypt_config: Option<Arc<CryptConfig>>,
301 ) -> Result<BackupStats, Error> {
302
303 let path = image_path.as_ref().to_owned();
304
305 let file = tokio::fs::File::open(path).await?;
306
307 let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new())
308 .map_err(Error::from);
309
310 let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024));
311
312 let stats = client
313 .upload_stream(archive_name, stream, "fixed", Some(image_size), crypt_config)
314 .await?;
315
316 Ok(stats)
317 }
318
319 #[api(
320 input: {
321 properties: {
322 repository: {
323 schema: REPO_URL_SCHEMA,
324 optional: true,
325 },
326 "output-format": {
327 schema: OUTPUT_FORMAT,
328 optional: true,
329 },
330 }
331 }
332 )]
333 /// List backup groups.
334 async fn list_backup_groups(param: Value) -> Result<Value, Error> {
335
336 let output_format = get_output_format(&param);
337
338 let repo = extract_repository_from_value(&param)?;
339
340 let client = connect(repo.host(), repo.user())?;
341
342 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
343
344 let mut result = client.get(&path, None).await?;
345
346 record_repository(&repo);
347
348 let render_group_path = |_v: &Value, record: &Value| -> Result<String, Error> {
349 let item: GroupListItem = serde_json::from_value(record.to_owned())?;
350 let group = BackupGroup::new(item.backup_type, item.backup_id);
351 Ok(group.group_path().to_str().unwrap().to_owned())
352 };
353
354 let render_backup_timestamp = |v: &Value, _record: &Value| -> Result<String, Error> {
355 let epoch = v.as_i64().unwrap();
356 let last_backup = Utc.timestamp(epoch, 0);
357 Ok(BackupDir::backup_time_to_string(last_backup))
358 };
359
360 let render_files = |_v: &Value, record: &Value| -> Result<String, Error> {
361 let item: GroupListItem = serde_json::from_value(record.to_owned())?;
362 Ok(tools::format::render_backup_file_list(&item.files))
363 };
364
365 let options = default_table_format_options()
366 .sortby("backup-type", false)
367 .sortby("backup-id", false)
368 .column(ColumnConfig::new("backup-id").renderer(render_group_path).header("group"))
369 .column(ColumnConfig::new("last-backup").renderer(render_backup_timestamp))
370 .column(ColumnConfig::new("backup-count"))
371 .column(ColumnConfig::new("files").renderer(render_files));
372
373 let mut data: Value = result["data"].take();
374
375 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_GROUPS;
376
377 format_and_print_result_full(&mut data, info, &output_format, &options);
378
379 Ok(Value::Null)
380 }
381
382 #[api(
383 input: {
384 properties: {
385 repository: {
386 schema: REPO_URL_SCHEMA,
387 optional: true,
388 },
389 group: {
390 type: String,
391 description: "Backup group.",
392 optional: true,
393 },
394 "output-format": {
395 schema: OUTPUT_FORMAT,
396 optional: true,
397 },
398 }
399 }
400 )]
401 /// List backup snapshots.
402 async fn list_snapshots(param: Value) -> Result<Value, Error> {
403
404 let repo = extract_repository_from_value(&param)?;
405
406 let output_format = get_output_format(&param);
407
408 let client = connect(repo.host(), repo.user())?;
409
410 let group = if let Some(path) = param["group"].as_str() {
411 Some(BackupGroup::parse(path)?)
412 } else {
413 None
414 };
415
416 let mut data = api_datastore_list_snapshots(&client, repo.store(), group).await?;
417
418 record_repository(&repo);
419
420 let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> {
421 let item: SnapshotListItem = serde_json::from_value(record.to_owned())?;
422 let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time);
423 Ok(snapshot.relative_path().to_str().unwrap().to_owned())
424 };
425
426 let render_files = |_v: &Value, record: &Value| -> Result<String, Error> {
427 let item: SnapshotListItem = serde_json::from_value(record.to_owned())?;
428 Ok(tools::format::render_backup_file_list(&item.files))
429 };
430
431 let options = default_table_format_options()
432 .sortby("backup-type", false)
433 .sortby("backup-id", false)
434 .sortby("backup-time", false)
435 .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot"))
436 .column(ColumnConfig::new("size"))
437 .column(ColumnConfig::new("files").renderer(render_files))
438 ;
439
440 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOTS;
441
442 format_and_print_result_full(&mut data, info, &output_format, &options);
443
444 Ok(Value::Null)
445 }
446
447 #[api(
448 input: {
449 properties: {
450 repository: {
451 schema: REPO_URL_SCHEMA,
452 optional: true,
453 },
454 snapshot: {
455 type: String,
456 description: "Snapshot path.",
457 },
458 }
459 }
460 )]
461 /// Forget (remove) backup snapshots.
462 async fn forget_snapshots(param: Value) -> Result<Value, Error> {
463
464 let repo = extract_repository_from_value(&param)?;
465
466 let path = tools::required_string_param(&param, "snapshot")?;
467 let snapshot = BackupDir::parse(path)?;
468
469 let mut client = connect(repo.host(), repo.user())?;
470
471 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
472
473 let result = client.delete(&path, Some(json!({
474 "backup-type": snapshot.group().backup_type(),
475 "backup-id": snapshot.group().backup_id(),
476 "backup-time": snapshot.backup_time().timestamp(),
477 }))).await?;
478
479 record_repository(&repo);
480
481 Ok(result)
482 }
483
484 #[api(
485 input: {
486 properties: {
487 repository: {
488 schema: REPO_URL_SCHEMA,
489 optional: true,
490 },
491 }
492 }
493 )]
494 /// Try to login. If successful, store ticket.
495 async fn api_login(param: Value) -> Result<Value, Error> {
496
497 let repo = extract_repository_from_value(&param)?;
498
499 let client = connect(repo.host(), repo.user())?;
500 client.login().await?;
501
502 record_repository(&repo);
503
504 Ok(Value::Null)
505 }
506
507 #[api(
508 input: {
509 properties: {
510 repository: {
511 schema: REPO_URL_SCHEMA,
512 optional: true,
513 },
514 }
515 }
516 )]
517 /// Logout (delete stored ticket).
518 fn api_logout(param: Value) -> Result<Value, Error> {
519
520 let repo = extract_repository_from_value(&param)?;
521
522 delete_ticket_info("proxmox-backup", repo.host(), repo.user())?;
523
524 Ok(Value::Null)
525 }
526
527 #[api(
528 input: {
529 properties: {
530 repository: {
531 schema: REPO_URL_SCHEMA,
532 optional: true,
533 },
534 snapshot: {
535 type: String,
536 description: "Snapshot path.",
537 },
538 }
539 }
540 )]
541 /// Dump catalog.
542 async fn dump_catalog(param: Value) -> Result<Value, Error> {
543
544 let repo = extract_repository_from_value(&param)?;
545
546 let path = tools::required_string_param(&param, "snapshot")?;
547 let snapshot = BackupDir::parse(path)?;
548
549 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
550
551 let crypt_config = match keyfile {
552 None => None,
553 Some(path) => {
554 let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
555 Some(Arc::new(CryptConfig::new(key)?))
556 }
557 };
558
559 let client = connect(repo.host(), repo.user())?;
560
561 let client = BackupReader::start(
562 client,
563 crypt_config.clone(),
564 repo.store(),
565 &snapshot.group().backup_type(),
566 &snapshot.group().backup_id(),
567 snapshot.backup_time(),
568 true,
569 ).await?;
570
571 let manifest = client.download_manifest().await?;
572
573 let index = client.download_dynamic_index(&manifest, CATALOG_NAME).await?;
574
575 let most_used = index.find_most_used_chunks(8);
576
577 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
578
579 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
580
581 let mut catalogfile = std::fs::OpenOptions::new()
582 .write(true)
583 .read(true)
584 .custom_flags(libc::O_TMPFILE)
585 .open("/tmp")?;
586
587 std::io::copy(&mut reader, &mut catalogfile)
588 .map_err(|err| format_err!("unable to download catalog - {}", err))?;
589
590 catalogfile.seek(SeekFrom::Start(0))?;
591
592 let mut catalog_reader = CatalogReader::new(catalogfile);
593
594 catalog_reader.dump()?;
595
596 record_repository(&repo);
597
598 Ok(Value::Null)
599 }
600
601 #[api(
602 input: {
603 properties: {
604 repository: {
605 schema: REPO_URL_SCHEMA,
606 optional: true,
607 },
608 snapshot: {
609 type: String,
610 description: "Snapshot path.",
611 },
612 "output-format": {
613 schema: OUTPUT_FORMAT,
614 optional: true,
615 },
616 }
617 }
618 )]
619 /// List snapshot files.
620 async fn list_snapshot_files(param: Value) -> Result<Value, Error> {
621
622 let repo = extract_repository_from_value(&param)?;
623
624 let path = tools::required_string_param(&param, "snapshot")?;
625 let snapshot = BackupDir::parse(path)?;
626
627 let output_format = get_output_format(&param);
628
629 let client = connect(repo.host(), repo.user())?;
630
631 let path = format!("api2/json/admin/datastore/{}/files", repo.store());
632
633 let mut result = client.get(&path, Some(json!({
634 "backup-type": snapshot.group().backup_type(),
635 "backup-id": snapshot.group().backup_id(),
636 "backup-time": snapshot.backup_time().timestamp(),
637 }))).await?;
638
639 record_repository(&repo);
640
641 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOT_FILES;
642
643 let mut data: Value = result["data"].take();
644
645 let options = default_table_format_options();
646
647 format_and_print_result_full(&mut data, info, &output_format, &options);
648
649 Ok(Value::Null)
650 }
651
652 #[api(
653 input: {
654 properties: {
655 repository: {
656 schema: REPO_URL_SCHEMA,
657 optional: true,
658 },
659 "output-format": {
660 schema: OUTPUT_FORMAT,
661 optional: true,
662 },
663 },
664 },
665 )]
666 /// Start garbage collection for a specific repository.
667 async fn start_garbage_collection(param: Value) -> Result<Value, Error> {
668
669 let repo = extract_repository_from_value(&param)?;
670
671 let output_format = get_output_format(&param);
672
673 let mut client = connect(repo.host(), repo.user())?;
674
675 let path = format!("api2/json/admin/datastore/{}/gc", repo.store());
676
677 let result = client.post(&path, None).await?;
678
679 record_repository(&repo);
680
681 view_task_result(client, result, &output_format).await?;
682
683 Ok(Value::Null)
684 }
685
686 fn parse_backupspec(value: &str) -> Result<(&str, &str), Error> {
687
688 if let Some(caps) = (BACKUPSPEC_REGEX.regex_obj)().captures(value) {
689 return Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str()));
690 }
691 bail!("unable to parse directory specification '{}'", value);
692 }
693
694 fn spawn_catalog_upload(
695 client: Arc<BackupWriter>,
696 crypt_config: Option<Arc<CryptConfig>>,
697 ) -> Result<
698 (
699 Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>,
700 tokio::sync::oneshot::Receiver<Result<BackupStats, Error>>
701 ), Error>
702 {
703 let (catalog_tx, catalog_rx) = std::sync::mpsc::sync_channel(10); // allow to buffer 10 writes
704 let catalog_stream = crate::tools::StdChannelStream(catalog_rx);
705 let catalog_chunk_size = 512*1024;
706 let catalog_chunk_stream = ChunkStream::new(catalog_stream, Some(catalog_chunk_size));
707
708 let catalog = Arc::new(Mutex::new(CatalogWriter::new(crate::tools::StdChannelWriter::new(catalog_tx))?));
709
710 let (catalog_result_tx, catalog_result_rx) = tokio::sync::oneshot::channel();
711
712 tokio::spawn(async move {
713 let catalog_upload_result = client
714 .upload_stream(CATALOG_NAME, catalog_chunk_stream, "dynamic", None, crypt_config)
715 .await;
716
717 if let Err(ref err) = catalog_upload_result {
718 eprintln!("catalog upload error - {}", err);
719 client.cancel();
720 }
721
722 let _ = catalog_result_tx.send(catalog_upload_result);
723 });
724
725 Ok((catalog, catalog_result_rx))
726 }
727
728 #[api(
729 input: {
730 properties: {
731 backupspec: {
732 type: Array,
733 description: "List of backup source specifications ([<label.ext>:<path>] ...)",
734 items: {
735 schema: BACKUP_SOURCE_SCHEMA,
736 }
737 },
738 repository: {
739 schema: REPO_URL_SCHEMA,
740 optional: true,
741 },
742 "include-dev": {
743 description: "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.",
744 optional: true,
745 items: {
746 type: String,
747 description: "Path to file.",
748 }
749 },
750 keyfile: {
751 schema: KEYFILE_SCHEMA,
752 optional: true,
753 },
754 "skip-lost-and-found": {
755 type: Boolean,
756 description: "Skip lost+found directory.",
757 optional: true,
758 },
759 "backup-type": {
760 schema: BACKUP_TYPE_SCHEMA,
761 optional: true,
762 },
763 "backup-id": {
764 schema: BACKUP_ID_SCHEMA,
765 optional: true,
766 },
767 "backup-time": {
768 schema: BACKUP_TIME_SCHEMA,
769 optional: true,
770 },
771 "chunk-size": {
772 schema: CHUNK_SIZE_SCHEMA,
773 optional: true,
774 },
775 "exclude": {
776 type: Array,
777 description: "List of paths or patterns for matching files to exclude.",
778 optional: true,
779 items: {
780 type: String,
781 description: "Path or match pattern.",
782 }
783 },
784 "entries-max": {
785 type: Integer,
786 description: "Max number of entries to hold in memory.",
787 optional: true,
788 default: pxar::ENCODER_MAX_ENTRIES as isize,
789 },
790 "verbose": {
791 type: Boolean,
792 description: "Verbose output.",
793 optional: true,
794 },
795 }
796 }
797 )]
798 /// Create (host) backup.
799 async fn create_backup(
800 param: Value,
801 _info: &ApiMethod,
802 _rpcenv: &mut dyn RpcEnvironment,
803 ) -> Result<Value, Error> {
804
805 let repo = extract_repository_from_value(&param)?;
806
807 let backupspec_list = tools::required_array_param(&param, "backupspec")?;
808
809 let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false);
810
811 let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false);
812
813 let verbose = param["verbose"].as_bool().unwrap_or(false);
814
815 let backup_time_opt = param["backup-time"].as_i64();
816
817 let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize);
818
819 if let Some(size) = chunk_size_opt {
820 verify_chunk_size(size)?;
821 }
822
823 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
824
825 let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename());
826
827 let backup_type = param["backup-type"].as_str().unwrap_or("host");
828
829 let include_dev = param["include-dev"].as_array();
830
831 let entries_max = param["entries-max"].as_u64().unwrap_or(pxar::ENCODER_MAX_ENTRIES as u64);
832
833 let empty = Vec::new();
834 let arg_pattern = param["exclude"].as_array().unwrap_or(&empty);
835
836 let mut pattern_list = Vec::with_capacity(arg_pattern.len());
837 for s in arg_pattern {
838 let l = s.as_str().ok_or_else(|| format_err!("Invalid pattern string slice"))?;
839 let p = pxar::MatchPattern::from_line(l.as_bytes())?
840 .ok_or_else(|| format_err!("Invalid match pattern in arguments"))?;
841 pattern_list.push(p);
842 }
843
844 let mut devices = if all_file_systems { None } else { Some(HashSet::new()) };
845
846 if let Some(include_dev) = include_dev {
847 if all_file_systems {
848 bail!("option 'all-file-systems' conflicts with option 'include-dev'");
849 }
850
851 let mut set = HashSet::new();
852 for path in include_dev {
853 let path = path.as_str().unwrap();
854 let stat = nix::sys::stat::stat(path)
855 .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?;
856 set.insert(stat.st_dev);
857 }
858 devices = Some(set);
859 }
860
861 let mut upload_list = vec![];
862
863 enum BackupType { PXAR, IMAGE, CONFIG, LOGFILE };
864
865 let mut upload_catalog = false;
866
867 for backupspec in backupspec_list {
868 let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?;
869
870 use std::os::unix::fs::FileTypeExt;
871
872 let metadata = std::fs::metadata(filename)
873 .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?;
874 let file_type = metadata.file_type();
875
876 let extension = target.rsplit('.').next()
877 .ok_or_else(|| format_err!("missing target file extenion '{}'", target))?;
878
879 match extension {
880 "pxar" => {
881 if !file_type.is_dir() {
882 bail!("got unexpected file type (expected directory)");
883 }
884 upload_list.push((BackupType::PXAR, filename.to_owned(), format!("{}.didx", target), 0));
885 upload_catalog = true;
886 }
887 "img" => {
888
889 if !(file_type.is_file() || file_type.is_block_device()) {
890 bail!("got unexpected file type (expected file or block device)");
891 }
892
893 let size = image_size(&PathBuf::from(filename))?;
894
895 if size == 0 { bail!("got zero-sized file '{}'", filename); }
896
897 upload_list.push((BackupType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size));
898 }
899 "conf" => {
900 if !file_type.is_file() {
901 bail!("got unexpected file type (expected regular file)");
902 }
903 upload_list.push((BackupType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len()));
904 }
905 "log" => {
906 if !file_type.is_file() {
907 bail!("got unexpected file type (expected regular file)");
908 }
909 upload_list.push((BackupType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len()));
910 }
911 _ => {
912 bail!("got unknown archive extension '{}'", extension);
913 }
914 }
915 }
916
917 let backup_time = Utc.timestamp(backup_time_opt.unwrap_or_else(|| Utc::now().timestamp()), 0);
918
919 let client = connect(repo.host(), repo.user())?;
920 record_repository(&repo);
921
922 println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time));
923
924 println!("Client name: {}", proxmox::tools::nodename());
925
926 let start_time = Local::now();
927
928 println!("Starting protocol: {}", start_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
929
930 let (crypt_config, rsa_encrypted_key) = match keyfile {
931 None => (None, None),
932 Some(path) => {
933 let (key, created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
934
935 let crypt_config = CryptConfig::new(key)?;
936
937 let path = master_pubkey_path()?;
938 if path.exists() {
939 let pem_data = file_get_contents(&path)?;
940 let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
941 let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?;
942 (Some(Arc::new(crypt_config)), Some(enc_key))
943 } else {
944 (Some(Arc::new(crypt_config)), None)
945 }
946 }
947 };
948
949 let client = BackupWriter::start(
950 client,
951 repo.store(),
952 backup_type,
953 &backup_id,
954 backup_time,
955 verbose,
956 ).await?;
957
958 let snapshot = BackupDir::new(backup_type, backup_id, backup_time.timestamp());
959 let mut manifest = BackupManifest::new(snapshot);
960
961 let (catalog, catalog_result_rx) = spawn_catalog_upload(client.clone(), crypt_config.clone())?;
962
963 for (backup_type, filename, target, size) in upload_list {
964 match backup_type {
965 BackupType::CONFIG => {
966 println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target);
967 let stats = client
968 .upload_blob_from_file(&filename, &target, crypt_config.clone(), true)
969 .await?;
970 manifest.add_file(target, stats.size, stats.csum)?;
971 }
972 BackupType::LOGFILE => { // fixme: remove - not needed anymore ?
973 println!("Upload log file '{}' to '{:?}' as {}", filename, repo, target);
974 let stats = client
975 .upload_blob_from_file(&filename, &target, crypt_config.clone(), true)
976 .await?;
977 manifest.add_file(target, stats.size, stats.csum)?;
978 }
979 BackupType::PXAR => {
980 println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target);
981 catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?;
982 let stats = backup_directory(
983 &client,
984 &filename,
985 &target,
986 chunk_size_opt,
987 devices.clone(),
988 verbose,
989 skip_lost_and_found,
990 crypt_config.clone(),
991 catalog.clone(),
992 pattern_list.clone(),
993 entries_max as usize,
994 ).await?;
995 manifest.add_file(target, stats.size, stats.csum)?;
996 catalog.lock().unwrap().end_directory()?;
997 }
998 BackupType::IMAGE => {
999 println!("Upload image '{}' to '{:?}' as {}", filename, repo, target);
1000 let stats = backup_image(
1001 &client,
1002 &filename,
1003 &target,
1004 size,
1005 chunk_size_opt,
1006 verbose,
1007 crypt_config.clone(),
1008 ).await?;
1009 manifest.add_file(target, stats.size, stats.csum)?;
1010 }
1011 }
1012 }
1013
1014 // finalize and upload catalog
1015 if upload_catalog {
1016 let mutex = Arc::try_unwrap(catalog)
1017 .map_err(|_| format_err!("unable to get catalog (still used)"))?;
1018 let mut catalog = mutex.into_inner().unwrap();
1019
1020 catalog.finish()?;
1021
1022 drop(catalog); // close upload stream
1023
1024 let stats = catalog_result_rx.await??;
1025
1026 manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum)?;
1027 }
1028
1029 if let Some(rsa_encrypted_key) = rsa_encrypted_key {
1030 let target = "rsa-encrypted.key";
1031 println!("Upload RSA encoded key to '{:?}' as {}", repo, target);
1032 let stats = client
1033 .upload_blob_from_data(rsa_encrypted_key, target, None, false, false)
1034 .await?;
1035 manifest.add_file(format!("{}.blob", target), stats.size, stats.csum)?;
1036
1037 // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t
1038 /*
1039 let mut buffer2 = vec![0u8; rsa.size() as usize];
1040 let pem_data = file_get_contents("master-private.pem")?;
1041 let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?;
1042 let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?;
1043 println!("TEST {} {:?}", len, buffer2);
1044 */
1045 }
1046
1047 // create manifest (index.json)
1048 let manifest = manifest.into_json();
1049
1050 println!("Upload index.json to '{:?}'", repo);
1051 let manifest = serde_json::to_string_pretty(&manifest)?.into();
1052 client
1053 .upload_blob_from_data(manifest, MANIFEST_BLOB_NAME, crypt_config.clone(), true, true)
1054 .await?;
1055
1056 client.finish().await?;
1057
1058 let end_time = Local::now();
1059 let elapsed = end_time.signed_duration_since(start_time);
1060 println!("Duration: {}", elapsed);
1061
1062 println!("End Time: {}", end_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
1063
1064 Ok(Value::Null)
1065 }
1066
1067 fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1068
1069 let mut result = vec![];
1070
1071 let data: Vec<&str> = arg.splitn(2, ':').collect();
1072
1073 if data.len() != 2 {
1074 result.push(String::from("root.pxar:/"));
1075 result.push(String::from("etc.pxar:/etc"));
1076 return result;
1077 }
1078
1079 let files = tools::complete_file_name(data[1], param);
1080
1081 for file in files {
1082 result.push(format!("{}:{}", data[0], file));
1083 }
1084
1085 result
1086 }
1087
1088 fn dump_image<W: Write>(
1089 client: Arc<BackupReader>,
1090 crypt_config: Option<Arc<CryptConfig>>,
1091 index: FixedIndexReader,
1092 mut writer: W,
1093 verbose: bool,
1094 ) -> Result<(), Error> {
1095
1096 let most_used = index.find_most_used_chunks(8);
1097
1098 let mut chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1099
1100 // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy
1101 // and thus slows down reading. Instead, directly use RemoteChunkReader
1102 let mut per = 0;
1103 let mut bytes = 0;
1104 let start_time = std::time::Instant::now();
1105
1106 for pos in 0..index.index_count() {
1107 let digest = index.index_digest(pos).unwrap();
1108 let raw_data = chunk_reader.read_chunk(&digest)?;
1109 writer.write_all(&raw_data)?;
1110 bytes += raw_data.len();
1111 if verbose {
1112 let next_per = ((pos+1)*100)/index.index_count();
1113 if per != next_per {
1114 eprintln!("progress {}% (read {} bytes, duration {} sec)",
1115 next_per, bytes, start_time.elapsed().as_secs());
1116 per = next_per;
1117 }
1118 }
1119 }
1120
1121 let end_time = std::time::Instant::now();
1122 let elapsed = end_time.duration_since(start_time);
1123 eprintln!("restore image complete (bytes={}, duration={:.2}s, speed={:.2}MB/s)",
1124 bytes,
1125 elapsed.as_secs_f64(),
1126 bytes as f64/(1024.0*1024.0*elapsed.as_secs_f64())
1127 );
1128
1129
1130 Ok(())
1131 }
1132
1133 #[api(
1134 input: {
1135 properties: {
1136 repository: {
1137 schema: REPO_URL_SCHEMA,
1138 optional: true,
1139 },
1140 snapshot: {
1141 type: String,
1142 description: "Group/Snapshot path.",
1143 },
1144 "archive-name": {
1145 description: "Backup archive name.",
1146 type: String,
1147 },
1148 target: {
1149 type: String,
1150 description: r###"Target directory path. Use '-' to write to standard output.
1151
1152 We do not extraxt '.pxar' archives when writing to standard output.
1153
1154 "###
1155 },
1156 "allow-existing-dirs": {
1157 type: Boolean,
1158 description: "Do not fail if directories already exists.",
1159 optional: true,
1160 },
1161 keyfile: {
1162 schema: KEYFILE_SCHEMA,
1163 optional: true,
1164 },
1165 }
1166 }
1167 )]
1168 /// Restore backup repository.
1169 async fn restore(param: Value) -> Result<Value, Error> {
1170 let repo = extract_repository_from_value(&param)?;
1171
1172 let verbose = param["verbose"].as_bool().unwrap_or(false);
1173
1174 let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false);
1175
1176 let archive_name = tools::required_string_param(&param, "archive-name")?;
1177
1178 let client = connect(repo.host(), repo.user())?;
1179
1180 record_repository(&repo);
1181
1182 let path = tools::required_string_param(&param, "snapshot")?;
1183
1184 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
1185 let group = BackupGroup::parse(path)?;
1186 api_datastore_latest_snapshot(&client, repo.store(), group).await?
1187 } else {
1188 let snapshot = BackupDir::parse(path)?;
1189 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
1190 };
1191
1192 let target = tools::required_string_param(&param, "target")?;
1193 let target = if target == "-" { None } else { Some(target) };
1194
1195 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
1196
1197 let crypt_config = match keyfile {
1198 None => None,
1199 Some(path) => {
1200 let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
1201 Some(Arc::new(CryptConfig::new(key)?))
1202 }
1203 };
1204
1205 let server_archive_name = if archive_name.ends_with(".pxar") {
1206 format!("{}.didx", archive_name)
1207 } else if archive_name.ends_with(".img") {
1208 format!("{}.fidx", archive_name)
1209 } else {
1210 format!("{}.blob", archive_name)
1211 };
1212
1213 let client = BackupReader::start(
1214 client,
1215 crypt_config.clone(),
1216 repo.store(),
1217 &backup_type,
1218 &backup_id,
1219 backup_time,
1220 true,
1221 ).await?;
1222
1223 let manifest = client.download_manifest().await?;
1224
1225 if server_archive_name == MANIFEST_BLOB_NAME {
1226 let backup_index_data = manifest.into_json().to_string();
1227 if let Some(target) = target {
1228 replace_file(target, backup_index_data.as_bytes(), CreateOptions::new())?;
1229 } else {
1230 let stdout = std::io::stdout();
1231 let mut writer = stdout.lock();
1232 writer.write_all(backup_index_data.as_bytes())
1233 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1234 }
1235
1236 } else if server_archive_name.ends_with(".blob") {
1237
1238 let mut reader = client.download_blob(&manifest, &server_archive_name).await?;
1239
1240 if let Some(target) = target {
1241 let mut writer = std::fs::OpenOptions::new()
1242 .write(true)
1243 .create(true)
1244 .create_new(true)
1245 .open(target)
1246 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
1247 std::io::copy(&mut reader, &mut writer)?;
1248 } else {
1249 let stdout = std::io::stdout();
1250 let mut writer = stdout.lock();
1251 std::io::copy(&mut reader, &mut writer)
1252 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1253 }
1254
1255 } else if server_archive_name.ends_with(".didx") {
1256
1257 let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
1258
1259 let most_used = index.find_most_used_chunks(8);
1260
1261 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1262
1263 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
1264
1265 if let Some(target) = target {
1266
1267 let feature_flags = pxar::flags::DEFAULT;
1268 let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags);
1269 decoder.set_callback(move |path| {
1270 if verbose {
1271 eprintln!("{:?}", path);
1272 }
1273 Ok(())
1274 });
1275 decoder.set_allow_existing_dirs(allow_existing_dirs);
1276
1277 decoder.restore(Path::new(target), &Vec::new())?;
1278 } else {
1279 let mut writer = std::fs::OpenOptions::new()
1280 .write(true)
1281 .open("/dev/stdout")
1282 .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?;
1283
1284 std::io::copy(&mut reader, &mut writer)
1285 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1286 }
1287 } else if server_archive_name.ends_with(".fidx") {
1288
1289 let index = client.download_fixed_index(&manifest, &server_archive_name).await?;
1290
1291 let mut writer = if let Some(target) = target {
1292 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 } else {
1299 std::fs::OpenOptions::new()
1300 .write(true)
1301 .open("/dev/stdout")
1302 .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?
1303 };
1304
1305 dump_image(client.clone(), crypt_config.clone(), index, &mut writer, verbose)?;
1306
1307 } else {
1308 bail!("unknown archive file extension (expected .pxar of .img)");
1309 }
1310
1311 Ok(Value::Null)
1312 }
1313
1314 #[api(
1315 input: {
1316 properties: {
1317 repository: {
1318 schema: REPO_URL_SCHEMA,
1319 optional: true,
1320 },
1321 snapshot: {
1322 type: String,
1323 description: "Group/Snapshot path.",
1324 },
1325 logfile: {
1326 type: String,
1327 description: "The path to the log file you want to upload.",
1328 },
1329 keyfile: {
1330 schema: KEYFILE_SCHEMA,
1331 optional: true,
1332 },
1333 }
1334 }
1335 )]
1336 /// Upload backup log file.
1337 async fn upload_log(param: Value) -> Result<Value, Error> {
1338
1339 let logfile = tools::required_string_param(&param, "logfile")?;
1340 let repo = extract_repository_from_value(&param)?;
1341
1342 let snapshot = tools::required_string_param(&param, "snapshot")?;
1343 let snapshot = BackupDir::parse(snapshot)?;
1344
1345 let mut client = connect(repo.host(), repo.user())?;
1346
1347 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
1348
1349 let crypt_config = match keyfile {
1350 None => None,
1351 Some(path) => {
1352 let (key, _created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
1353 let crypt_config = CryptConfig::new(key)?;
1354 Some(Arc::new(crypt_config))
1355 }
1356 };
1357
1358 let data = file_get_contents(logfile)?;
1359
1360 let blob = DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?;
1361
1362 let raw_data = blob.into_inner();
1363
1364 let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store());
1365
1366 let args = json!({
1367 "backup-type": snapshot.group().backup_type(),
1368 "backup-id": snapshot.group().backup_id(),
1369 "backup-time": snapshot.backup_time().timestamp(),
1370 });
1371
1372 let body = hyper::Body::from(raw_data);
1373
1374 client.upload("application/octet-stream", body, &path, Some(args)).await
1375 }
1376
1377 const API_METHOD_PRUNE: ApiMethod = ApiMethod::new(
1378 &ApiHandler::Async(&prune),
1379 &ObjectSchema::new(
1380 "Prune a backup repository.",
1381 &proxmox_backup::add_common_prune_prameters!([
1382 ("dry-run", true, &BooleanSchema::new(
1383 "Just show what prune would do, but do not delete anything.")
1384 .schema()),
1385 ("group", false, &StringSchema::new("Backup group.").schema()),
1386 ], [
1387 ("output-format", true, &OUTPUT_FORMAT),
1388 ("repository", true, &REPO_URL_SCHEMA),
1389 ])
1390 )
1391 );
1392
1393 fn prune<'a>(
1394 param: Value,
1395 _info: &ApiMethod,
1396 _rpcenv: &'a mut dyn RpcEnvironment,
1397 ) -> proxmox::api::ApiFuture<'a> {
1398 async move {
1399 prune_async(param).await
1400 }.boxed()
1401 }
1402
1403 async fn prune_async(mut param: Value) -> Result<Value, Error> {
1404 let repo = extract_repository_from_value(&param)?;
1405
1406 let mut client = connect(repo.host(), repo.user())?;
1407
1408 let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
1409
1410 let group = tools::required_string_param(&param, "group")?;
1411 let group = BackupGroup::parse(group)?;
1412
1413 let output_format = get_output_format(&param);
1414
1415 param.as_object_mut().unwrap().remove("repository");
1416 param.as_object_mut().unwrap().remove("group");
1417 param.as_object_mut().unwrap().remove("output-format");
1418
1419 param["backup-type"] = group.backup_type().into();
1420 param["backup-id"] = group.backup_id().into();
1421
1422 let result = client.post(&path, Some(param)).await?;
1423
1424 record_repository(&repo);
1425
1426 view_task_result(client, result, &output_format).await?;
1427
1428 Ok(Value::Null)
1429 }
1430
1431 #[api(
1432 input: {
1433 properties: {
1434 repository: {
1435 schema: REPO_URL_SCHEMA,
1436 optional: true,
1437 },
1438 "output-format": {
1439 schema: OUTPUT_FORMAT,
1440 optional: true,
1441 },
1442 }
1443 }
1444 )]
1445 /// Get repository status.
1446 async fn status(param: Value) -> Result<Value, Error> {
1447
1448 let repo = extract_repository_from_value(&param)?;
1449
1450 let output_format = get_output_format(&param);
1451
1452 let client = connect(repo.host(), repo.user())?;
1453
1454 let path = format!("api2/json/admin/datastore/{}/status", repo.store());
1455
1456 let mut result = client.get(&path, None).await?;
1457 let mut data = result["data"].take();
1458
1459 record_repository(&repo);
1460
1461 let render_total_percentage = |v: &Value, record: &Value| -> Result<String, Error> {
1462 let v = v.as_u64().unwrap();
1463 let total = record["total"].as_u64().unwrap();
1464 let roundup = total/200;
1465 let per = ((v+roundup)*100)/total;
1466 let info = format!(" ({} %)", per);
1467 Ok(format!("{} {:>8}", v, info))
1468 };
1469
1470 let options = default_table_format_options()
1471 .noheader(true)
1472 .column(ColumnConfig::new("total").renderer(render_total_percentage))
1473 .column(ColumnConfig::new("used").renderer(render_total_percentage))
1474 .column(ColumnConfig::new("avail").renderer(render_total_percentage));
1475
1476 let schema = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_STATUS;
1477
1478 format_and_print_result_full(&mut data, schema, &output_format, &options);
1479
1480 Ok(Value::Null)
1481 }
1482
1483 // like get, but simply ignore errors and return Null instead
1484 async fn try_get(repo: &BackupRepository, url: &str) -> Value {
1485
1486 let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
1487 let password = std::env::var(ENV_VAR_PBS_PASSWORD).ok();
1488
1489 let options = HttpClientOptions::new()
1490 .prefix(Some("proxmox-backup".to_string()))
1491 .password(password)
1492 .interactive(false)
1493 .fingerprint(fingerprint)
1494 .fingerprint_cache(true)
1495 .ticket_cache(true);
1496
1497 let client = match HttpClient::new(repo.host(), repo.user(), options) {
1498 Ok(v) => v,
1499 _ => return Value::Null,
1500 };
1501
1502 let mut resp = match client.get(url, None).await {
1503 Ok(v) => v,
1504 _ => return Value::Null,
1505 };
1506
1507 if let Some(map) = resp.as_object_mut() {
1508 if let Some(data) = map.remove("data") {
1509 return data;
1510 }
1511 }
1512 Value::Null
1513 }
1514
1515 fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1516 proxmox_backup::tools::runtime::main(async { complete_backup_group_do(param).await })
1517 }
1518
1519 async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> {
1520
1521 let mut result = vec![];
1522
1523 let repo = match extract_repository_from_map(param) {
1524 Some(v) => v,
1525 _ => return result,
1526 };
1527
1528 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
1529
1530 let data = try_get(&repo, &path).await;
1531
1532 if let Some(list) = data.as_array() {
1533 for item in list {
1534 if let (Some(backup_id), Some(backup_type)) =
1535 (item["backup-id"].as_str(), item["backup-type"].as_str())
1536 {
1537 result.push(format!("{}/{}", backup_type, backup_id));
1538 }
1539 }
1540 }
1541
1542 result
1543 }
1544
1545 fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1546 proxmox_backup::tools::runtime::main(async { complete_group_or_snapshot_do(arg, param).await })
1547 }
1548
1549 async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1550
1551 if arg.matches('/').count() < 2 {
1552 let groups = complete_backup_group_do(param).await;
1553 let mut result = vec![];
1554 for group in groups {
1555 result.push(group.to_string());
1556 result.push(format!("{}/", group));
1557 }
1558 return result;
1559 }
1560
1561 complete_backup_snapshot_do(param).await
1562 }
1563
1564 fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1565 proxmox_backup::tools::runtime::main(async { complete_backup_snapshot_do(param).await })
1566 }
1567
1568 async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> {
1569
1570 let mut result = vec![];
1571
1572 let repo = match extract_repository_from_map(param) {
1573 Some(v) => v,
1574 _ => return result,
1575 };
1576
1577 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
1578
1579 let data = try_get(&repo, &path).await;
1580
1581 if let Some(list) = data.as_array() {
1582 for item in list {
1583 if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
1584 (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64())
1585 {
1586 let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
1587 result.push(snapshot.relative_path().to_str().unwrap().to_owned());
1588 }
1589 }
1590 }
1591
1592 result
1593 }
1594
1595 fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1596 proxmox_backup::tools::runtime::main(async { complete_server_file_name_do(param).await })
1597 }
1598
1599 async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> {
1600
1601 let mut result = vec![];
1602
1603 let repo = match extract_repository_from_map(param) {
1604 Some(v) => v,
1605 _ => return result,
1606 };
1607
1608 let snapshot = match param.get("snapshot") {
1609 Some(path) => {
1610 match BackupDir::parse(path) {
1611 Ok(v) => v,
1612 _ => return result,
1613 }
1614 }
1615 _ => return result,
1616 };
1617
1618 let query = tools::json_object_to_query(json!({
1619 "backup-type": snapshot.group().backup_type(),
1620 "backup-id": snapshot.group().backup_id(),
1621 "backup-time": snapshot.backup_time().timestamp(),
1622 })).unwrap();
1623
1624 let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query);
1625
1626 let data = try_get(&repo, &path).await;
1627
1628 if let Some(list) = data.as_array() {
1629 for item in list {
1630 if let Some(filename) = item["filename"].as_str() {
1631 result.push(filename.to_owned());
1632 }
1633 }
1634 }
1635
1636 result
1637 }
1638
1639 fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1640 complete_server_file_name(arg, param)
1641 .iter()
1642 .map(|v| tools::format::strip_server_file_expenstion(&v))
1643 .collect()
1644 }
1645
1646 fn complete_pxar_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1647 complete_server_file_name(arg, param)
1648 .iter()
1649 .filter_map(|v| {
1650 let name = tools::format::strip_server_file_expenstion(&v);
1651 if name.ends_with(".pxar") {
1652 Some(name)
1653 } else {
1654 None
1655 }
1656 })
1657 .collect()
1658 }
1659
1660 fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
1661
1662 let mut result = vec![];
1663
1664 let mut size = 64;
1665 loop {
1666 result.push(size.to_string());
1667 size *= 2;
1668 if size > 4096 { break; }
1669 }
1670
1671 result
1672 }
1673
1674 fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
1675
1676 // fixme: implement other input methods
1677
1678 use std::env::VarError::*;
1679 match std::env::var("PBS_ENCRYPTION_PASSWORD") {
1680 Ok(p) => return Ok(p.as_bytes().to_vec()),
1681 Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
1682 Err(NotPresent) => {
1683 // Try another method
1684 }
1685 }
1686
1687 // If we're on a TTY, query the user for a password
1688 if tty::stdin_isatty() {
1689 return Ok(tty::read_password("Encryption Key Password: ")?);
1690 }
1691
1692 bail!("no password input mechanism available");
1693 }
1694
1695 fn key_create(
1696 param: Value,
1697 _info: &ApiMethod,
1698 _rpcenv: &mut dyn RpcEnvironment,
1699 ) -> Result<Value, Error> {
1700
1701 let path = tools::required_string_param(&param, "path")?;
1702 let path = PathBuf::from(path);
1703
1704 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
1705
1706 let key = proxmox::sys::linux::random_data(32)?;
1707
1708 if kdf == "scrypt" {
1709 // always read passphrase from tty
1710 if !tty::stdin_isatty() {
1711 bail!("unable to read passphrase - no tty");
1712 }
1713
1714 let password = tty::read_and_verify_password("Encryption Key Password: ")?;
1715
1716 let key_config = encrypt_key_with_passphrase(&key, &password)?;
1717
1718 store_key_config(&path, false, key_config)?;
1719
1720 Ok(Value::Null)
1721 } else if kdf == "none" {
1722 let created = Local.timestamp(Local::now().timestamp(), 0);
1723
1724 store_key_config(&path, false, KeyConfig {
1725 kdf: None,
1726 created,
1727 modified: created,
1728 data: key,
1729 })?;
1730
1731 Ok(Value::Null)
1732 } else {
1733 unreachable!();
1734 }
1735 }
1736
1737 fn master_pubkey_path() -> Result<PathBuf, Error> {
1738 let base = BaseDirectories::with_prefix("proxmox-backup")?;
1739
1740 // usually $HOME/.config/proxmox-backup/master-public.pem
1741 let path = base.place_config_file("master-public.pem")?;
1742
1743 Ok(path)
1744 }
1745
1746 fn key_import_master_pubkey(
1747 param: Value,
1748 _info: &ApiMethod,
1749 _rpcenv: &mut dyn RpcEnvironment,
1750 ) -> Result<Value, Error> {
1751
1752 let path = tools::required_string_param(&param, "path")?;
1753 let path = PathBuf::from(path);
1754
1755 let pem_data = file_get_contents(&path)?;
1756
1757 if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
1758 bail!("Unable to decode PEM data - {}", err);
1759 }
1760
1761 let target_path = master_pubkey_path()?;
1762
1763 replace_file(&target_path, &pem_data, CreateOptions::new())?;
1764
1765 println!("Imported public master key to {:?}", target_path);
1766
1767 Ok(Value::Null)
1768 }
1769
1770 fn key_create_master_key(
1771 _param: Value,
1772 _info: &ApiMethod,
1773 _rpcenv: &mut dyn RpcEnvironment,
1774 ) -> Result<Value, Error> {
1775
1776 // we need a TTY to query the new password
1777 if !tty::stdin_isatty() {
1778 bail!("unable to create master key - no tty");
1779 }
1780
1781 let rsa = openssl::rsa::Rsa::generate(4096)?;
1782 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
1783
1784
1785 let password = String::from_utf8(tty::read_and_verify_password("Master Key Password: ")?)?;
1786
1787 let pub_key: Vec<u8> = pkey.public_key_to_pem()?;
1788 let filename_pub = "master-public.pem";
1789 println!("Writing public master key to {}", filename_pub);
1790 replace_file(filename_pub, pub_key.as_slice(), CreateOptions::new())?;
1791
1792 let cipher = openssl::symm::Cipher::aes_256_cbc();
1793 let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, password.as_bytes())?;
1794
1795 let filename_priv = "master-private.pem";
1796 println!("Writing private master key to {}", filename_priv);
1797 replace_file(filename_priv, priv_key.as_slice(), CreateOptions::new())?;
1798
1799 Ok(Value::Null)
1800 }
1801
1802 fn key_change_passphrase(
1803 param: Value,
1804 _info: &ApiMethod,
1805 _rpcenv: &mut dyn RpcEnvironment,
1806 ) -> Result<Value, Error> {
1807
1808 let path = tools::required_string_param(&param, "path")?;
1809 let path = PathBuf::from(path);
1810
1811 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
1812
1813 // we need a TTY to query the new password
1814 if !tty::stdin_isatty() {
1815 bail!("unable to change passphrase - no tty");
1816 }
1817
1818 let (key, created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
1819
1820 if kdf == "scrypt" {
1821
1822 let password = tty::read_and_verify_password("New Password: ")?;
1823
1824 let mut new_key_config = encrypt_key_with_passphrase(&key, &password)?;
1825 new_key_config.created = created; // keep original value
1826
1827 store_key_config(&path, true, new_key_config)?;
1828
1829 Ok(Value::Null)
1830 } else if kdf == "none" {
1831 let modified = Local.timestamp(Local::now().timestamp(), 0);
1832
1833 store_key_config(&path, true, KeyConfig {
1834 kdf: None,
1835 created, // keep original value
1836 modified,
1837 data: key.to_vec(),
1838 })?;
1839
1840 Ok(Value::Null)
1841 } else {
1842 unreachable!();
1843 }
1844 }
1845
1846 fn key_mgmt_cli() -> CliCommandMap {
1847
1848 const KDF_SCHEMA: Schema =
1849 StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.")
1850 .format(&ApiStringFormat::Enum(&["scrypt", "none"]))
1851 .default("scrypt")
1852 .schema();
1853
1854 #[sortable]
1855 const API_METHOD_KEY_CREATE: ApiMethod = ApiMethod::new(
1856 &ApiHandler::Sync(&key_create),
1857 &ObjectSchema::new(
1858 "Create a new encryption key.",
1859 &sorted!([
1860 ("path", false, &StringSchema::new("File system path.").schema()),
1861 ("kdf", true, &KDF_SCHEMA),
1862 ]),
1863 )
1864 );
1865
1866 let key_create_cmd_def = CliCommand::new(&API_METHOD_KEY_CREATE)
1867 .arg_param(&["path"])
1868 .completion_cb("path", tools::complete_file_name);
1869
1870 #[sortable]
1871 const API_METHOD_KEY_CHANGE_PASSPHRASE: ApiMethod = ApiMethod::new(
1872 &ApiHandler::Sync(&key_change_passphrase),
1873 &ObjectSchema::new(
1874 "Change the passphrase required to decrypt the key.",
1875 &sorted!([
1876 ("path", false, &StringSchema::new("File system path.").schema()),
1877 ("kdf", true, &KDF_SCHEMA),
1878 ]),
1879 )
1880 );
1881
1882 let key_change_passphrase_cmd_def = CliCommand::new(&API_METHOD_KEY_CHANGE_PASSPHRASE)
1883 .arg_param(&["path"])
1884 .completion_cb("path", tools::complete_file_name);
1885
1886 const API_METHOD_KEY_CREATE_MASTER_KEY: ApiMethod = ApiMethod::new(
1887 &ApiHandler::Sync(&key_create_master_key),
1888 &ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.", &[])
1889 );
1890
1891 let key_create_master_key_cmd_def = CliCommand::new(&API_METHOD_KEY_CREATE_MASTER_KEY);
1892
1893 #[sortable]
1894 const API_METHOD_KEY_IMPORT_MASTER_PUBKEY: ApiMethod = ApiMethod::new(
1895 &ApiHandler::Sync(&key_import_master_pubkey),
1896 &ObjectSchema::new(
1897 "Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.",
1898 &sorted!([ ("path", false, &StringSchema::new("File system path.").schema()) ]),
1899 )
1900 );
1901
1902 let key_import_master_pubkey_cmd_def = CliCommand::new(&API_METHOD_KEY_IMPORT_MASTER_PUBKEY)
1903 .arg_param(&["path"])
1904 .completion_cb("path", tools::complete_file_name);
1905
1906 CliCommandMap::new()
1907 .insert("create", key_create_cmd_def)
1908 .insert("create-master-key", key_create_master_key_cmd_def)
1909 .insert("import-master-pubkey", key_import_master_pubkey_cmd_def)
1910 .insert("change-passphrase", key_change_passphrase_cmd_def)
1911 }
1912
1913 fn mount(
1914 param: Value,
1915 _info: &ApiMethod,
1916 _rpcenv: &mut dyn RpcEnvironment,
1917 ) -> Result<Value, Error> {
1918 let verbose = param["verbose"].as_bool().unwrap_or(false);
1919 if verbose {
1920 // This will stay in foreground with debug output enabled as None is
1921 // passed for the RawFd.
1922 return proxmox_backup::tools::runtime::main(mount_do(param, None));
1923 }
1924
1925 // Process should be deamonized.
1926 // Make sure to fork before the async runtime is instantiated to avoid troubles.
1927 let pipe = pipe()?;
1928 match fork() {
1929 Ok(ForkResult::Parent { .. }) => {
1930 nix::unistd::close(pipe.1).unwrap();
1931 // Blocks the parent process until we are ready to go in the child
1932 let _res = nix::unistd::read(pipe.0, &mut [0]).unwrap();
1933 Ok(Value::Null)
1934 }
1935 Ok(ForkResult::Child) => {
1936 nix::unistd::close(pipe.0).unwrap();
1937 nix::unistd::setsid().unwrap();
1938 proxmox_backup::tools::runtime::main(mount_do(param, Some(pipe.1)))
1939 }
1940 Err(_) => bail!("failed to daemonize process"),
1941 }
1942 }
1943
1944 async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
1945 let repo = extract_repository_from_value(&param)?;
1946 let archive_name = tools::required_string_param(&param, "archive-name")?;
1947 let target = tools::required_string_param(&param, "target")?;
1948 let client = connect(repo.host(), repo.user())?;
1949
1950 record_repository(&repo);
1951
1952 let path = tools::required_string_param(&param, "snapshot")?;
1953 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
1954 let group = BackupGroup::parse(path)?;
1955 api_datastore_latest_snapshot(&client, repo.store(), group).await?
1956 } else {
1957 let snapshot = BackupDir::parse(path)?;
1958 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
1959 };
1960
1961 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
1962 let crypt_config = match keyfile {
1963 None => None,
1964 Some(path) => {
1965 let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
1966 Some(Arc::new(CryptConfig::new(key)?))
1967 }
1968 };
1969
1970 let server_archive_name = if archive_name.ends_with(".pxar") {
1971 format!("{}.didx", archive_name)
1972 } else {
1973 bail!("Can only mount pxar archives.");
1974 };
1975
1976 let client = BackupReader::start(
1977 client,
1978 crypt_config.clone(),
1979 repo.store(),
1980 &backup_type,
1981 &backup_id,
1982 backup_time,
1983 true,
1984 ).await?;
1985
1986 let manifest = client.download_manifest().await?;
1987
1988 if server_archive_name.ends_with(".didx") {
1989 let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
1990 let most_used = index.find_most_used_chunks(8);
1991 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1992 let reader = BufferedDynamicReader::new(index, chunk_reader);
1993 let decoder = pxar::Decoder::new(reader)?;
1994 let options = OsStr::new("ro,default_permissions");
1995 let mut session = pxar::fuse::Session::new(decoder, &options, pipe.is_none())
1996 .map_err(|err| format_err!("pxar mount failed: {}", err))?;
1997
1998 // Mount the session but not call fuse deamonize as this will cause
1999 // issues with the runtime after the fork
2000 let deamonize = false;
2001 session.mount(&Path::new(target), deamonize)?;
2002
2003 if let Some(pipe) = pipe {
2004 nix::unistd::chdir(Path::new("/")).unwrap();
2005 // Finish creation of deamon by redirecting filedescriptors.
2006 let nullfd = nix::fcntl::open(
2007 "/dev/null",
2008 nix::fcntl::OFlag::O_RDWR,
2009 nix::sys::stat::Mode::empty(),
2010 ).unwrap();
2011 nix::unistd::dup2(nullfd, 0).unwrap();
2012 nix::unistd::dup2(nullfd, 1).unwrap();
2013 nix::unistd::dup2(nullfd, 2).unwrap();
2014 if nullfd > 2 {
2015 nix::unistd::close(nullfd).unwrap();
2016 }
2017 // Signal the parent process that we are done with the setup and it can
2018 // terminate.
2019 nix::unistd::write(pipe, &[0u8])?;
2020 nix::unistd::close(pipe).unwrap();
2021 }
2022
2023 let multithreaded = true;
2024 session.run_loop(multithreaded)?;
2025 } else {
2026 bail!("unknown archive file extension (expected .pxar)");
2027 }
2028
2029 Ok(Value::Null)
2030 }
2031
2032 #[api(
2033 input: {
2034 properties: {
2035 "snapshot": {
2036 type: String,
2037 description: "Group/Snapshot path.",
2038 },
2039 "archive-name": {
2040 type: String,
2041 description: "Backup archive name.",
2042 },
2043 "repository": {
2044 optional: true,
2045 schema: REPO_URL_SCHEMA,
2046 },
2047 "keyfile": {
2048 optional: true,
2049 type: String,
2050 description: "Path to encryption key.",
2051 },
2052 },
2053 },
2054 )]
2055 /// Shell to interactively inspect and restore snapshots.
2056 async fn catalog_shell(param: Value) -> Result<(), Error> {
2057 let repo = extract_repository_from_value(&param)?;
2058 let client = connect(repo.host(), repo.user())?;
2059 let path = tools::required_string_param(&param, "snapshot")?;
2060 let archive_name = tools::required_string_param(&param, "archive-name")?;
2061
2062 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
2063 let group = BackupGroup::parse(path)?;
2064 api_datastore_latest_snapshot(&client, repo.store(), group).await?
2065 } else {
2066 let snapshot = BackupDir::parse(path)?;
2067 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
2068 };
2069
2070 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
2071 let crypt_config = match keyfile {
2072 None => None,
2073 Some(path) => {
2074 let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
2075 Some(Arc::new(CryptConfig::new(key)?))
2076 }
2077 };
2078
2079 let server_archive_name = if archive_name.ends_with(".pxar") {
2080 format!("{}.didx", archive_name)
2081 } else {
2082 bail!("Can only mount pxar archives.");
2083 };
2084
2085 let client = BackupReader::start(
2086 client,
2087 crypt_config.clone(),
2088 repo.store(),
2089 &backup_type,
2090 &backup_id,
2091 backup_time,
2092 true,
2093 ).await?;
2094
2095 let tmpfile = std::fs::OpenOptions::new()
2096 .write(true)
2097 .read(true)
2098 .custom_flags(libc::O_TMPFILE)
2099 .open("/tmp")?;
2100
2101 let manifest = client.download_manifest().await?;
2102
2103 let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
2104 let most_used = index.find_most_used_chunks(8);
2105 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config.clone(), most_used);
2106 let reader = BufferedDynamicReader::new(index, chunk_reader);
2107 let mut decoder = pxar::Decoder::new(reader)?;
2108 decoder.set_callback(|path| {
2109 println!("{:?}", path);
2110 Ok(())
2111 });
2112
2113 let tmpfile = client.download(CATALOG_NAME, tmpfile).await?;
2114 let index = DynamicIndexReader::new(tmpfile)
2115 .map_err(|err| format_err!("unable to read catalog index - {}", err))?;
2116
2117 // Note: do not use values stored in index (not trusted) - instead, computed them again
2118 let (csum, size) = index.compute_csum();
2119 manifest.verify_file(CATALOG_NAME, &csum, size)?;
2120
2121 let most_used = index.find_most_used_chunks(8);
2122 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
2123 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
2124 let mut catalogfile = std::fs::OpenOptions::new()
2125 .write(true)
2126 .read(true)
2127 .custom_flags(libc::O_TMPFILE)
2128 .open("/tmp")?;
2129
2130 std::io::copy(&mut reader, &mut catalogfile)
2131 .map_err(|err| format_err!("unable to download catalog - {}", err))?;
2132
2133 catalogfile.seek(SeekFrom::Start(0))?;
2134 let catalog_reader = CatalogReader::new(catalogfile);
2135 let state = Shell::new(
2136 catalog_reader,
2137 &server_archive_name,
2138 decoder,
2139 )?;
2140
2141 println!("Starting interactive shell");
2142 state.shell()?;
2143
2144 record_repository(&repo);
2145
2146 Ok(())
2147 }
2148
2149 fn catalog_mgmt_cli() -> CliCommandMap {
2150 let catalog_shell_cmd_def = CliCommand::new(&API_METHOD_CATALOG_SHELL)
2151 .arg_param(&["snapshot", "archive-name"])
2152 .completion_cb("repository", complete_repository)
2153 .completion_cb("archive-name", complete_pxar_archive_name)
2154 .completion_cb("snapshot", complete_group_or_snapshot);
2155
2156 let catalog_dump_cmd_def = CliCommand::new(&API_METHOD_DUMP_CATALOG)
2157 .arg_param(&["snapshot"])
2158 .completion_cb("repository", complete_repository)
2159 .completion_cb("snapshot", complete_backup_snapshot);
2160
2161 CliCommandMap::new()
2162 .insert("dump", catalog_dump_cmd_def)
2163 .insert("shell", catalog_shell_cmd_def)
2164 }
2165
2166 #[api(
2167 input: {
2168 properties: {
2169 repository: {
2170 schema: REPO_URL_SCHEMA,
2171 optional: true,
2172 },
2173 limit: {
2174 description: "The maximal number of tasks to list.",
2175 type: Integer,
2176 optional: true,
2177 minimum: 1,
2178 maximum: 1000,
2179 default: 50,
2180 },
2181 "output-format": {
2182 schema: OUTPUT_FORMAT,
2183 optional: true,
2184 },
2185 all: {
2186 type: Boolean,
2187 description: "Also list stopped tasks.",
2188 optional: true,
2189 },
2190 }
2191 }
2192 )]
2193 /// List running server tasks for this repo user
2194 async fn task_list(param: Value) -> Result<Value, Error> {
2195
2196 let output_format = get_output_format(&param);
2197
2198 let repo = extract_repository_from_value(&param)?;
2199 let client = connect(repo.host(), repo.user())?;
2200
2201 let limit = param["limit"].as_u64().unwrap_or(50) as usize;
2202 let running = !param["all"].as_bool().unwrap_or(false);
2203
2204 let args = json!({
2205 "running": running,
2206 "start": 0,
2207 "limit": limit,
2208 "userfilter": repo.user(),
2209 "store": repo.store(),
2210 });
2211
2212 let mut result = client.get("api2/json/nodes/localhost/tasks", Some(args)).await?;
2213 let mut data = result["data"].take();
2214
2215 let schema = &proxmox_backup::api2::node::tasks::API_RETURN_SCHEMA_LIST_TASKS;
2216
2217 let options = default_table_format_options()
2218 .column(ColumnConfig::new("starttime").right_align(false).renderer(tools::format::render_epoch))
2219 .column(ColumnConfig::new("endtime").right_align(false).renderer(tools::format::render_epoch))
2220 .column(ColumnConfig::new("upid"))
2221 .column(ColumnConfig::new("status").renderer(tools::format::render_task_status));
2222
2223 format_and_print_result_full(&mut data, schema, &output_format, &options);
2224
2225 Ok(Value::Null)
2226 }
2227
2228 #[api(
2229 input: {
2230 properties: {
2231 repository: {
2232 schema: REPO_URL_SCHEMA,
2233 optional: true,
2234 },
2235 upid: {
2236 schema: UPID_SCHEMA,
2237 },
2238 }
2239 }
2240 )]
2241 /// Display the task log.
2242 async fn task_log(param: Value) -> Result<Value, Error> {
2243
2244 let repo = extract_repository_from_value(&param)?;
2245 let upid = tools::required_string_param(&param, "upid")?;
2246
2247 let client = connect(repo.host(), repo.user())?;
2248
2249 display_task_log(client, upid, true).await?;
2250
2251 Ok(Value::Null)
2252 }
2253
2254 #[api(
2255 input: {
2256 properties: {
2257 repository: {
2258 schema: REPO_URL_SCHEMA,
2259 optional: true,
2260 },
2261 upid: {
2262 schema: UPID_SCHEMA,
2263 },
2264 }
2265 }
2266 )]
2267 /// Try to stop a specific task.
2268 async fn task_stop(param: Value) -> Result<Value, Error> {
2269
2270 let repo = extract_repository_from_value(&param)?;
2271 let upid_str = tools::required_string_param(&param, "upid")?;
2272
2273 let mut client = connect(repo.host(), repo.user())?;
2274
2275 let path = format!("api2/json/nodes/localhost/tasks/{}", upid_str);
2276 let _ = client.delete(&path, None).await?;
2277
2278 Ok(Value::Null)
2279 }
2280
2281 fn task_mgmt_cli() -> CliCommandMap {
2282
2283 let task_list_cmd_def = CliCommand::new(&API_METHOD_TASK_LIST)
2284 .completion_cb("repository", complete_repository);
2285
2286 let task_log_cmd_def = CliCommand::new(&API_METHOD_TASK_LOG)
2287 .arg_param(&["upid"]);
2288
2289 let task_stop_cmd_def = CliCommand::new(&API_METHOD_TASK_STOP)
2290 .arg_param(&["upid"]);
2291
2292 CliCommandMap::new()
2293 .insert("log", task_log_cmd_def)
2294 .insert("list", task_list_cmd_def)
2295 .insert("stop", task_stop_cmd_def)
2296 }
2297
2298 fn main() {
2299
2300 let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP)
2301 .arg_param(&["backupspec"])
2302 .completion_cb("repository", complete_repository)
2303 .completion_cb("backupspec", complete_backup_source)
2304 .completion_cb("keyfile", tools::complete_file_name)
2305 .completion_cb("chunk-size", complete_chunk_size);
2306
2307 let upload_log_cmd_def = CliCommand::new(&API_METHOD_UPLOAD_LOG)
2308 .arg_param(&["snapshot", "logfile"])
2309 .completion_cb("snapshot", complete_backup_snapshot)
2310 .completion_cb("logfile", tools::complete_file_name)
2311 .completion_cb("keyfile", tools::complete_file_name)
2312 .completion_cb("repository", complete_repository);
2313
2314 let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS)
2315 .completion_cb("repository", complete_repository);
2316
2317 let snapshots_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOTS)
2318 .arg_param(&["group"])
2319 .completion_cb("group", complete_backup_group)
2320 .completion_cb("repository", complete_repository);
2321
2322 let forget_cmd_def = CliCommand::new(&API_METHOD_FORGET_SNAPSHOTS)
2323 .arg_param(&["snapshot"])
2324 .completion_cb("repository", complete_repository)
2325 .completion_cb("snapshot", complete_backup_snapshot);
2326
2327 let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
2328 .completion_cb("repository", complete_repository);
2329
2330 let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE)
2331 .arg_param(&["snapshot", "archive-name", "target"])
2332 .completion_cb("repository", complete_repository)
2333 .completion_cb("snapshot", complete_group_or_snapshot)
2334 .completion_cb("archive-name", complete_archive_name)
2335 .completion_cb("target", tools::complete_file_name);
2336
2337 let files_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOT_FILES)
2338 .arg_param(&["snapshot"])
2339 .completion_cb("repository", complete_repository)
2340 .completion_cb("snapshot", complete_backup_snapshot);
2341
2342 let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE)
2343 .arg_param(&["group"])
2344 .completion_cb("group", complete_backup_group)
2345 .completion_cb("repository", complete_repository);
2346
2347 let status_cmd_def = CliCommand::new(&API_METHOD_STATUS)
2348 .completion_cb("repository", complete_repository);
2349
2350 let login_cmd_def = CliCommand::new(&API_METHOD_API_LOGIN)
2351 .completion_cb("repository", complete_repository);
2352
2353 let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT)
2354 .completion_cb("repository", complete_repository);
2355
2356 #[sortable]
2357 const API_METHOD_MOUNT: ApiMethod = ApiMethod::new(
2358 &ApiHandler::Sync(&mount),
2359 &ObjectSchema::new(
2360 "Mount pxar archive.",
2361 &sorted!([
2362 ("snapshot", false, &StringSchema::new("Group/Snapshot path.").schema()),
2363 ("archive-name", false, &StringSchema::new("Backup archive name.").schema()),
2364 ("target", false, &StringSchema::new("Target directory path.").schema()),
2365 ("repository", true, &REPO_URL_SCHEMA),
2366 ("keyfile", true, &StringSchema::new("Path to encryption key.").schema()),
2367 ("verbose", true, &BooleanSchema::new("Verbose output.").default(false).schema()),
2368 ]),
2369 )
2370 );
2371
2372 let mount_cmd_def = CliCommand::new(&API_METHOD_MOUNT)
2373 .arg_param(&["snapshot", "archive-name", "target"])
2374 .completion_cb("repository", complete_repository)
2375 .completion_cb("snapshot", complete_group_or_snapshot)
2376 .completion_cb("archive-name", complete_pxar_archive_name)
2377 .completion_cb("target", tools::complete_file_name);
2378
2379
2380 let cmd_def = CliCommandMap::new()
2381 .insert("backup", backup_cmd_def)
2382 .insert("upload-log", upload_log_cmd_def)
2383 .insert("forget", forget_cmd_def)
2384 .insert("garbage-collect", garbage_collect_cmd_def)
2385 .insert("list", list_cmd_def)
2386 .insert("login", login_cmd_def)
2387 .insert("logout", logout_cmd_def)
2388 .insert("prune", prune_cmd_def)
2389 .insert("restore", restore_cmd_def)
2390 .insert("snapshots", snapshots_cmd_def)
2391 .insert("files", files_cmd_def)
2392 .insert("status", status_cmd_def)
2393 .insert("key", key_mgmt_cli())
2394 .insert("mount", mount_cmd_def)
2395 .insert("catalog", catalog_mgmt_cli())
2396 .insert("task", task_mgmt_cli());
2397
2398 run_cli_command(cmd_def, Some(|future| {
2399 proxmox_backup::tools::runtime::main(future)
2400 }));
2401 }