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