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