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