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