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