]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-client.rs
client restore: factor out archive/type parsing
[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
TL
1110fn parse_archive_type(name: &str) -> (String, ArchiveType) {
1111 if name.ends_with(".pxar") {
1112 (format!("{}.didx", name), ArchiveType::DynamicIndex)
1113 } else if name.ends_with(".img") {
1114 (format!("{}.fidx", name), ArchiveType::FixedIndex)
1115 } else {
1116 (format!("{}.blob", name), ArchiveType::Blob)
1117 }
1118}
1119
a47a02ae
DM
1120#[api(
1121 input: {
1122 properties: {
1123 repository: {
1124 schema: REPO_URL_SCHEMA,
1125 optional: true,
1126 },
1127 snapshot: {
1128 type: String,
1129 description: "Group/Snapshot path.",
1130 },
1131 "archive-name": {
1132 description: "Backup archive name.",
1133 type: String,
1134 },
1135 target: {
1136 type: String,
90c815bf 1137 description: r###"Target directory path. Use '-' to write to standard output.
8a8a4703 1138
5eee6d89 1139We do not extraxt '.pxar' archives when writing to standard output.
8a8a4703 1140
a47a02ae
DM
1141"###
1142 },
1143 "allow-existing-dirs": {
1144 type: Boolean,
1145 description: "Do not fail if directories already exists.",
1146 optional: true,
1147 },
1148 keyfile: {
1149 schema: KEYFILE_SCHEMA,
1150 optional: true,
1151 },
1152 }
1153 }
1154)]
1155/// Restore backup repository.
1156async fn restore(param: Value) -> Result<Value, Error> {
2665cef7 1157 let repo = extract_repository_from_value(&param)?;
9f912493 1158
86eda3eb
DM
1159 let verbose = param["verbose"].as_bool().unwrap_or(false);
1160
46d5aa0a
DM
1161 let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false);
1162
d5c34d98
DM
1163 let archive_name = tools::required_string_param(&param, "archive-name")?;
1164
d59dbeca 1165 let client = connect(repo.host(), repo.user())?;
d0a03d40 1166
d0a03d40 1167 record_repository(&repo);
d5c34d98 1168
9f912493 1169 let path = tools::required_string_param(&param, "snapshot")?;
9f912493 1170
86eda3eb 1171 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
d5c34d98 1172 let group = BackupGroup::parse(path)?;
27c9affb 1173 api_datastore_latest_snapshot(&client, repo.store(), group).await?
d5c34d98
DM
1174 } else {
1175 let snapshot = BackupDir::parse(path)?;
86eda3eb
DM
1176 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
1177 };
9f912493 1178
d5c34d98 1179 let target = tools::required_string_param(&param, "target")?;
bf125261 1180 let target = if target == "-" { None } else { Some(target) };
2ae7d196 1181
11377a47 1182 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
2ae7d196 1183
86eda3eb
DM
1184 let crypt_config = match keyfile {
1185 None => None,
1186 Some(path) => {
6d20a29d 1187 let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
86eda3eb
DM
1188 Some(Arc::new(CryptConfig::new(key)?))
1189 }
1190 };
d5c34d98 1191
296c50ba
DM
1192 let client = BackupReader::start(
1193 client,
1194 crypt_config.clone(),
1195 repo.store(),
1196 &backup_type,
1197 &backup_id,
1198 backup_time,
1199 true,
1200 ).await?;
86eda3eb 1201
f06b820a 1202 let manifest = client.download_manifest().await?;
02fcf372 1203
dc155e9b
TL
1204 let (archive_name, archive_type) = parse_archive_type(archive_name);
1205
1206 if archive_name == MANIFEST_BLOB_NAME {
f06b820a 1207 let backup_index_data = manifest.into_json().to_string();
02fcf372 1208 if let Some(target) = target {
feaa1ad3 1209 replace_file(target, backup_index_data.as_bytes(), CreateOptions::new())?;
02fcf372
DM
1210 } else {
1211 let stdout = std::io::stdout();
1212 let mut writer = stdout.lock();
296c50ba 1213 writer.write_all(backup_index_data.as_bytes())
02fcf372
DM
1214 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1215 }
1216
dc155e9b 1217 } else if archive_type == ArchiveType::Blob {
d2267b11 1218
dc155e9b 1219 let mut reader = client.download_blob(&manifest, &archive_name).await?;
f8100e96 1220
bf125261 1221 if let Some(target) = target {
0d986280
DM
1222 let mut writer = std::fs::OpenOptions::new()
1223 .write(true)
1224 .create(true)
1225 .create_new(true)
1226 .open(target)
1227 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
1228 std::io::copy(&mut reader, &mut writer)?;
bf125261
DM
1229 } else {
1230 let stdout = std::io::stdout();
1231 let mut writer = stdout.lock();
0d986280 1232 std::io::copy(&mut reader, &mut writer)
bf125261
DM
1233 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1234 }
f8100e96 1235
dc155e9b 1236 } else if archive_type == ArchiveType::DynamicIndex {
86eda3eb 1237
dc155e9b 1238 let index = client.download_dynamic_index(&manifest, &archive_name).await?;
df65bd3d 1239
f4bf7dfc
DM
1240 let most_used = index.find_most_used_chunks(8);
1241
1242 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1243
afb4cd28 1244 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
86eda3eb 1245
bf125261 1246 if let Some(target) = target {
86eda3eb 1247
47651f95 1248 let feature_flags = pxar::flags::DEFAULT;
f701d033
DM
1249 let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags);
1250 decoder.set_callback(move |path| {
bf125261 1251 if verbose {
fd04ca7a 1252 eprintln!("{:?}", path);
bf125261
DM
1253 }
1254 Ok(())
1255 });
6a879109
CE
1256 decoder.set_allow_existing_dirs(allow_existing_dirs);
1257
fa7e957c 1258 decoder.restore(Path::new(target), &Vec::new())?;
bf125261 1259 } else {
88892ea8
DM
1260 let mut writer = std::fs::OpenOptions::new()
1261 .write(true)
1262 .open("/dev/stdout")
1263 .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?;
afb4cd28 1264
bf125261
DM
1265 std::io::copy(&mut reader, &mut writer)
1266 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1267 }
dc155e9b 1268 } else if archive_type == ArchiveType::FixedIndex {
afb4cd28 1269
dc155e9b 1270 let index = client.download_fixed_index(&manifest, &archive_name).await?;
df65bd3d 1271
88892ea8
DM
1272 let mut writer = if let Some(target) = target {
1273 std::fs::OpenOptions::new()
bf125261
DM
1274 .write(true)
1275 .create(true)
1276 .create_new(true)
1277 .open(target)
88892ea8 1278 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?
bf125261 1279 } else {
88892ea8
DM
1280 std::fs::OpenOptions::new()
1281 .write(true)
1282 .open("/dev/stdout")
1283 .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?
1284 };
afb4cd28 1285
fd04ca7a 1286 dump_image(client.clone(), crypt_config.clone(), index, &mut writer, verbose)?;
3031e44c 1287 }
fef44d4f
DM
1288
1289 Ok(Value::Null)
45db6f89
DM
1290}
1291
a47a02ae
DM
1292#[api(
1293 input: {
1294 properties: {
1295 repository: {
1296 schema: REPO_URL_SCHEMA,
1297 optional: true,
1298 },
1299 snapshot: {
1300 type: String,
1301 description: "Group/Snapshot path.",
1302 },
1303 logfile: {
1304 type: String,
1305 description: "The path to the log file you want to upload.",
1306 },
1307 keyfile: {
1308 schema: KEYFILE_SCHEMA,
1309 optional: true,
1310 },
1311 }
1312 }
1313)]
1314/// Upload backup log file.
1315async fn upload_log(param: Value) -> Result<Value, Error> {
ec34f7eb
DM
1316
1317 let logfile = tools::required_string_param(&param, "logfile")?;
1318 let repo = extract_repository_from_value(&param)?;
1319
1320 let snapshot = tools::required_string_param(&param, "snapshot")?;
1321 let snapshot = BackupDir::parse(snapshot)?;
1322
d59dbeca 1323 let mut client = connect(repo.host(), repo.user())?;
ec34f7eb 1324
11377a47 1325 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
ec34f7eb
DM
1326
1327 let crypt_config = match keyfile {
1328 None => None,
1329 Some(path) => {
6d20a29d 1330 let (key, _created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
ec34f7eb 1331 let crypt_config = CryptConfig::new(key)?;
9025312a 1332 Some(Arc::new(crypt_config))
ec34f7eb
DM
1333 }
1334 };
1335
e18a6c9e 1336 let data = file_get_contents(logfile)?;
ec34f7eb 1337
7123ff7d 1338 let blob = DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?;
ec34f7eb
DM
1339
1340 let raw_data = blob.into_inner();
1341
1342 let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store());
1343
1344 let args = json!({
1345 "backup-type": snapshot.group().backup_type(),
1346 "backup-id": snapshot.group().backup_id(),
1347 "backup-time": snapshot.backup_time().timestamp(),
1348 });
1349
1350 let body = hyper::Body::from(raw_data);
1351
8a8a4703 1352 client.upload("application/octet-stream", body, &path, Some(args)).await
ec34f7eb
DM
1353}
1354
032d3ad8
DM
1355const API_METHOD_PRUNE: ApiMethod = ApiMethod::new(
1356 &ApiHandler::Async(&prune),
1357 &ObjectSchema::new(
1358 "Prune a backup repository.",
1359 &proxmox_backup::add_common_prune_prameters!([
1360 ("dry-run", true, &BooleanSchema::new(
1361 "Just show what prune would do, but do not delete anything.")
1362 .schema()),
1363 ("group", false, &StringSchema::new("Backup group.").schema()),
1364 ], [
1365 ("output-format", true, &OUTPUT_FORMAT),
1366 ("repository", true, &REPO_URL_SCHEMA),
1367 ])
1368 )
1369);
1370
1371fn prune<'a>(
1372 param: Value,
1373 _info: &ApiMethod,
1374 _rpcenv: &'a mut dyn RpcEnvironment,
1375) -> proxmox::api::ApiFuture<'a> {
1376 async move {
1377 prune_async(param).await
1378 }.boxed()
1379}
83b7db02 1380
032d3ad8 1381async fn prune_async(mut param: Value) -> Result<Value, Error> {
2665cef7 1382 let repo = extract_repository_from_value(&param)?;
83b7db02 1383
d59dbeca 1384 let mut client = connect(repo.host(), repo.user())?;
83b7db02 1385
d0a03d40 1386 let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
83b7db02 1387
9fdc3ef4
DM
1388 let group = tools::required_string_param(&param, "group")?;
1389 let group = BackupGroup::parse(group)?;
c2043614
DM
1390
1391 let output_format = get_output_format(&param);
9fdc3ef4 1392
ea7a7ef2
DM
1393 param.as_object_mut().unwrap().remove("repository");
1394 param.as_object_mut().unwrap().remove("group");
163e9bbe 1395 param.as_object_mut().unwrap().remove("output-format");
ea7a7ef2
DM
1396
1397 param["backup-type"] = group.backup_type().into();
1398 param["backup-id"] = group.backup_id().into();
83b7db02 1399
db1e061d 1400 let mut result = client.post(&path, Some(param)).await?;
74fa81b8 1401
87c42375 1402 record_repository(&repo);
3b03abfe 1403
db1e061d
DM
1404 let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> {
1405 let item: PruneListItem = serde_json::from_value(record.to_owned())?;
1406 let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time);
1407 Ok(snapshot.relative_path().to_str().unwrap().to_owned())
1408 };
1409
1410 let options = default_table_format_options()
1411 .sortby("backup-type", false)
1412 .sortby("backup-id", false)
1413 .sortby("backup-time", false)
1414 .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot"))
74f7240b 1415 .column(ColumnConfig::new("backup-time").renderer(tools::format::render_epoch).header("date"))
db1e061d
DM
1416 .column(ColumnConfig::new("keep"))
1417 ;
1418
1419 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_PRUNE;
1420
1421 let mut data = result["data"].take();
1422
1423 format_and_print_result_full(&mut data, info, &output_format, &options);
d0a03d40 1424
43a406fd 1425 Ok(Value::Null)
83b7db02
DM
1426}
1427
a47a02ae
DM
1428#[api(
1429 input: {
1430 properties: {
1431 repository: {
1432 schema: REPO_URL_SCHEMA,
1433 optional: true,
1434 },
1435 "output-format": {
1436 schema: OUTPUT_FORMAT,
1437 optional: true,
1438 },
1439 }
1440 }
1441)]
1442/// Get repository status.
1443async fn status(param: Value) -> Result<Value, Error> {
34a816cc
DM
1444
1445 let repo = extract_repository_from_value(&param)?;
1446
c2043614 1447 let output_format = get_output_format(&param);
34a816cc 1448
d59dbeca 1449 let client = connect(repo.host(), repo.user())?;
34a816cc
DM
1450
1451 let path = format!("api2/json/admin/datastore/{}/status", repo.store());
1452
1dc117bb 1453 let mut result = client.get(&path, None).await?;
390c5bdd 1454 let mut data = result["data"].take();
34a816cc
DM
1455
1456 record_repository(&repo);
1457
390c5bdd
DM
1458 let render_total_percentage = |v: &Value, record: &Value| -> Result<String, Error> {
1459 let v = v.as_u64().unwrap();
1460 let total = record["total"].as_u64().unwrap();
1461 let roundup = total/200;
1462 let per = ((v+roundup)*100)/total;
e23f5863
DM
1463 let info = format!(" ({} %)", per);
1464 Ok(format!("{} {:>8}", v, info))
390c5bdd 1465 };
1dc117bb 1466
c2043614 1467 let options = default_table_format_options()
be2425ff 1468 .noheader(true)
e23f5863 1469 .column(ColumnConfig::new("total").renderer(render_total_percentage))
390c5bdd
DM
1470 .column(ColumnConfig::new("used").renderer(render_total_percentage))
1471 .column(ColumnConfig::new("avail").renderer(render_total_percentage));
34a816cc 1472
ea5f547f 1473 let schema = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_STATUS;
390c5bdd
DM
1474
1475 format_and_print_result_full(&mut data, schema, &output_format, &options);
34a816cc
DM
1476
1477 Ok(Value::Null)
1478}
1479
5a2df000 1480// like get, but simply ignore errors and return Null instead
e9722f8b 1481async fn try_get(repo: &BackupRepository, url: &str) -> Value {
024f11bb 1482
a05c0c6f 1483 let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
d1c65727 1484 let password = std::env::var(ENV_VAR_PBS_PASSWORD).ok();
a05c0c6f 1485
d59dbeca 1486 let options = HttpClientOptions::new()
5030b7ce 1487 .prefix(Some("proxmox-backup".to_string()))
d1c65727 1488 .password(password)
d59dbeca 1489 .interactive(false)
a05c0c6f 1490 .fingerprint(fingerprint)
5a74756c 1491 .fingerprint_cache(true)
d59dbeca
DM
1492 .ticket_cache(true);
1493
1494 let client = match HttpClient::new(repo.host(), repo.user(), options) {
45cdce06
DM
1495 Ok(v) => v,
1496 _ => return Value::Null,
1497 };
b2388518 1498
e9722f8b 1499 let mut resp = match client.get(url, None).await {
b2388518
DM
1500 Ok(v) => v,
1501 _ => return Value::Null,
1502 };
1503
1504 if let Some(map) = resp.as_object_mut() {
1505 if let Some(data) = map.remove("data") {
1506 return data;
1507 }
1508 }
1509 Value::Null
1510}
1511
b2388518 1512fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
3f06d6fb 1513 proxmox_backup::tools::runtime::main(async { complete_backup_group_do(param).await })
e9722f8b
WB
1514}
1515
1516async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> {
024f11bb 1517
b2388518
DM
1518 let mut result = vec![];
1519
2665cef7 1520 let repo = match extract_repository_from_map(param) {
b2388518 1521 Some(v) => v,
024f11bb
DM
1522 _ => return result,
1523 };
1524
b2388518
DM
1525 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
1526
e9722f8b 1527 let data = try_get(&repo, &path).await;
b2388518
DM
1528
1529 if let Some(list) = data.as_array() {
024f11bb 1530 for item in list {
98f0b972
DM
1531 if let (Some(backup_id), Some(backup_type)) =
1532 (item["backup-id"].as_str(), item["backup-type"].as_str())
1533 {
1534 result.push(format!("{}/{}", backup_type, backup_id));
024f11bb
DM
1535 }
1536 }
1537 }
1538
1539 result
1540}
1541
b2388518 1542fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
3f06d6fb 1543 proxmox_backup::tools::runtime::main(async { complete_group_or_snapshot_do(arg, param).await })
e9722f8b
WB
1544}
1545
1546async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
b2388518 1547
b2388518 1548 if arg.matches('/').count() < 2 {
e9722f8b 1549 let groups = complete_backup_group_do(param).await;
543a260f 1550 let mut result = vec![];
b2388518
DM
1551 for group in groups {
1552 result.push(group.to_string());
1553 result.push(format!("{}/", group));
1554 }
1555 return result;
1556 }
1557
e9722f8b 1558 complete_backup_snapshot_do(param).await
543a260f 1559}
b2388518 1560
3fb53e07 1561fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
3f06d6fb 1562 proxmox_backup::tools::runtime::main(async { complete_backup_snapshot_do(param).await })
e9722f8b
WB
1563}
1564
1565async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> {
543a260f
DM
1566
1567 let mut result = vec![];
1568
1569 let repo = match extract_repository_from_map(param) {
1570 Some(v) => v,
1571 _ => return result,
1572 };
1573
1574 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
b2388518 1575
e9722f8b 1576 let data = try_get(&repo, &path).await;
b2388518
DM
1577
1578 if let Some(list) = data.as_array() {
1579 for item in list {
1580 if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
1581 (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64())
1582 {
1583 let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
1584 result.push(snapshot.relative_path().to_str().unwrap().to_owned());
1585 }
1586 }
1587 }
1588
1589 result
1590}
1591
45db6f89 1592fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
3f06d6fb 1593 proxmox_backup::tools::runtime::main(async { complete_server_file_name_do(param).await })
e9722f8b
WB
1594}
1595
1596async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> {
08dc340a
DM
1597
1598 let mut result = vec![];
1599
2665cef7 1600 let repo = match extract_repository_from_map(param) {
08dc340a
DM
1601 Some(v) => v,
1602 _ => return result,
1603 };
1604
1605 let snapshot = match param.get("snapshot") {
1606 Some(path) => {
1607 match BackupDir::parse(path) {
1608 Ok(v) => v,
1609 _ => return result,
1610 }
1611 }
1612 _ => return result,
1613 };
1614
1615 let query = tools::json_object_to_query(json!({
1616 "backup-type": snapshot.group().backup_type(),
1617 "backup-id": snapshot.group().backup_id(),
1618 "backup-time": snapshot.backup_time().timestamp(),
1619 })).unwrap();
1620
1621 let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query);
1622
e9722f8b 1623 let data = try_get(&repo, &path).await;
08dc340a
DM
1624
1625 if let Some(list) = data.as_array() {
1626 for item in list {
c4f025eb 1627 if let Some(filename) = item["filename"].as_str() {
08dc340a
DM
1628 result.push(filename.to_owned());
1629 }
1630 }
1631 }
1632
45db6f89
DM
1633 result
1634}
1635
1636fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
52c171e4 1637 complete_server_file_name(arg, param)
e9722f8b 1638 .iter()
4939255f 1639 .map(|v| tools::format::strip_server_file_expenstion(&v))
e9722f8b 1640 .collect()
08dc340a
DM
1641}
1642
0ec9e1b0
DM
1643fn complete_pxar_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1644 complete_server_file_name(arg, param)
1645 .iter()
1646 .filter_map(|v| {
4939255f 1647 let name = tools::format::strip_server_file_expenstion(&v);
0ec9e1b0
DM
1648 if name.ends_with(".pxar") {
1649 Some(name)
1650 } else {
1651 None
1652 }
1653 })
1654 .collect()
1655}
1656
49811347
DM
1657fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
1658
1659 let mut result = vec![];
1660
1661 let mut size = 64;
1662 loop {
1663 result.push(size.to_string());
11377a47 1664 size *= 2;
49811347
DM
1665 if size > 4096 { break; }
1666 }
1667
1668 result
1669}
1670
826f309b 1671fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
ff5d3707 1672
f2401311
DM
1673 // fixme: implement other input methods
1674
1675 use std::env::VarError::*;
1676 match std::env::var("PBS_ENCRYPTION_PASSWORD") {
826f309b 1677 Ok(p) => return Ok(p.as_bytes().to_vec()),
f2401311
DM
1678 Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
1679 Err(NotPresent) => {
1680 // Try another method
1681 }
1682 }
1683
1684 // If we're on a TTY, query the user for a password
501f4fa2
DM
1685 if tty::stdin_isatty() {
1686 return Ok(tty::read_password("Encryption Key Password: ")?);
f2401311
DM
1687 }
1688
1689 bail!("no password input mechanism available");
1690}
1691
ac716234
DM
1692fn key_create(
1693 param: Value,
1694 _info: &ApiMethod,
1695 _rpcenv: &mut dyn RpcEnvironment,
1696) -> Result<Value, Error> {
1697
9b06db45
DM
1698 let path = tools::required_string_param(&param, "path")?;
1699 let path = PathBuf::from(path);
ac716234 1700
181f097a 1701 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
ac716234
DM
1702
1703 let key = proxmox::sys::linux::random_data(32)?;
1704
181f097a
DM
1705 if kdf == "scrypt" {
1706 // always read passphrase from tty
501f4fa2 1707 if !tty::stdin_isatty() {
181f097a
DM
1708 bail!("unable to read passphrase - no tty");
1709 }
ac716234 1710
501f4fa2 1711 let password = tty::read_and_verify_password("Encryption Key Password: ")?;
181f097a 1712
ab44acff 1713 let key_config = encrypt_key_with_passphrase(&key, &password)?;
37c5a175 1714
ab44acff 1715 store_key_config(&path, false, key_config)?;
181f097a
DM
1716
1717 Ok(Value::Null)
1718 } else if kdf == "none" {
1719 let created = Local.timestamp(Local::now().timestamp(), 0);
1720
1721 store_key_config(&path, false, KeyConfig {
1722 kdf: None,
1723 created,
ab44acff 1724 modified: created,
181f097a
DM
1725 data: key,
1726 })?;
1727
1728 Ok(Value::Null)
1729 } else {
1730 unreachable!();
1731 }
ac716234
DM
1732}
1733
9f46c7de
DM
1734fn master_pubkey_path() -> Result<PathBuf, Error> {
1735 let base = BaseDirectories::with_prefix("proxmox-backup")?;
1736
1737 // usually $HOME/.config/proxmox-backup/master-public.pem
1738 let path = base.place_config_file("master-public.pem")?;
1739
1740 Ok(path)
1741}
1742
3ea8bfc9
DM
1743fn key_import_master_pubkey(
1744 param: Value,
1745 _info: &ApiMethod,
1746 _rpcenv: &mut dyn RpcEnvironment,
1747) -> Result<Value, Error> {
1748
1749 let path = tools::required_string_param(&param, "path")?;
1750 let path = PathBuf::from(path);
1751
e18a6c9e 1752 let pem_data = file_get_contents(&path)?;
3ea8bfc9
DM
1753
1754 if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
1755 bail!("Unable to decode PEM data - {}", err);
1756 }
1757
9f46c7de 1758 let target_path = master_pubkey_path()?;
3ea8bfc9 1759
feaa1ad3 1760 replace_file(&target_path, &pem_data, CreateOptions::new())?;
3ea8bfc9
DM
1761
1762 println!("Imported public master key to {:?}", target_path);
1763
1764 Ok(Value::Null)
1765}
1766
37c5a175
DM
1767fn key_create_master_key(
1768 _param: Value,
1769 _info: &ApiMethod,
1770 _rpcenv: &mut dyn RpcEnvironment,
1771) -> Result<Value, Error> {
1772
1773 // we need a TTY to query the new password
501f4fa2 1774 if !tty::stdin_isatty() {
37c5a175
DM
1775 bail!("unable to create master key - no tty");
1776 }
1777
1778 let rsa = openssl::rsa::Rsa::generate(4096)?;
1779 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
1780
37c5a175 1781
501f4fa2 1782 let password = String::from_utf8(tty::read_and_verify_password("Master Key Password: ")?)?;
37c5a175
DM
1783
1784 let pub_key: Vec<u8> = pkey.public_key_to_pem()?;
1785 let filename_pub = "master-public.pem";
1786 println!("Writing public master key to {}", filename_pub);
feaa1ad3 1787 replace_file(filename_pub, pub_key.as_slice(), CreateOptions::new())?;
37c5a175
DM
1788
1789 let cipher = openssl::symm::Cipher::aes_256_cbc();
cbe01dc5 1790 let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, password.as_bytes())?;
37c5a175
DM
1791
1792 let filename_priv = "master-private.pem";
1793 println!("Writing private master key to {}", filename_priv);
feaa1ad3 1794 replace_file(filename_priv, priv_key.as_slice(), CreateOptions::new())?;
37c5a175
DM
1795
1796 Ok(Value::Null)
1797}
ac716234
DM
1798
1799fn key_change_passphrase(
1800 param: Value,
1801 _info: &ApiMethod,
1802 _rpcenv: &mut dyn RpcEnvironment,
1803) -> Result<Value, Error> {
1804
9b06db45
DM
1805 let path = tools::required_string_param(&param, "path")?;
1806 let path = PathBuf::from(path);
ac716234 1807
181f097a
DM
1808 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
1809
ac716234 1810 // we need a TTY to query the new password
501f4fa2 1811 if !tty::stdin_isatty() {
ac716234
DM
1812 bail!("unable to change passphrase - no tty");
1813 }
1814
6d20a29d 1815 let (key, created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
ac716234 1816
181f097a 1817 if kdf == "scrypt" {
ac716234 1818
501f4fa2 1819 let password = tty::read_and_verify_password("New Password: ")?;
ac716234 1820
cbe01dc5 1821 let mut new_key_config = encrypt_key_with_passphrase(&key, &password)?;
ab44acff
DM
1822 new_key_config.created = created; // keep original value
1823
1824 store_key_config(&path, true, new_key_config)?;
ac716234 1825
181f097a
DM
1826 Ok(Value::Null)
1827 } else if kdf == "none" {
ab44acff 1828 let modified = Local.timestamp(Local::now().timestamp(), 0);
181f097a
DM
1829
1830 store_key_config(&path, true, KeyConfig {
1831 kdf: None,
ab44acff
DM
1832 created, // keep original value
1833 modified,
6d0983db 1834 data: key.to_vec(),
181f097a
DM
1835 })?;
1836
1837 Ok(Value::Null)
1838 } else {
1839 unreachable!();
1840 }
f2401311
DM
1841}
1842
1843fn key_mgmt_cli() -> CliCommandMap {
1844
255f378a 1845 const KDF_SCHEMA: Schema =
181f097a 1846 StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.")
bc0d0388
DM
1847 .format(&ApiStringFormat::Enum(&[
1848 EnumEntry::new("scrypt", "SCrypt"),
1849 EnumEntry::new("none", "Do not encrypt the key")]))
255f378a
DM
1850 .default("scrypt")
1851 .schema();
1852
552c2259 1853 #[sortable]
255f378a
DM
1854 const API_METHOD_KEY_CREATE: ApiMethod = ApiMethod::new(
1855 &ApiHandler::Sync(&key_create),
1856 &ObjectSchema::new(
1857 "Create a new encryption key.",
552c2259 1858 &sorted!([
255f378a
DM
1859 ("path", false, &StringSchema::new("File system path.").schema()),
1860 ("kdf", true, &KDF_SCHEMA),
552c2259 1861 ]),
255f378a 1862 )
181f097a 1863 );
7074a0b3 1864
255f378a 1865 let key_create_cmd_def = CliCommand::new(&API_METHOD_KEY_CREATE)
49fddd98 1866 .arg_param(&["path"])
9b06db45 1867 .completion_cb("path", tools::complete_file_name);
f2401311 1868
552c2259 1869 #[sortable]
255f378a
DM
1870 const API_METHOD_KEY_CHANGE_PASSPHRASE: ApiMethod = ApiMethod::new(
1871 &ApiHandler::Sync(&key_change_passphrase),
1872 &ObjectSchema::new(
1873 "Change the passphrase required to decrypt the key.",
552c2259 1874 &sorted!([
255f378a
DM
1875 ("path", false, &StringSchema::new("File system path.").schema()),
1876 ("kdf", true, &KDF_SCHEMA),
552c2259 1877 ]),
255f378a
DM
1878 )
1879 );
7074a0b3 1880
255f378a 1881 let key_change_passphrase_cmd_def = CliCommand::new(&API_METHOD_KEY_CHANGE_PASSPHRASE)
49fddd98 1882 .arg_param(&["path"])
9b06db45 1883 .completion_cb("path", tools::complete_file_name);
ac716234 1884
255f378a
DM
1885 const API_METHOD_KEY_CREATE_MASTER_KEY: ApiMethod = ApiMethod::new(
1886 &ApiHandler::Sync(&key_create_master_key),
1887 &ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.", &[])
1888 );
7074a0b3 1889
255f378a
DM
1890 let key_create_master_key_cmd_def = CliCommand::new(&API_METHOD_KEY_CREATE_MASTER_KEY);
1891
552c2259 1892 #[sortable]
255f378a
DM
1893 const API_METHOD_KEY_IMPORT_MASTER_PUBKEY: ApiMethod = ApiMethod::new(
1894 &ApiHandler::Sync(&key_import_master_pubkey),
1895 &ObjectSchema::new(
1896 "Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.",
552c2259 1897 &sorted!([ ("path", false, &StringSchema::new("File system path.").schema()) ]),
255f378a
DM
1898 )
1899 );
7074a0b3 1900
255f378a 1901 let key_import_master_pubkey_cmd_def = CliCommand::new(&API_METHOD_KEY_IMPORT_MASTER_PUBKEY)
49fddd98 1902 .arg_param(&["path"])
3ea8bfc9
DM
1903 .completion_cb("path", tools::complete_file_name);
1904
11377a47 1905 CliCommandMap::new()
48ef3c33
DM
1906 .insert("create", key_create_cmd_def)
1907 .insert("create-master-key", key_create_master_key_cmd_def)
1908 .insert("import-master-pubkey", key_import_master_pubkey_cmd_def)
1909 .insert("change-passphrase", key_change_passphrase_cmd_def)
f2401311
DM
1910}
1911
70235f72
CE
1912fn mount(
1913 param: Value,
1914 _info: &ApiMethod,
1915 _rpcenv: &mut dyn RpcEnvironment,
1916) -> Result<Value, Error> {
1917 let verbose = param["verbose"].as_bool().unwrap_or(false);
1918 if verbose {
1919 // This will stay in foreground with debug output enabled as None is
1920 // passed for the RawFd.
3f06d6fb 1921 return proxmox_backup::tools::runtime::main(mount_do(param, None));
70235f72
CE
1922 }
1923
1924 // Process should be deamonized.
1925 // Make sure to fork before the async runtime is instantiated to avoid troubles.
1926 let pipe = pipe()?;
1927 match fork() {
11377a47 1928 Ok(ForkResult::Parent { .. }) => {
70235f72
CE
1929 nix::unistd::close(pipe.1).unwrap();
1930 // Blocks the parent process until we are ready to go in the child
1931 let _res = nix::unistd::read(pipe.0, &mut [0]).unwrap();
1932 Ok(Value::Null)
1933 }
1934 Ok(ForkResult::Child) => {
1935 nix::unistd::close(pipe.0).unwrap();
1936 nix::unistd::setsid().unwrap();
3f06d6fb 1937 proxmox_backup::tools::runtime::main(mount_do(param, Some(pipe.1)))
70235f72
CE
1938 }
1939 Err(_) => bail!("failed to daemonize process"),
1940 }
1941}
1942
1943async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
1944 let repo = extract_repository_from_value(&param)?;
1945 let archive_name = tools::required_string_param(&param, "archive-name")?;
1946 let target = tools::required_string_param(&param, "target")?;
d59dbeca 1947 let client = connect(repo.host(), repo.user())?;
70235f72
CE
1948
1949 record_repository(&repo);
1950
1951 let path = tools::required_string_param(&param, "snapshot")?;
1952 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
1953 let group = BackupGroup::parse(path)?;
27c9affb 1954 api_datastore_latest_snapshot(&client, repo.store(), group).await?
70235f72
CE
1955 } else {
1956 let snapshot = BackupDir::parse(path)?;
1957 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
1958 };
1959
11377a47 1960 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
70235f72
CE
1961 let crypt_config = match keyfile {
1962 None => None,
1963 Some(path) => {
6d20a29d 1964 let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
70235f72
CE
1965 Some(Arc::new(CryptConfig::new(key)?))
1966 }
1967 };
1968
1969 let server_archive_name = if archive_name.ends_with(".pxar") {
1970 format!("{}.didx", archive_name)
1971 } else {
1972 bail!("Can only mount pxar archives.");
1973 };
1974
296c50ba
DM
1975 let client = BackupReader::start(
1976 client,
1977 crypt_config.clone(),
1978 repo.store(),
1979 &backup_type,
1980 &backup_id,
1981 backup_time,
1982 true,
1983 ).await?;
70235f72 1984
f06b820a 1985 let manifest = client.download_manifest().await?;
296c50ba 1986
70235f72 1987 if server_archive_name.ends_with(".didx") {
c3d84a22 1988 let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
70235f72
CE
1989 let most_used = index.find_most_used_chunks(8);
1990 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1991 let reader = BufferedDynamicReader::new(index, chunk_reader);
f701d033 1992 let decoder = pxar::Decoder::new(reader)?;
70235f72 1993 let options = OsStr::new("ro,default_permissions");
2a111910 1994 let mut session = pxar::fuse::Session::new(decoder, &options, pipe.is_none())
70235f72
CE
1995 .map_err(|err| format_err!("pxar mount failed: {}", err))?;
1996
1997 // Mount the session but not call fuse deamonize as this will cause
1998 // issues with the runtime after the fork
1999 let deamonize = false;
2000 session.mount(&Path::new(target), deamonize)?;
2001
2002 if let Some(pipe) = pipe {
2003 nix::unistd::chdir(Path::new("/")).unwrap();
add5861e 2004 // Finish creation of daemon by redirecting filedescriptors.
70235f72
CE
2005 let nullfd = nix::fcntl::open(
2006 "/dev/null",
2007 nix::fcntl::OFlag::O_RDWR,
2008 nix::sys::stat::Mode::empty(),
2009 ).unwrap();
2010 nix::unistd::dup2(nullfd, 0).unwrap();
2011 nix::unistd::dup2(nullfd, 1).unwrap();
2012 nix::unistd::dup2(nullfd, 2).unwrap();
2013 if nullfd > 2 {
2014 nix::unistd::close(nullfd).unwrap();
2015 }
2016 // Signal the parent process that we are done with the setup and it can
2017 // terminate.
11377a47 2018 nix::unistd::write(pipe, &[0u8])?;
70235f72
CE
2019 nix::unistd::close(pipe).unwrap();
2020 }
2021
2022 let multithreaded = true;
2023 session.run_loop(multithreaded)?;
2024 } else {
2025 bail!("unknown archive file extension (expected .pxar)");
2026 }
2027
2028 Ok(Value::Null)
2029}
2030
78d54360
WB
2031#[api(
2032 input: {
2033 properties: {
2034 "snapshot": {
2035 type: String,
2036 description: "Group/Snapshot path.",
2037 },
2038 "archive-name": {
2039 type: String,
2040 description: "Backup archive name.",
2041 },
2042 "repository": {
2043 optional: true,
2044 schema: REPO_URL_SCHEMA,
2045 },
2046 "keyfile": {
2047 optional: true,
2048 type: String,
2049 description: "Path to encryption key.",
2050 },
2051 },
2052 },
2053)]
2054/// Shell to interactively inspect and restore snapshots.
2055async fn catalog_shell(param: Value) -> Result<(), Error> {
3cf73c4e 2056 let repo = extract_repository_from_value(&param)?;
d59dbeca 2057 let client = connect(repo.host(), repo.user())?;
3cf73c4e
CE
2058 let path = tools::required_string_param(&param, "snapshot")?;
2059 let archive_name = tools::required_string_param(&param, "archive-name")?;
2060
2061 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
2062 let group = BackupGroup::parse(path)?;
27c9affb 2063 api_datastore_latest_snapshot(&client, repo.store(), group).await?
3cf73c4e
CE
2064 } else {
2065 let snapshot = BackupDir::parse(path)?;
2066 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
2067 };
2068
2069 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
2070 let crypt_config = match keyfile {
2071 None => None,
2072 Some(path) => {
6d20a29d 2073 let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
3cf73c4e
CE
2074 Some(Arc::new(CryptConfig::new(key)?))
2075 }
2076 };
2077
2078 let server_archive_name = if archive_name.ends_with(".pxar") {
2079 format!("{}.didx", archive_name)
2080 } else {
2081 bail!("Can only mount pxar archives.");
2082 };
2083
2084 let client = BackupReader::start(
2085 client,
2086 crypt_config.clone(),
2087 repo.store(),
2088 &backup_type,
2089 &backup_id,
2090 backup_time,
2091 true,
2092 ).await?;
2093
2094 let tmpfile = std::fs::OpenOptions::new()
2095 .write(true)
2096 .read(true)
2097 .custom_flags(libc::O_TMPFILE)
2098 .open("/tmp")?;
2099
2100 let manifest = client.download_manifest().await?;
2101
2102 let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
2103 let most_used = index.find_most_used_chunks(8);
2104 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config.clone(), most_used);
2105 let reader = BufferedDynamicReader::new(index, chunk_reader);
f701d033
DM
2106 let mut decoder = pxar::Decoder::new(reader)?;
2107 decoder.set_callback(|path| {
2108 println!("{:?}", path);
2109 Ok(())
2110 });
3cf73c4e
CE
2111
2112 let tmpfile = client.download(CATALOG_NAME, tmpfile).await?;
2113 let index = DynamicIndexReader::new(tmpfile)
2114 .map_err(|err| format_err!("unable to read catalog index - {}", err))?;
2115
2116 // Note: do not use values stored in index (not trusted) - instead, computed them again
2117 let (csum, size) = index.compute_csum();
2118 manifest.verify_file(CATALOG_NAME, &csum, size)?;
2119
2120 let most_used = index.find_most_used_chunks(8);
2121 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
2122 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
2123 let mut catalogfile = std::fs::OpenOptions::new()
2124 .write(true)
2125 .read(true)
2126 .custom_flags(libc::O_TMPFILE)
2127 .open("/tmp")?;
2128
2129 std::io::copy(&mut reader, &mut catalogfile)
2130 .map_err(|err| format_err!("unable to download catalog - {}", err))?;
2131
2132 catalogfile.seek(SeekFrom::Start(0))?;
2133 let catalog_reader = CatalogReader::new(catalogfile);
2134 let state = Shell::new(
2135 catalog_reader,
2136 &server_archive_name,
2137 decoder,
2138 )?;
2139
2140 println!("Starting interactive shell");
2141 state.shell()?;
2142
2143 record_repository(&repo);
2144
78d54360 2145 Ok(())
3cf73c4e
CE
2146}
2147
1c6ad6ef 2148fn catalog_mgmt_cli() -> CliCommandMap {
78d54360 2149 let catalog_shell_cmd_def = CliCommand::new(&API_METHOD_CATALOG_SHELL)
1c6ad6ef
DM
2150 .arg_param(&["snapshot", "archive-name"])
2151 .completion_cb("repository", complete_repository)
0ec9e1b0 2152 .completion_cb("archive-name", complete_pxar_archive_name)
1c6ad6ef
DM
2153 .completion_cb("snapshot", complete_group_or_snapshot);
2154
1c6ad6ef
DM
2155 let catalog_dump_cmd_def = CliCommand::new(&API_METHOD_DUMP_CATALOG)
2156 .arg_param(&["snapshot"])
2157 .completion_cb("repository", complete_repository)
2158 .completion_cb("snapshot", complete_backup_snapshot);
2159
2160 CliCommandMap::new()
48ef3c33
DM
2161 .insert("dump", catalog_dump_cmd_def)
2162 .insert("shell", catalog_shell_cmd_def)
1c6ad6ef
DM
2163}
2164
5830c205
DM
2165#[api(
2166 input: {
2167 properties: {
2168 repository: {
2169 schema: REPO_URL_SCHEMA,
2170 optional: true,
2171 },
2172 limit: {
2173 description: "The maximal number of tasks to list.",
2174 type: Integer,
2175 optional: true,
2176 minimum: 1,
2177 maximum: 1000,
2178 default: 50,
2179 },
2180 "output-format": {
2181 schema: OUTPUT_FORMAT,
2182 optional: true,
2183 },
4939255f
DM
2184 all: {
2185 type: Boolean,
2186 description: "Also list stopped tasks.",
2187 optional: true,
2188 },
5830c205
DM
2189 }
2190 }
2191)]
2192/// List running server tasks for this repo user
d6c4a119 2193async fn task_list(param: Value) -> Result<Value, Error> {
5830c205 2194
c2043614
DM
2195 let output_format = get_output_format(&param);
2196
d6c4a119 2197 let repo = extract_repository_from_value(&param)?;
d59dbeca 2198 let client = connect(repo.host(), repo.user())?;
5830c205 2199
d6c4a119 2200 let limit = param["limit"].as_u64().unwrap_or(50) as usize;
4939255f 2201 let running = !param["all"].as_bool().unwrap_or(false);
5830c205 2202
d6c4a119 2203 let args = json!({
4939255f 2204 "running": running,
d6c4a119
DM
2205 "start": 0,
2206 "limit": limit,
2207 "userfilter": repo.user(),
2208 "store": repo.store(),
2209 });
5830c205 2210
4939255f
DM
2211 let mut result = client.get("api2/json/nodes/localhost/tasks", Some(args)).await?;
2212 let mut data = result["data"].take();
5830c205 2213
4939255f
DM
2214 let schema = &proxmox_backup::api2::node::tasks::API_RETURN_SCHEMA_LIST_TASKS;
2215
2216 let options = default_table_format_options()
2217 .column(ColumnConfig::new("starttime").right_align(false).renderer(tools::format::render_epoch))
2218 .column(ColumnConfig::new("endtime").right_align(false).renderer(tools::format::render_epoch))
2219 .column(ColumnConfig::new("upid"))
2220 .column(ColumnConfig::new("status").renderer(tools::format::render_task_status));
2221
2222 format_and_print_result_full(&mut data, schema, &output_format, &options);
5830c205
DM
2223
2224 Ok(Value::Null)
2225}
2226
2227#[api(
2228 input: {
2229 properties: {
2230 repository: {
2231 schema: REPO_URL_SCHEMA,
2232 optional: true,
2233 },
2234 upid: {
2235 schema: UPID_SCHEMA,
2236 },
2237 }
2238 }
2239)]
2240/// Display the task log.
d6c4a119 2241async fn task_log(param: Value) -> Result<Value, Error> {
5830c205 2242
d6c4a119
DM
2243 let repo = extract_repository_from_value(&param)?;
2244 let upid = tools::required_string_param(&param, "upid")?;
5830c205 2245
d59dbeca 2246 let client = connect(repo.host(), repo.user())?;
5830c205 2247
d6c4a119 2248 display_task_log(client, upid, true).await?;
5830c205
DM
2249
2250 Ok(Value::Null)
2251}
2252
3f1020b7
DM
2253#[api(
2254 input: {
2255 properties: {
2256 repository: {
2257 schema: REPO_URL_SCHEMA,
2258 optional: true,
2259 },
2260 upid: {
2261 schema: UPID_SCHEMA,
2262 },
2263 }
2264 }
2265)]
2266/// Try to stop a specific task.
d6c4a119 2267async fn task_stop(param: Value) -> Result<Value, Error> {
3f1020b7 2268
d6c4a119
DM
2269 let repo = extract_repository_from_value(&param)?;
2270 let upid_str = tools::required_string_param(&param, "upid")?;
3f1020b7 2271
d59dbeca 2272 let mut client = connect(repo.host(), repo.user())?;
3f1020b7 2273
d6c4a119
DM
2274 let path = format!("api2/json/nodes/localhost/tasks/{}", upid_str);
2275 let _ = client.delete(&path, None).await?;
3f1020b7
DM
2276
2277 Ok(Value::Null)
2278}
2279
5830c205
DM
2280fn task_mgmt_cli() -> CliCommandMap {
2281
2282 let task_list_cmd_def = CliCommand::new(&API_METHOD_TASK_LIST)
2283 .completion_cb("repository", complete_repository);
2284
2285 let task_log_cmd_def = CliCommand::new(&API_METHOD_TASK_LOG)
2286 .arg_param(&["upid"]);
2287
3f1020b7
DM
2288 let task_stop_cmd_def = CliCommand::new(&API_METHOD_TASK_STOP)
2289 .arg_param(&["upid"]);
2290
5830c205
DM
2291 CliCommandMap::new()
2292 .insert("log", task_log_cmd_def)
2293 .insert("list", task_list_cmd_def)
3f1020b7 2294 .insert("stop", task_stop_cmd_def)
5830c205 2295}
1c6ad6ef 2296
f2401311 2297fn main() {
33d64b81 2298
255f378a 2299 let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP)
49fddd98 2300 .arg_param(&["backupspec"])
d0a03d40 2301 .completion_cb("repository", complete_repository)
49811347 2302 .completion_cb("backupspec", complete_backup_source)
6d0983db 2303 .completion_cb("keyfile", tools::complete_file_name)
49811347 2304 .completion_cb("chunk-size", complete_chunk_size);
f8838fe9 2305
255f378a 2306 let upload_log_cmd_def = CliCommand::new(&API_METHOD_UPLOAD_LOG)
49fddd98 2307 .arg_param(&["snapshot", "logfile"])
543a260f 2308 .completion_cb("snapshot", complete_backup_snapshot)
ec34f7eb
DM
2309 .completion_cb("logfile", tools::complete_file_name)
2310 .completion_cb("keyfile", tools::complete_file_name)
2311 .completion_cb("repository", complete_repository);
2312
255f378a 2313 let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS)
d0a03d40 2314 .completion_cb("repository", complete_repository);
41c039e1 2315
255f378a 2316 let snapshots_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOTS)
49fddd98 2317 .arg_param(&["group"])
024f11bb 2318 .completion_cb("group", complete_backup_group)
d0a03d40 2319 .completion_cb("repository", complete_repository);
184f17af 2320
255f378a 2321 let forget_cmd_def = CliCommand::new(&API_METHOD_FORGET_SNAPSHOTS)
49fddd98 2322 .arg_param(&["snapshot"])
b2388518 2323 .completion_cb("repository", complete_repository)
543a260f 2324 .completion_cb("snapshot", complete_backup_snapshot);
6f62c924 2325
255f378a 2326 let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
d0a03d40 2327 .completion_cb("repository", complete_repository);
8cc0d6af 2328
255f378a 2329 let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE)
49fddd98 2330 .arg_param(&["snapshot", "archive-name", "target"])
b2388518 2331 .completion_cb("repository", complete_repository)
08dc340a
DM
2332 .completion_cb("snapshot", complete_group_or_snapshot)
2333 .completion_cb("archive-name", complete_archive_name)
2334 .completion_cb("target", tools::complete_file_name);
9f912493 2335
255f378a 2336 let files_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOT_FILES)
49fddd98 2337 .arg_param(&["snapshot"])
52c171e4 2338 .completion_cb("repository", complete_repository)
543a260f 2339 .completion_cb("snapshot", complete_backup_snapshot);
52c171e4 2340
255f378a 2341 let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE)
49fddd98 2342 .arg_param(&["group"])
9fdc3ef4 2343 .completion_cb("group", complete_backup_group)
d0a03d40 2344 .completion_cb("repository", complete_repository);
9f912493 2345
255f378a 2346 let status_cmd_def = CliCommand::new(&API_METHOD_STATUS)
34a816cc
DM
2347 .completion_cb("repository", complete_repository);
2348
255f378a 2349 let login_cmd_def = CliCommand::new(&API_METHOD_API_LOGIN)
e240d8be
DM
2350 .completion_cb("repository", complete_repository);
2351
255f378a 2352 let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT)
e240d8be 2353 .completion_cb("repository", complete_repository);
32efac1c 2354
552c2259 2355 #[sortable]
255f378a
DM
2356 const API_METHOD_MOUNT: ApiMethod = ApiMethod::new(
2357 &ApiHandler::Sync(&mount),
2358 &ObjectSchema::new(
2359 "Mount pxar archive.",
552c2259 2360 &sorted!([
255f378a
DM
2361 ("snapshot", false, &StringSchema::new("Group/Snapshot path.").schema()),
2362 ("archive-name", false, &StringSchema::new("Backup archive name.").schema()),
2363 ("target", false, &StringSchema::new("Target directory path.").schema()),
2364 ("repository", true, &REPO_URL_SCHEMA),
2365 ("keyfile", true, &StringSchema::new("Path to encryption key.").schema()),
2366 ("verbose", true, &BooleanSchema::new("Verbose output.").default(false).schema()),
552c2259 2367 ]),
255f378a
DM
2368 )
2369 );
7074a0b3 2370
255f378a 2371 let mount_cmd_def = CliCommand::new(&API_METHOD_MOUNT)
49fddd98 2372 .arg_param(&["snapshot", "archive-name", "target"])
70235f72
CE
2373 .completion_cb("repository", complete_repository)
2374 .completion_cb("snapshot", complete_group_or_snapshot)
0ec9e1b0 2375 .completion_cb("archive-name", complete_pxar_archive_name)
70235f72 2376 .completion_cb("target", tools::complete_file_name);
e240d8be 2377
3cf73c4e 2378
41c039e1 2379 let cmd_def = CliCommandMap::new()
48ef3c33
DM
2380 .insert("backup", backup_cmd_def)
2381 .insert("upload-log", upload_log_cmd_def)
2382 .insert("forget", forget_cmd_def)
2383 .insert("garbage-collect", garbage_collect_cmd_def)
2384 .insert("list", list_cmd_def)
2385 .insert("login", login_cmd_def)
2386 .insert("logout", logout_cmd_def)
2387 .insert("prune", prune_cmd_def)
2388 .insert("restore", restore_cmd_def)
2389 .insert("snapshots", snapshots_cmd_def)
2390 .insert("files", files_cmd_def)
2391 .insert("status", status_cmd_def)
2392 .insert("key", key_mgmt_cli())
2393 .insert("mount", mount_cmd_def)
5830c205
DM
2394 .insert("catalog", catalog_mgmt_cli())
2395 .insert("task", task_mgmt_cli());
48ef3c33 2396
7b22acd0
DM
2397 let rpcenv = CliEnvironment::new();
2398 run_cli_command(cmd_def, rpcenv, Some(|future| {
d08bc483
DM
2399 proxmox_backup::tools::runtime::main(future)
2400 }));
ff5d3707 2401}