]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-client.rs
src/backup/fixed_index.rs: new helper to compute checksum and file size
[proxmox-backup.git] / src / bin / proxmox-backup-client.rs
CommitLineData
826f309b 1//#[macro_use]
fe0e04c6 2extern crate proxmox_backup;
ff5d3707 3
4use failure::*;
728797d0 5//use std::os::unix::io::AsRawFd;
fa5d6977 6use chrono::{Local, Utc, TimeZone};
e9c9409a 7use std::path::{Path, PathBuf};
2eeaacb9 8use std::collections::{HashSet, HashMap};
a84ef4c2 9use std::io::{BufReader, Write, Seek, SeekFrom};
2761d6a4
DM
10use std::os::unix::fs::OpenOptionsExt;
11
e18a6c9e 12use proxmox::tools::fs::{file_get_contents, file_get_json, file_set_contents, image_size};
ff5d3707 13
fe0e04c6 14use proxmox_backup::tools;
4de0e142 15use proxmox_backup::cli::*;
bbf9e7e9 16use proxmox_backup::api2::types::*;
ef2f2efb 17use proxmox_backup::api_schema::*;
dc9a007b 18use proxmox_backup::api_schema::router::*;
151c6ce2 19use proxmox_backup::client::*;
247cdbce 20use proxmox_backup::backup::*;
7926a3a1 21use proxmox_backup::pxar::{ self, catalog::* };
86eda3eb 22
fe0e04c6
DM
23//use proxmox_backup::backup::image_index::*;
24//use proxmox_backup::config::datastore;
8968258b 25//use proxmox_backup::pxar::encoder::*;
728797d0 26//use proxmox_backup::backup::datastore::*;
23bb8780 27
f5f13ebc 28use serde_json::{json, Value};
1c0472e8 29//use hyper::Body;
2761d6a4 30use std::sync::{Arc, Mutex};
ae0be2dd 31use regex::Regex;
d0a03d40 32use xdg::BaseDirectories;
ae0be2dd
DM
33
34use lazy_static::lazy_static;
5a2df000 35use futures::*;
c4ff3dce 36use tokio::sync::mpsc;
ae0be2dd
DM
37
38lazy_static! {
79679c2d 39 static ref BACKUPSPEC_REGEX: Regex = Regex::new(r"^([a-zA-Z0-9_-]+\.(?:pxar|img|conf|log)):(.+)$").unwrap();
f2401311
DM
40
41 static ref REPO_URL_SCHEMA: Arc<Schema> = Arc::new(
42 StringSchema::new("Repository URL.")
43 .format(BACKUP_REPO_URL.clone())
44 .max_length(256)
45 .into()
46 );
ae0be2dd 47}
33d64b81 48
d0a03d40 49
2665cef7
DM
50fn get_default_repository() -> Option<String> {
51 std::env::var("PBS_REPOSITORY").ok()
52}
53
54fn extract_repository_from_value(
55 param: &Value,
56) -> Result<BackupRepository, Error> {
57
58 let repo_url = param["repository"]
59 .as_str()
60 .map(String::from)
61 .or_else(get_default_repository)
62 .ok_or_else(|| format_err!("unable to get (default) repository"))?;
63
64 let repo: BackupRepository = repo_url.parse()?;
65
66 Ok(repo)
67}
68
69fn extract_repository_from_map(
70 param: &HashMap<String, String>,
71) -> Option<BackupRepository> {
72
73 param.get("repository")
74 .map(String::from)
75 .or_else(get_default_repository)
76 .and_then(|repo_url| repo_url.parse::<BackupRepository>().ok())
77}
78
d0a03d40
DM
79fn record_repository(repo: &BackupRepository) {
80
81 let base = match BaseDirectories::with_prefix("proxmox-backup") {
82 Ok(v) => v,
83 _ => return,
84 };
85
86 // usually $HOME/.cache/proxmox-backup/repo-list
87 let path = match base.place_cache_file("repo-list") {
88 Ok(v) => v,
89 _ => return,
90 };
91
e18a6c9e 92 let mut data = file_get_json(&path, None).unwrap_or(json!({}));
d0a03d40
DM
93
94 let repo = repo.to_string();
95
96 data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 };
97
98 let mut map = serde_json::map::Map::new();
99
100 loop {
101 let mut max_used = 0;
102 let mut max_repo = None;
103 for (repo, count) in data.as_object().unwrap() {
104 if map.contains_key(repo) { continue; }
105 if let Some(count) = count.as_i64() {
106 if count > max_used {
107 max_used = count;
108 max_repo = Some(repo);
109 }
110 }
111 }
112 if let Some(repo) = max_repo {
113 map.insert(repo.to_owned(), json!(max_used));
114 } else {
115 break;
116 }
117 if map.len() > 10 { // store max. 10 repos
118 break;
119 }
120 }
121
122 let new_data = json!(map);
123
e18a6c9e 124 let _ = file_set_contents(path, new_data.to_string().as_bytes(), None);
d0a03d40
DM
125}
126
49811347 127fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
d0a03d40
DM
128
129 let mut result = vec![];
130
131 let base = match BaseDirectories::with_prefix("proxmox-backup") {
132 Ok(v) => v,
133 _ => return result,
134 };
135
136 // usually $HOME/.cache/proxmox-backup/repo-list
137 let path = match base.place_cache_file("repo-list") {
138 Ok(v) => v,
139 _ => return result,
140 };
141
e18a6c9e 142 let data = file_get_json(&path, None).unwrap_or(json!({}));
d0a03d40
DM
143
144 if let Some(map) = data.as_object() {
49811347 145 for (repo, _count) in map {
d0a03d40
DM
146 result.push(repo.to_owned());
147 }
148 }
149
150 result
151}
152
e9722f8b 153async fn backup_directory<P: AsRef<Path>>(
c4ff3dce 154 client: &BackupClient,
17d6979a 155 dir_path: P,
247cdbce 156 archive_name: &str,
36898ffc 157 chunk_size: Option<usize>,
2eeaacb9 158 device_set: Option<HashSet<u64>>,
219ef0e6 159 verbose: bool,
5b72c9b4 160 skip_lost_and_found: bool,
f98ac774 161 crypt_config: Option<Arc<CryptConfig>>,
9d135fe6 162 catalog: Arc<Mutex<CatalogBlobWriter<std::fs::File>>>,
2c3891d1 163) -> Result<BackupStats, Error> {
33d64b81 164
2761d6a4 165 let pxar_stream = PxarBackupStream::open(dir_path.as_ref(), device_set, verbose, skip_lost_and_found, catalog)?;
e9722f8b 166 let mut chunk_stream = ChunkStream::new(pxar_stream, chunk_size);
ff3d3100 167
e9722f8b 168 let (mut tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks
5e7a09be 169
c4ff3dce 170 let stream = rx
e9722f8b 171 .map_err(Error::from);
17d6979a 172
c4ff3dce 173 // spawn chunker inside a separate task so that it can run parallel
e9722f8b
WB
174 tokio::spawn(async move {
175 let _ = tx.send_all(&mut chunk_stream).await;
176 });
17d6979a 177
e9722f8b
WB
178 let stats = client
179 .upload_stream(archive_name, stream, "dynamic", None, crypt_config)
180 .await?;
bcd879cf 181
2c3891d1 182 Ok(stats)
bcd879cf
DM
183}
184
e9722f8b 185async fn backup_image<P: AsRef<Path>>(
6af905c1
DM
186 client: &BackupClient,
187 image_path: P,
188 archive_name: &str,
189 image_size: u64,
36898ffc 190 chunk_size: Option<usize>,
1c0472e8 191 _verbose: bool,
f98ac774 192 crypt_config: Option<Arc<CryptConfig>>,
2c3891d1 193) -> Result<BackupStats, Error> {
6af905c1 194
6af905c1
DM
195 let path = image_path.as_ref().to_owned();
196
e9722f8b 197 let file = tokio::fs::File::open(path).await?;
6af905c1
DM
198
199 let stream = tokio::codec::FramedRead::new(file, tokio::codec::BytesCodec::new())
200 .map_err(Error::from);
201
36898ffc 202 let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024));
6af905c1 203
e9722f8b
WB
204 let stats = client
205 .upload_stream(archive_name, stream, "fixed", Some(image_size), crypt_config)
206 .await?;
6af905c1 207
2c3891d1 208 Ok(stats)
6af905c1
DM
209}
210
52c171e4
DM
211fn strip_server_file_expenstion(name: &str) -> String {
212
213 if name.ends_with(".didx") {
214 return name[..name.len()-5].to_owned();
215 } else if name.ends_with(".fidx") {
216 return name[..name.len()-5].to_owned();
217 } else if name.ends_with(".blob") {
218 return name[..name.len()-5].to_owned();
219 } else {
220 return name.to_owned(); // should not happen
8e39232a 221 }
8e39232a
DM
222}
223
812c6f87
DM
224fn list_backup_groups(
225 param: Value,
226 _info: &ApiMethod,
dd5495d6 227 _rpcenv: &mut dyn RpcEnvironment,
812c6f87
DM
228) -> Result<Value, Error> {
229
2665cef7 230 let repo = extract_repository_from_value(&param)?;
812c6f87 231
45cdce06 232 let client = HttpClient::new(repo.host(), repo.user())?;
812c6f87 233
d0a03d40 234 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
812c6f87 235
e9722f8b
WB
236 let mut result = async_main(async move {
237 client.get(&path, None).await
238 })?;
812c6f87 239
d0a03d40
DM
240 record_repository(&repo);
241
812c6f87 242 // fixme: implement and use output formatter instead ..
80822b95
DM
243 let list = result["data"].as_array_mut().unwrap();
244
245 list.sort_unstable_by(|a, b| {
246 let a_id = a["backup-id"].as_str().unwrap();
247 let a_backup_type = a["backup-type"].as_str().unwrap();
248 let b_id = b["backup-id"].as_str().unwrap();
249 let b_backup_type = b["backup-type"].as_str().unwrap();
250
251 let type_order = a_backup_type.cmp(b_backup_type);
252 if type_order == std::cmp::Ordering::Equal {
253 a_id.cmp(b_id)
254 } else {
255 type_order
256 }
257 });
812c6f87 258
34a816cc
DM
259 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
260
261 let mut result = vec![];
262
812c6f87
DM
263 for item in list {
264
ad20d198
DM
265 let id = item["backup-id"].as_str().unwrap();
266 let btype = item["backup-type"].as_str().unwrap();
267 let epoch = item["last-backup"].as_i64().unwrap();
fa5d6977 268 let last_backup = Utc.timestamp(epoch, 0);
ad20d198 269 let backup_count = item["backup-count"].as_u64().unwrap();
812c6f87 270
1e9a94e5 271 let group = BackupGroup::new(btype, id);
812c6f87
DM
272
273 let path = group.group_path().to_str().unwrap().to_owned();
ad20d198 274
52c171e4
DM
275 let files = item["files"].as_array().unwrap().iter()
276 .map(|v| strip_server_file_expenstion(v.as_str().unwrap())).collect();
ad20d198 277
34a816cc 278 if output_format == "text" {
fa5d6977
DM
279 println!(
280 "{:20} | {} | {:5} | {}",
281 path,
282 BackupDir::backup_time_to_string(last_backup),
283 backup_count,
284 tools::join(&files, ' '),
285 );
34a816cc
DM
286 } else {
287 result.push(json!({
288 "backup-type": btype,
289 "backup-id": id,
290 "last-backup": epoch,
291 "backup-count": backup_count,
292 "files": files,
293 }));
294 }
812c6f87
DM
295 }
296
9aa3f682 297 if output_format != "text" { format_and_print_result(&result.into(), &output_format); }
34a816cc 298
812c6f87
DM
299 Ok(Value::Null)
300}
301
184f17af
DM
302fn list_snapshots(
303 param: Value,
304 _info: &ApiMethod,
dd5495d6 305 _rpcenv: &mut dyn RpcEnvironment,
184f17af
DM
306) -> Result<Value, Error> {
307
2665cef7 308 let repo = extract_repository_from_value(&param)?;
184f17af 309
34a816cc
DM
310 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
311
45cdce06 312 let client = HttpClient::new(repo.host(), repo.user())?;
184f17af 313
9e391bb7 314 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
184f17af 315
15c847f1
DM
316 let mut args = json!({});
317 if let Some(path) = param["group"].as_str() {
318 let group = BackupGroup::parse(path)?;
319 args["backup-type"] = group.backup_type().into();
320 args["backup-id"] = group.backup_id().into();
321 }
322
e9722f8b
WB
323 let result = async_main(async move {
324 client.get(&path, Some(args)).await
325 })?;
184f17af 326
d0a03d40
DM
327 record_repository(&repo);
328
184f17af
DM
329 let list = result["data"].as_array().unwrap();
330
34a816cc
DM
331 let mut result = vec![];
332
184f17af
DM
333 for item in list {
334
335 let id = item["backup-id"].as_str().unwrap();
336 let btype = item["backup-type"].as_str().unwrap();
337 let epoch = item["backup-time"].as_i64().unwrap();
184f17af 338
391d3107 339 let snapshot = BackupDir::new(btype, id, epoch);
184f17af
DM
340
341 let path = snapshot.relative_path().to_str().unwrap().to_owned();
342
52c171e4
DM
343 let files = item["files"].as_array().unwrap().iter()
344 .map(|v| strip_server_file_expenstion(v.as_str().unwrap())).collect();
184f17af 345
34a816cc 346 if output_format == "text" {
a17a0e7a
DM
347 let size_str = if let Some(size) = item["size"].as_u64() {
348 size.to_string()
349 } else {
350 String::from("-")
351 };
352 println!("{} | {} | {}", path, size_str, tools::join(&files, ' '));
34a816cc 353 } else {
a17a0e7a 354 let mut data = json!({
34a816cc
DM
355 "backup-type": btype,
356 "backup-id": id,
357 "backup-time": epoch,
358 "files": files,
a17a0e7a
DM
359 });
360 if let Some(size) = item["size"].as_u64() {
361 data["size"] = size.into();
362 }
363 result.push(data);
34a816cc 364 }
184f17af
DM
365 }
366
f6ede796 367 if output_format != "text" { format_and_print_result(&result.into(), &output_format); }
34a816cc 368
184f17af
DM
369 Ok(Value::Null)
370}
371
6f62c924
DM
372fn forget_snapshots(
373 param: Value,
374 _info: &ApiMethod,
dd5495d6 375 _rpcenv: &mut dyn RpcEnvironment,
6f62c924
DM
376) -> Result<Value, Error> {
377
2665cef7 378 let repo = extract_repository_from_value(&param)?;
6f62c924
DM
379
380 let path = tools::required_string_param(&param, "snapshot")?;
381 let snapshot = BackupDir::parse(path)?;
382
45cdce06 383 let mut client = HttpClient::new(repo.host(), repo.user())?;
6f62c924 384
9e391bb7 385 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
6f62c924 386
e9722f8b
WB
387 let result = async_main(async move {
388 client.delete(&path, Some(json!({
389 "backup-type": snapshot.group().backup_type(),
390 "backup-id": snapshot.group().backup_id(),
391 "backup-time": snapshot.backup_time().timestamp(),
392 }))).await
393 })?;
6f62c924 394
d0a03d40
DM
395 record_repository(&repo);
396
6f62c924
DM
397 Ok(result)
398}
399
e240d8be
DM
400fn api_login(
401 param: Value,
402 _info: &ApiMethod,
403 _rpcenv: &mut dyn RpcEnvironment,
404) -> Result<Value, Error> {
405
406 let repo = extract_repository_from_value(&param)?;
407
408 let client = HttpClient::new(repo.host(), repo.user())?;
e9722f8b 409 async_main(async move { client.login().await })?;
e240d8be
DM
410
411 record_repository(&repo);
412
413 Ok(Value::Null)
414}
415
416fn api_logout(
417 param: Value,
418 _info: &ApiMethod,
419 _rpcenv: &mut dyn RpcEnvironment,
420) -> Result<Value, Error> {
421
422 let repo = extract_repository_from_value(&param)?;
423
424 delete_ticket_info(repo.host(), repo.user())?;
425
426 Ok(Value::Null)
427}
428
9049a8cf
DM
429fn dump_catalog(
430 param: Value,
431 _info: &ApiMethod,
432 _rpcenv: &mut dyn RpcEnvironment,
433) -> Result<Value, Error> {
434
435 let repo = extract_repository_from_value(&param)?;
436
437 let path = tools::required_string_param(&param, "snapshot")?;
438 let snapshot = BackupDir::parse(path)?;
439
440 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
441
442 let crypt_config = match keyfile {
443 None => None,
444 Some(path) => {
445 let (key, _) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
9025312a 446 Some(Arc::new(CryptConfig::new(key)?))
9049a8cf
DM
447 }
448 };
449
450 let client = HttpClient::new(repo.host(), repo.user())?;
451
e9722f8b
WB
452 async_main(async move {
453 let client = client.start_backup_reader(
454 repo.store(),
455 &snapshot.group().backup_type(),
456 &snapshot.group().backup_id(),
457 snapshot.backup_time(), true).await?;
9049a8cf 458
e9722f8b
WB
459 let blob_file = std::fs::OpenOptions::new()
460 .read(true)
461 .write(true)
462 .custom_flags(libc::O_TMPFILE)
463 .open("/tmp")?;
9049a8cf 464
e9722f8b 465 let mut blob_file = client.download("catalog.blob", blob_file).await?;
a84ef4c2 466
e9722f8b 467 blob_file.seek(SeekFrom::Start(0))?;
a84ef4c2 468
e9722f8b
WB
469 let reader = BufReader::new(blob_file);
470 let mut catalog_reader = CatalogBlobReader::new(reader, crypt_config)?;
9049a8cf 471
e9722f8b 472 catalog_reader.dump()?;
9049a8cf 473
e9722f8b
WB
474 record_repository(&repo);
475
476 Ok::<(), Error>(())
477 })?;
9049a8cf
DM
478
479 Ok(Value::Null)
480}
481
52c171e4
DM
482fn list_snapshot_files(
483 param: Value,
484 _info: &ApiMethod,
485 _rpcenv: &mut dyn RpcEnvironment,
486) -> Result<Value, Error> {
487
488 let repo = extract_repository_from_value(&param)?;
489
490 let path = tools::required_string_param(&param, "snapshot")?;
491 let snapshot = BackupDir::parse(path)?;
492
493 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
494
495 let client = HttpClient::new(repo.host(), repo.user())?;
496
497 let path = format!("api2/json/admin/datastore/{}/files", repo.store());
498
e9722f8b
WB
499 let mut result = async_main(async move {
500 client.get(&path, Some(json!({
501 "backup-type": snapshot.group().backup_type(),
502 "backup-id": snapshot.group().backup_id(),
503 "backup-time": snapshot.backup_time().timestamp(),
504 }))).await
505 })?;
52c171e4
DM
506
507 record_repository(&repo);
508
8c70e3eb 509 let list: Value = result["data"].take();
52c171e4
DM
510
511 if output_format == "text" {
8c70e3eb
DM
512 for item in list.as_array().unwrap().iter() {
513 println!(
514 "{} {}",
515 strip_server_file_expenstion(item["filename"].as_str().unwrap()),
516 item["size"].as_u64().unwrap_or(0),
517 );
52c171e4
DM
518 }
519 } else {
8c70e3eb 520 format_and_print_result(&list, &output_format);
52c171e4
DM
521 }
522
523 Ok(Value::Null)
524}
525
8cc0d6af
DM
526fn start_garbage_collection(
527 param: Value,
528 _info: &ApiMethod,
dd5495d6 529 _rpcenv: &mut dyn RpcEnvironment,
8cc0d6af
DM
530) -> Result<Value, Error> {
531
2665cef7 532 let repo = extract_repository_from_value(&param)?;
8cc0d6af 533
45cdce06 534 let mut client = HttpClient::new(repo.host(), repo.user())?;
8cc0d6af 535
d0a03d40 536 let path = format!("api2/json/admin/datastore/{}/gc", repo.store());
8cc0d6af 537
e9722f8b 538 let result = async_main(async move { client.post(&path, None).await })?;
8cc0d6af 539
d0a03d40
DM
540 record_repository(&repo);
541
8cc0d6af
DM
542 Ok(result)
543}
33d64b81 544
ae0be2dd
DM
545fn parse_backupspec(value: &str) -> Result<(&str, &str), Error> {
546
547 if let Some(caps) = BACKUPSPEC_REGEX.captures(value) {
548 return Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str()));
549 }
550 bail!("unable to parse directory specification '{}'", value);
551}
552
6049b71f
DM
553fn create_backup(
554 param: Value,
555 _info: &ApiMethod,
dd5495d6 556 _rpcenv: &mut dyn RpcEnvironment,
6049b71f 557) -> Result<Value, Error> {
ff5d3707 558
2665cef7 559 let repo = extract_repository_from_value(&param)?;
ae0be2dd
DM
560
561 let backupspec_list = tools::required_array_param(&param, "backupspec")?;
a914a774 562
eed6db39
DM
563 let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false);
564
5b72c9b4
DM
565 let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false);
566
219ef0e6
DM
567 let verbose = param["verbose"].as_bool().unwrap_or(false);
568
ca5d0b61
DM
569 let backup_time_opt = param["backup-time"].as_i64();
570
36898ffc 571 let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize);
2d9d143a 572
247cdbce
DM
573 if let Some(size) = chunk_size_opt {
574 verify_chunk_size(size)?;
2d9d143a
DM
575 }
576
6d0983db
DM
577 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
578
f69adc81 579 let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename());
fba30411 580
bbf9e7e9 581 let backup_type = param["backup-type"].as_str().unwrap_or("host");
ca5d0b61 582
2eeaacb9
DM
583 let include_dev = param["include-dev"].as_array();
584
585 let mut devices = if all_file_systems { None } else { Some(HashSet::new()) };
586
587 if let Some(include_dev) = include_dev {
588 if all_file_systems {
589 bail!("option 'all-file-systems' conflicts with option 'include-dev'");
590 }
591
592 let mut set = HashSet::new();
593 for path in include_dev {
594 let path = path.as_str().unwrap();
595 let stat = nix::sys::stat::stat(path)
596 .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?;
597 set.insert(stat.st_dev);
598 }
599 devices = Some(set);
600 }
601
ae0be2dd 602 let mut upload_list = vec![];
a914a774 603
79679c2d 604 enum BackupType { PXAR, IMAGE, CONFIG, LOGFILE };
6af905c1 605
ae0be2dd
DM
606 for backupspec in backupspec_list {
607 let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?;
bcd879cf 608
eb1804c5
DM
609 use std::os::unix::fs::FileTypeExt;
610
611 let metadata = match std::fs::metadata(filename) {
612 Ok(m) => m,
ae0be2dd
DM
613 Err(err) => bail!("unable to access '{}' - {}", filename, err),
614 };
eb1804c5 615 let file_type = metadata.file_type();
23bb8780 616
4af0ee05
DM
617 let extension = target.rsplit('.').next()
618 .ok_or(format_err!("missing target file extenion '{}'", target))?;
bcd879cf 619
ec8a9bb9
DM
620 match extension {
621 "pxar" => {
622 if !file_type.is_dir() {
623 bail!("got unexpected file type (expected directory)");
624 }
4af0ee05 625 upload_list.push((BackupType::PXAR, filename.to_owned(), format!("{}.didx", target), 0));
ec8a9bb9
DM
626 }
627 "img" => {
eb1804c5 628
ec8a9bb9
DM
629 if !(file_type.is_file() || file_type.is_block_device()) {
630 bail!("got unexpected file type (expected file or block device)");
631 }
eb1804c5 632
e18a6c9e 633 let size = image_size(&PathBuf::from(filename))?;
23bb8780 634
ec8a9bb9 635 if size == 0 { bail!("got zero-sized file '{}'", filename); }
ae0be2dd 636
4af0ee05 637 upload_list.push((BackupType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size));
ec8a9bb9
DM
638 }
639 "conf" => {
640 if !file_type.is_file() {
641 bail!("got unexpected file type (expected regular file)");
642 }
4af0ee05 643 upload_list.push((BackupType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len()));
ec8a9bb9 644 }
79679c2d
DM
645 "log" => {
646 if !file_type.is_file() {
647 bail!("got unexpected file type (expected regular file)");
648 }
4af0ee05 649 upload_list.push((BackupType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len()));
79679c2d 650 }
ec8a9bb9
DM
651 _ => {
652 bail!("got unknown archive extension '{}'", extension);
653 }
ae0be2dd
DM
654 }
655 }
656
ca5d0b61 657 let backup_time = Utc.timestamp(backup_time_opt.unwrap_or(Utc::now().timestamp()), 0);
ae0be2dd 658
c4ff3dce 659 let client = HttpClient::new(repo.host(), repo.user())?;
d0a03d40
DM
660 record_repository(&repo);
661
ca5d0b61
DM
662 println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time));
663
f69adc81 664 println!("Client name: {}", proxmox::tools::nodename());
ca5d0b61
DM
665
666 let start_time = Local::now();
667
7a6cfbd9 668 println!("Starting protocol: {}", start_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
51144821 669
bb823140
DM
670 let (crypt_config, rsa_encrypted_key) = match keyfile {
671 None => (None, None),
6d0983db 672 Some(path) => {
bb823140
DM
673 let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
674
675 let crypt_config = CryptConfig::new(key)?;
676
677 let path = master_pubkey_path()?;
678 if path.exists() {
e18a6c9e 679 let pem_data = file_get_contents(&path)?;
bb823140
DM
680 let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
681 let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?;
682 (Some(Arc::new(crypt_config)), Some(enc_key))
683 } else {
684 (Some(Arc::new(crypt_config)), None)
685 }
6d0983db
DM
686 }
687 };
f98ac774 688
e9722f8b
WB
689 async_main(async move {
690 let client = client
691 .start_backup(repo.store(), backup_type, &backup_id, backup_time, verbose)
692 .await?;
693
694 let mut file_list = vec![];
695
696 // fixme: encrypt/sign catalog?
697 let catalog_file = std::fs::OpenOptions::new()
698 .write(true)
699 .read(true)
700 .custom_flags(libc::O_TMPFILE)
701 .open("/tmp")?;
702
703 let catalog = Arc::new(Mutex::new(CatalogBlobWriter::new_compressed(catalog_file)?));
704 let mut upload_catalog = false;
705
706 for (backup_type, filename, target, size) in upload_list {
707 match backup_type {
708 BackupType::CONFIG => {
709 println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target);
710 let stats = client
711 .upload_blob_from_file(&filename, &target, crypt_config.clone(), true)
712 .await?;
713 file_list.push((target, stats));
714 }
715 BackupType::LOGFILE => { // fixme: remove - not needed anymore ?
716 println!("Upload log file '{}' to '{:?}' as {}", filename, repo, target);
717 let stats = client
718 .upload_blob_from_file(&filename, &target, crypt_config.clone(), true)
719 .await?;
720 file_list.push((target, stats));
721 }
722 BackupType::PXAR => {
723 upload_catalog = true;
724 println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target);
725 catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?;
726 let stats = backup_directory(
727 &client,
728 &filename,
729 &target,
730 chunk_size_opt,
731 devices.clone(),
732 verbose,
733 skip_lost_and_found,
734 crypt_config.clone(),
735 catalog.clone(),
736 ).await?;
737 file_list.push((target, stats));
738 catalog.lock().unwrap().end_directory()?;
739 }
740 BackupType::IMAGE => {
741 println!("Upload image '{}' to '{:?}' as {}", filename, repo, target);
742 let stats = backup_image(
743 &client,
744 &filename,
745 &target,
746 size,
747 chunk_size_opt,
748 verbose,
749 crypt_config.clone(),
750 ).await?;
751 file_list.push((target, stats));
752 }
6af905c1
DM
753 }
754 }
4818c8b6 755
e9722f8b
WB
756 // finalize and upload catalog
757 if upload_catalog {
758 let mutex = Arc::try_unwrap(catalog)
759 .map_err(|_| format_err!("unable to get catalog (still used)"))?;
760 let mut catalog_file = mutex.into_inner().unwrap().finish()?;
2761d6a4 761
e9722f8b 762 let target = "catalog.blob";
2761d6a4 763
e9722f8b 764 catalog_file.seek(SeekFrom::Start(0))?;
9d135fe6 765
e9722f8b
WB
766 let stats = client.upload_blob(catalog_file, target).await?;
767 file_list.push((target.to_owned(), stats));
768 }
2761d6a4 769
e9722f8b
WB
770 if let Some(rsa_encrypted_key) = rsa_encrypted_key {
771 let target = "rsa-encrypted.key";
772 println!("Upload RSA encoded key to '{:?}' as {}", repo, target);
773 let stats = client
774 .upload_blob_from_data(rsa_encrypted_key, target, None, false, false)
775 .await?;
776 file_list.push((format!("{}.blob", target), stats));
777
778 // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t
779 /*
780 let mut buffer2 = vec![0u8; rsa.size() as usize];
781 let pem_data = file_get_contents("master-private.pem")?;
782 let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?;
783 let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?;
784 println!("TEST {} {:?}", len, buffer2);
785 */
786 }
9f46c7de 787
e9722f8b
WB
788 // create index.json
789 let file_list = file_list.iter()
790 .fold(vec![], |mut acc, (filename, stats)| {
791 acc.push(json!({
792 "filename": filename,
793 "size": stats.size,
794 "csum": proxmox::tools::digest_to_hex(&stats.csum),
795 }));
796 acc
797 });
2c3891d1 798
e9722f8b
WB
799 let index = json!({
800 "backup-type": backup_type,
801 "backup-id": backup_id,
802 "backup-time": backup_time.timestamp(),
803 "files": file_list,
804 });
2c3891d1 805
e9722f8b
WB
806 println!("Upload index.json to '{:?}'", repo);
807 let index_data = serde_json::to_string_pretty(&index)?.into();
808 client
809 .upload_blob_from_data(index_data, "index.json.blob", crypt_config.clone(), true, true)
810 .await?;
2c3891d1 811
e9722f8b 812 client.finish().await?;
c4ff3dce 813
e9722f8b
WB
814 let end_time = Local::now();
815 let elapsed = end_time.signed_duration_since(start_time);
816 println!("Duration: {}", elapsed);
3ec3ec3f 817
e9722f8b 818 println!("End Time: {}", end_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
3d5c11e5 819
e9722f8b
WB
820 Ok(Value::Null)
821 })
f98ea63d
DM
822}
823
d0a03d40 824fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
f98ea63d
DM
825
826 let mut result = vec![];
827
828 let data: Vec<&str> = arg.splitn(2, ':').collect();
829
bff11030 830 if data.len() != 2 {
8968258b
DM
831 result.push(String::from("root.pxar:/"));
832 result.push(String::from("etc.pxar:/etc"));
bff11030
DM
833 return result;
834 }
f98ea63d 835
496a6784 836 let files = tools::complete_file_name(data[1], param);
f98ea63d
DM
837
838 for file in files {
839 result.push(format!("{}:{}", data[0], file));
840 }
841
842 result
ff5d3707 843}
844
9f912493
DM
845fn restore(
846 param: Value,
847 _info: &ApiMethod,
dd5495d6 848 _rpcenv: &mut dyn RpcEnvironment,
9f912493 849) -> Result<Value, Error> {
e9722f8b
WB
850 async_main(restore_do(param))
851}
9f912493 852
e9722f8b 853async fn restore_do(param: Value) -> Result<Value, Error> {
2665cef7 854 let repo = extract_repository_from_value(&param)?;
9f912493 855
86eda3eb
DM
856 let verbose = param["verbose"].as_bool().unwrap_or(false);
857
46d5aa0a
DM
858 let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false);
859
d5c34d98
DM
860 let archive_name = tools::required_string_param(&param, "archive-name")?;
861
86eda3eb 862 let client = HttpClient::new(repo.host(), repo.user())?;
d0a03d40 863
d0a03d40 864 record_repository(&repo);
d5c34d98 865
9f912493 866 let path = tools::required_string_param(&param, "snapshot")?;
9f912493 867
86eda3eb 868 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
d5c34d98 869 let group = BackupGroup::parse(path)?;
9f912493 870
9e391bb7
DM
871 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
872 let result = client.get(&path, Some(json!({
d5c34d98
DM
873 "backup-type": group.backup_type(),
874 "backup-id": group.backup_id(),
e9722f8b 875 }))).await?;
9f912493 876
d5c34d98
DM
877 let list = result["data"].as_array().unwrap();
878 if list.len() == 0 {
879 bail!("backup group '{}' does not contain any snapshots:", path);
880 }
9f912493 881
86eda3eb 882 let epoch = list[0]["backup-time"].as_i64().unwrap();
fa5d6977 883 let backup_time = Utc.timestamp(epoch, 0);
86eda3eb 884 (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time)
d5c34d98
DM
885 } else {
886 let snapshot = BackupDir::parse(path)?;
86eda3eb
DM
887 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
888 };
9f912493 889
d5c34d98 890 let target = tools::required_string_param(&param, "target")?;
bf125261 891 let target = if target == "-" { None } else { Some(target) };
2ae7d196 892
86eda3eb 893 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
2ae7d196 894
86eda3eb
DM
895 let crypt_config = match keyfile {
896 None => None,
897 Some(path) => {
898 let (key, _) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
899 Some(Arc::new(CryptConfig::new(key)?))
900 }
901 };
d5c34d98 902
afb4cd28
DM
903 let server_archive_name = if archive_name.ends_with(".pxar") {
904 format!("{}.didx", archive_name)
905 } else if archive_name.ends_with(".img") {
906 format!("{}.fidx", archive_name)
907 } else {
f8100e96 908 format!("{}.blob", archive_name)
afb4cd28 909 };
9f912493 910
e9722f8b
WB
911 let client = client
912 .start_backup_reader(repo.store(), &backup_type, &backup_id, backup_time, true)
913 .await?;
86eda3eb 914
86eda3eb
DM
915 let tmpfile = std::fs::OpenOptions::new()
916 .write(true)
917 .read(true)
918 .custom_flags(libc::O_TMPFILE)
919 .open("/tmp")?;
920
02fcf372
DM
921 const INDEX_BLOB_NAME: &str = "index.json.blob";
922
e9722f8b 923 let index_data = client.download(INDEX_BLOB_NAME, Vec::with_capacity(64*1024)).await?;
02fcf372
DM
924 let blob = DataBlob::from_raw(index_data)?;
925 blob.verify_crc()?;
926 let backup_index_data = blob.decode(crypt_config.clone())?;
927 let backup_index: Value = serde_json::from_slice(&backup_index_data[..])?;
928
929 if server_archive_name == INDEX_BLOB_NAME {
930 if let Some(target) = target {
931 file_set_contents(target, &backup_index_data, None)?;
932 } else {
933 let stdout = std::io::stdout();
934 let mut writer = stdout.lock();
935 writer.write_all(&backup_index_data)
936 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
937 }
938
939 } else if server_archive_name.ends_with(".blob") {
2b92971f 940 let mut tmpfile = client.download(&server_archive_name, tmpfile).await?;
0d986280
DM
941 tmpfile.seek(SeekFrom::Start(0))?;
942 let mut reader = DataBlobReader::new(tmpfile, crypt_config)?;
f8100e96 943
bf125261 944 if let Some(target) = target {
0d986280
DM
945 let mut writer = std::fs::OpenOptions::new()
946 .write(true)
947 .create(true)
948 .create_new(true)
949 .open(target)
950 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
951 std::io::copy(&mut reader, &mut writer)?;
bf125261
DM
952 } else {
953 let stdout = std::io::stdout();
954 let mut writer = stdout.lock();
0d986280 955 std::io::copy(&mut reader, &mut writer)
bf125261
DM
956 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
957 }
f8100e96
DM
958
959 } else if server_archive_name.ends_with(".didx") {
e9722f8b 960 let tmpfile = client.download(&server_archive_name, tmpfile).await?;
86eda3eb 961
afb4cd28
DM
962 let index = DynamicIndexReader::new(tmpfile)
963 .map_err(|err| format_err!("unable to read dynamic index '{}' - {}", archive_name, err))?;
86eda3eb 964
f4bf7dfc
DM
965 let most_used = index.find_most_used_chunks(8);
966
967 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
968
afb4cd28 969 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
86eda3eb 970
bf125261 971 if let Some(target) = target {
86eda3eb 972
47651f95 973 let feature_flags = pxar::flags::DEFAULT;
bf125261
DM
974 let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags, |path| {
975 if verbose {
976 println!("{:?}", path);
977 }
978 Ok(())
979 });
6a879109
CE
980 decoder.set_allow_existing_dirs(allow_existing_dirs);
981
bf125261 982
fa7e957c 983 decoder.restore(Path::new(target), &Vec::new())?;
bf125261
DM
984 } else {
985 let stdout = std::io::stdout();
986 let mut writer = stdout.lock();
afb4cd28 987
bf125261
DM
988 std::io::copy(&mut reader, &mut writer)
989 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
990 }
afb4cd28 991 } else if server_archive_name.ends_with(".fidx") {
e9722f8b 992 let tmpfile = client.download(&server_archive_name, tmpfile).await?;
afb4cd28
DM
993
994 let index = FixedIndexReader::new(tmpfile)
995 .map_err(|err| format_err!("unable to read fixed index '{}' - {}", archive_name, err))?;
7dcbe051 996
f4bf7dfc
DM
997 let most_used = index.find_most_used_chunks(8);
998
999 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1000
afb4cd28
DM
1001 let mut reader = BufferedFixedReader::new(index, chunk_reader);
1002
bf125261
DM
1003 if let Some(target) = target {
1004 let mut writer = std::fs::OpenOptions::new()
1005 .write(true)
1006 .create(true)
1007 .create_new(true)
1008 .open(target)
1009 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
1010
1011 std::io::copy(&mut reader, &mut writer)
1012 .map_err(|err| format_err!("unable to store data - {}", err))?;
1013 } else {
1014 let stdout = std::io::stdout();
1015 let mut writer = stdout.lock();
afb4cd28 1016
bf125261
DM
1017 std::io::copy(&mut reader, &mut writer)
1018 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1019 }
45db6f89 1020 } else {
f8100e96 1021 bail!("unknown archive file extension (expected .pxar of .img)");
3031e44c 1022 }
fef44d4f
DM
1023
1024 Ok(Value::Null)
45db6f89
DM
1025}
1026
ec34f7eb
DM
1027fn upload_log(
1028 param: Value,
1029 _info: &ApiMethod,
1030 _rpcenv: &mut dyn RpcEnvironment,
1031) -> Result<Value, Error> {
1032
1033 let logfile = tools::required_string_param(&param, "logfile")?;
1034 let repo = extract_repository_from_value(&param)?;
1035
1036 let snapshot = tools::required_string_param(&param, "snapshot")?;
1037 let snapshot = BackupDir::parse(snapshot)?;
1038
1039 let mut client = HttpClient::new(repo.host(), repo.user())?;
1040
1041 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
1042
1043 let crypt_config = match keyfile {
1044 None => None,
1045 Some(path) => {
1046 let (key, _created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
1047 let crypt_config = CryptConfig::new(key)?;
9025312a 1048 Some(Arc::new(crypt_config))
ec34f7eb
DM
1049 }
1050 };
1051
e18a6c9e 1052 let data = file_get_contents(logfile)?;
ec34f7eb 1053
9025312a 1054 let blob = DataBlob::encode(&data, crypt_config, true)?;
ec34f7eb
DM
1055
1056 let raw_data = blob.into_inner();
1057
1058 let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store());
1059
1060 let args = json!({
1061 "backup-type": snapshot.group().backup_type(),
1062 "backup-id": snapshot.group().backup_id(),
1063 "backup-time": snapshot.backup_time().timestamp(),
1064 });
1065
1066 let body = hyper::Body::from(raw_data);
1067
e9722f8b
WB
1068 async_main(async move {
1069 client.upload("application/octet-stream", body, &path, Some(args)).await
1070 })
ec34f7eb
DM
1071}
1072
83b7db02 1073fn prune(
ea7a7ef2 1074 mut param: Value,
83b7db02 1075 _info: &ApiMethod,
dd5495d6 1076 _rpcenv: &mut dyn RpcEnvironment,
83b7db02
DM
1077) -> Result<Value, Error> {
1078
2665cef7 1079 let repo = extract_repository_from_value(&param)?;
83b7db02 1080
45cdce06 1081 let mut client = HttpClient::new(repo.host(), repo.user())?;
83b7db02 1082
d0a03d40 1083 let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
83b7db02 1084
9fdc3ef4
DM
1085 let group = tools::required_string_param(&param, "group")?;
1086 let group = BackupGroup::parse(group)?;
1087
ea7a7ef2
DM
1088 param.as_object_mut().unwrap().remove("repository");
1089 param.as_object_mut().unwrap().remove("group");
1090
1091 param["backup-type"] = group.backup_type().into();
1092 param["backup-id"] = group.backup_id().into();
83b7db02 1093
e9722f8b 1094 let _result = async_main(async move { client.post(&path, Some(param)).await })?;
83b7db02 1095
d0a03d40
DM
1096 record_repository(&repo);
1097
43a406fd 1098 Ok(Value::Null)
83b7db02
DM
1099}
1100
34a816cc
DM
1101fn status(
1102 param: Value,
1103 _info: &ApiMethod,
1104 _rpcenv: &mut dyn RpcEnvironment,
1105) -> Result<Value, Error> {
1106
1107 let repo = extract_repository_from_value(&param)?;
1108
1109 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
1110
1111 let client = HttpClient::new(repo.host(), repo.user())?;
1112
1113 let path = format!("api2/json/admin/datastore/{}/status", repo.store());
1114
e9722f8b 1115 let result = async_main(async move { client.get(&path, None).await })?;
34a816cc
DM
1116 let data = &result["data"];
1117
1118 record_repository(&repo);
1119
1120 if output_format == "text" {
1121 let total = data["total"].as_u64().unwrap();
1122 let used = data["used"].as_u64().unwrap();
1123 let avail = data["avail"].as_u64().unwrap();
1124 let roundup = total/200;
1125
1126 println!(
1127 "total: {} used: {} ({} %) available: {}",
1128 total,
1129 used,
1130 ((used+roundup)*100)/total,
1131 avail,
1132 );
1133 } else {
f6ede796 1134 format_and_print_result(data, &output_format);
34a816cc
DM
1135 }
1136
1137 Ok(Value::Null)
1138}
1139
5a2df000 1140// like get, but simply ignore errors and return Null instead
e9722f8b 1141async fn try_get(repo: &BackupRepository, url: &str) -> Value {
024f11bb 1142
45cdce06
DM
1143 let client = match HttpClient::new(repo.host(), repo.user()) {
1144 Ok(v) => v,
1145 _ => return Value::Null,
1146 };
b2388518 1147
e9722f8b 1148 let mut resp = match client.get(url, None).await {
b2388518
DM
1149 Ok(v) => v,
1150 _ => return Value::Null,
1151 };
1152
1153 if let Some(map) = resp.as_object_mut() {
1154 if let Some(data) = map.remove("data") {
1155 return data;
1156 }
1157 }
1158 Value::Null
1159}
1160
b2388518 1161fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
e9722f8b
WB
1162 async_main(async { complete_backup_group_do(param).await })
1163}
1164
1165async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> {
024f11bb 1166
b2388518
DM
1167 let mut result = vec![];
1168
2665cef7 1169 let repo = match extract_repository_from_map(param) {
b2388518 1170 Some(v) => v,
024f11bb
DM
1171 _ => return result,
1172 };
1173
b2388518
DM
1174 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
1175
e9722f8b 1176 let data = try_get(&repo, &path).await;
b2388518
DM
1177
1178 if let Some(list) = data.as_array() {
024f11bb 1179 for item in list {
98f0b972
DM
1180 if let (Some(backup_id), Some(backup_type)) =
1181 (item["backup-id"].as_str(), item["backup-type"].as_str())
1182 {
1183 result.push(format!("{}/{}", backup_type, backup_id));
024f11bb
DM
1184 }
1185 }
1186 }
1187
1188 result
1189}
1190
b2388518 1191fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
e9722f8b
WB
1192 async_main(async { complete_group_or_snapshot_do(arg, param).await })
1193}
1194
1195async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
b2388518 1196
b2388518 1197 if arg.matches('/').count() < 2 {
e9722f8b 1198 let groups = complete_backup_group_do(param).await;
543a260f 1199 let mut result = vec![];
b2388518
DM
1200 for group in groups {
1201 result.push(group.to_string());
1202 result.push(format!("{}/", group));
1203 }
1204 return result;
1205 }
1206
e9722f8b 1207 complete_backup_snapshot_do(param).await
543a260f 1208}
b2388518 1209
3fb53e07 1210fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
e9722f8b
WB
1211 async_main(async { complete_backup_snapshot_do(param).await })
1212}
1213
1214async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> {
543a260f
DM
1215
1216 let mut result = vec![];
1217
1218 let repo = match extract_repository_from_map(param) {
1219 Some(v) => v,
1220 _ => return result,
1221 };
1222
1223 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
b2388518 1224
e9722f8b 1225 let data = try_get(&repo, &path).await;
b2388518
DM
1226
1227 if let Some(list) = data.as_array() {
1228 for item in list {
1229 if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
1230 (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64())
1231 {
1232 let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
1233 result.push(snapshot.relative_path().to_str().unwrap().to_owned());
1234 }
1235 }
1236 }
1237
1238 result
1239}
1240
45db6f89 1241fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
e9722f8b
WB
1242 async_main(async { complete_server_file_name_do(param).await })
1243}
1244
1245async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> {
08dc340a
DM
1246
1247 let mut result = vec![];
1248
2665cef7 1249 let repo = match extract_repository_from_map(param) {
08dc340a
DM
1250 Some(v) => v,
1251 _ => return result,
1252 };
1253
1254 let snapshot = match param.get("snapshot") {
1255 Some(path) => {
1256 match BackupDir::parse(path) {
1257 Ok(v) => v,
1258 _ => return result,
1259 }
1260 }
1261 _ => return result,
1262 };
1263
1264 let query = tools::json_object_to_query(json!({
1265 "backup-type": snapshot.group().backup_type(),
1266 "backup-id": snapshot.group().backup_id(),
1267 "backup-time": snapshot.backup_time().timestamp(),
1268 })).unwrap();
1269
1270 let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query);
1271
e9722f8b 1272 let data = try_get(&repo, &path).await;
08dc340a
DM
1273
1274 if let Some(list) = data.as_array() {
1275 for item in list {
c4f025eb 1276 if let Some(filename) = item["filename"].as_str() {
08dc340a
DM
1277 result.push(filename.to_owned());
1278 }
1279 }
1280 }
1281
45db6f89
DM
1282 result
1283}
1284
1285fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
52c171e4 1286 complete_server_file_name(arg, param)
e9722f8b
WB
1287 .iter()
1288 .map(|v| strip_server_file_expenstion(&v))
1289 .collect()
08dc340a
DM
1290}
1291
49811347
DM
1292fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
1293
1294 let mut result = vec![];
1295
1296 let mut size = 64;
1297 loop {
1298 result.push(size.to_string());
1299 size = size * 2;
1300 if size > 4096 { break; }
1301 }
1302
1303 result
1304}
1305
826f309b 1306fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
ff5d3707 1307
f2401311
DM
1308 // fixme: implement other input methods
1309
1310 use std::env::VarError::*;
1311 match std::env::var("PBS_ENCRYPTION_PASSWORD") {
826f309b 1312 Ok(p) => return Ok(p.as_bytes().to_vec()),
f2401311
DM
1313 Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
1314 Err(NotPresent) => {
1315 // Try another method
1316 }
1317 }
1318
1319 // If we're on a TTY, query the user for a password
1320 if crate::tools::tty::stdin_isatty() {
826f309b 1321 return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?);
f2401311
DM
1322 }
1323
1324 bail!("no password input mechanism available");
1325}
1326
ac716234
DM
1327fn key_create(
1328 param: Value,
1329 _info: &ApiMethod,
1330 _rpcenv: &mut dyn RpcEnvironment,
1331) -> Result<Value, Error> {
1332
9b06db45
DM
1333 let path = tools::required_string_param(&param, "path")?;
1334 let path = PathBuf::from(path);
ac716234 1335
181f097a 1336 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
ac716234
DM
1337
1338 let key = proxmox::sys::linux::random_data(32)?;
1339
181f097a
DM
1340 if kdf == "scrypt" {
1341 // always read passphrase from tty
1342 if !crate::tools::tty::stdin_isatty() {
1343 bail!("unable to read passphrase - no tty");
1344 }
ac716234 1345
181f097a
DM
1346 let password = crate::tools::tty::read_password("Encryption Key Password: ")?;
1347
ab44acff 1348 let key_config = encrypt_key_with_passphrase(&key, &password)?;
37c5a175 1349
ab44acff 1350 store_key_config(&path, false, key_config)?;
181f097a
DM
1351
1352 Ok(Value::Null)
1353 } else if kdf == "none" {
1354 let created = Local.timestamp(Local::now().timestamp(), 0);
1355
1356 store_key_config(&path, false, KeyConfig {
1357 kdf: None,
1358 created,
ab44acff 1359 modified: created,
181f097a
DM
1360 data: key,
1361 })?;
1362
1363 Ok(Value::Null)
1364 } else {
1365 unreachable!();
1366 }
ac716234
DM
1367}
1368
9f46c7de
DM
1369fn master_pubkey_path() -> Result<PathBuf, Error> {
1370 let base = BaseDirectories::with_prefix("proxmox-backup")?;
1371
1372 // usually $HOME/.config/proxmox-backup/master-public.pem
1373 let path = base.place_config_file("master-public.pem")?;
1374
1375 Ok(path)
1376}
1377
3ea8bfc9
DM
1378fn key_import_master_pubkey(
1379 param: Value,
1380 _info: &ApiMethod,
1381 _rpcenv: &mut dyn RpcEnvironment,
1382) -> Result<Value, Error> {
1383
1384 let path = tools::required_string_param(&param, "path")?;
1385 let path = PathBuf::from(path);
1386
e18a6c9e 1387 let pem_data = file_get_contents(&path)?;
3ea8bfc9
DM
1388
1389 if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
1390 bail!("Unable to decode PEM data - {}", err);
1391 }
1392
9f46c7de 1393 let target_path = master_pubkey_path()?;
3ea8bfc9 1394
e18a6c9e 1395 file_set_contents(&target_path, &pem_data, None)?;
3ea8bfc9
DM
1396
1397 println!("Imported public master key to {:?}", target_path);
1398
1399 Ok(Value::Null)
1400}
1401
37c5a175
DM
1402fn key_create_master_key(
1403 _param: Value,
1404 _info: &ApiMethod,
1405 _rpcenv: &mut dyn RpcEnvironment,
1406) -> Result<Value, Error> {
1407
1408 // we need a TTY to query the new password
1409 if !crate::tools::tty::stdin_isatty() {
1410 bail!("unable to create master key - no tty");
1411 }
1412
1413 let rsa = openssl::rsa::Rsa::generate(4096)?;
1414 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
1415
1416 let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?;
1417 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
1418
1419 if new_pw != verify_pw {
1420 bail!("Password verification fail!");
1421 }
1422
1423 if new_pw.len() < 5 {
1424 bail!("Password is too short!");
1425 }
1426
1427 let pub_key: Vec<u8> = pkey.public_key_to_pem()?;
1428 let filename_pub = "master-public.pem";
1429 println!("Writing public master key to {}", filename_pub);
e18a6c9e 1430 file_set_contents(filename_pub, pub_key.as_slice(), None)?;
37c5a175
DM
1431
1432 let cipher = openssl::symm::Cipher::aes_256_cbc();
1433 let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?;
1434
1435 let filename_priv = "master-private.pem";
1436 println!("Writing private master key to {}", filename_priv);
e18a6c9e 1437 file_set_contents(filename_priv, priv_key.as_slice(), None)?;
37c5a175
DM
1438
1439 Ok(Value::Null)
1440}
ac716234
DM
1441
1442fn key_change_passphrase(
1443 param: Value,
1444 _info: &ApiMethod,
1445 _rpcenv: &mut dyn RpcEnvironment,
1446) -> Result<Value, Error> {
1447
9b06db45
DM
1448 let path = tools::required_string_param(&param, "path")?;
1449 let path = PathBuf::from(path);
ac716234 1450
181f097a
DM
1451 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
1452
ac716234
DM
1453 // we need a TTY to query the new password
1454 if !crate::tools::tty::stdin_isatty() {
1455 bail!("unable to change passphrase - no tty");
1456 }
1457
ab44acff 1458 let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
ac716234 1459
181f097a 1460 if kdf == "scrypt" {
ac716234 1461
181f097a
DM
1462 let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?;
1463 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
ac716234 1464
181f097a
DM
1465 if new_pw != verify_pw {
1466 bail!("Password verification fail!");
1467 }
1468
1469 if new_pw.len() < 5 {
1470 bail!("Password is too short!");
1471 }
ac716234 1472
ab44acff
DM
1473 let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?;
1474 new_key_config.created = created; // keep original value
1475
1476 store_key_config(&path, true, new_key_config)?;
ac716234 1477
181f097a
DM
1478 Ok(Value::Null)
1479 } else if kdf == "none" {
ab44acff 1480 let modified = Local.timestamp(Local::now().timestamp(), 0);
181f097a
DM
1481
1482 store_key_config(&path, true, KeyConfig {
1483 kdf: None,
ab44acff
DM
1484 created, // keep original value
1485 modified,
6d0983db 1486 data: key.to_vec(),
181f097a
DM
1487 })?;
1488
1489 Ok(Value::Null)
1490 } else {
1491 unreachable!();
1492 }
f2401311
DM
1493}
1494
1495fn key_mgmt_cli() -> CliCommandMap {
1496
181f097a
DM
1497 let kdf_schema: Arc<Schema> = Arc::new(
1498 StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.")
1499 .format(Arc::new(ApiStringFormat::Enum(&["scrypt", "none"])))
1500 .default("scrypt")
1501 .into()
1502 );
1503
f2401311
DM
1504 let key_create_cmd_def = CliCommand::new(
1505 ApiMethod::new(
1506 key_create,
1507 ObjectSchema::new("Create a new encryption key.")
9b06db45 1508 .required("path", StringSchema::new("File system path."))
181f097a 1509 .optional("kdf", kdf_schema.clone())
f2401311 1510 ))
9b06db45
DM
1511 .arg_param(vec!["path"])
1512 .completion_cb("path", tools::complete_file_name);
f2401311 1513
ac716234
DM
1514 let key_change_passphrase_cmd_def = CliCommand::new(
1515 ApiMethod::new(
1516 key_change_passphrase,
1517 ObjectSchema::new("Change the passphrase required to decrypt the key.")
9b06db45 1518 .required("path", StringSchema::new("File system path."))
181f097a 1519 .optional("kdf", kdf_schema.clone())
9b06db45
DM
1520 ))
1521 .arg_param(vec!["path"])
1522 .completion_cb("path", tools::complete_file_name);
ac716234 1523
37c5a175
DM
1524 let key_create_master_key_cmd_def = CliCommand::new(
1525 ApiMethod::new(
1526 key_create_master_key,
1527 ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.")
1528 ));
1529
3ea8bfc9
DM
1530 let key_import_master_pubkey_cmd_def = CliCommand::new(
1531 ApiMethod::new(
1532 key_import_master_pubkey,
1533 ObjectSchema::new("Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.")
1534 .required("path", StringSchema::new("File system path."))
1535 ))
1536 .arg_param(vec!["path"])
1537 .completion_cb("path", tools::complete_file_name);
1538
f2401311 1539 let cmd_def = CliCommandMap::new()
ac716234 1540 .insert("create".to_owned(), key_create_cmd_def.into())
37c5a175 1541 .insert("create-master-key".to_owned(), key_create_master_key_cmd_def.into())
3ea8bfc9 1542 .insert("import-master-pubkey".to_owned(), key_import_master_pubkey_cmd_def.into())
ac716234 1543 .insert("change-passphrase".to_owned(), key_change_passphrase_cmd_def.into());
f2401311
DM
1544
1545 cmd_def
1546}
1547
f2401311 1548fn main() {
33d64b81 1549
25f1650b
DM
1550 let backup_source_schema: Arc<Schema> = Arc::new(
1551 StringSchema::new("Backup source specification ([<label>:<path>]).")
1552 .format(Arc::new(ApiStringFormat::Pattern(&BACKUPSPEC_REGEX)))
1553 .into()
1554 );
1555
597a9203 1556 let backup_cmd_def = CliCommand::new(
ff5d3707 1557 ApiMethod::new(
bcd879cf 1558 create_backup,
597a9203 1559 ObjectSchema::new("Create (host) backup.")
ae0be2dd
DM
1560 .required(
1561 "backupspec",
1562 ArraySchema::new(
74cdb521 1563 "List of backup source specifications ([<label.ext>:<path>] ...)",
25f1650b 1564 backup_source_schema,
ae0be2dd
DM
1565 ).min_length(1)
1566 )
2665cef7 1567 .optional("repository", REPO_URL_SCHEMA.clone())
2eeaacb9
DM
1568 .optional(
1569 "include-dev",
1570 ArraySchema::new(
1571 "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.",
1572 StringSchema::new("Path to file.").into()
1573 )
1574 )
6d0983db
DM
1575 .optional(
1576 "keyfile",
1577 StringSchema::new("Path to encryption key. All data will be encrypted using this key."))
219ef0e6
DM
1578 .optional(
1579 "verbose",
1580 BooleanSchema::new("Verbose output.").default(false))
5b72c9b4
DM
1581 .optional(
1582 "skip-lost-and-found",
1583 BooleanSchema::new("Skip lost+found directory").default(false))
fba30411 1584 .optional(
bbf9e7e9
DM
1585 "backup-type",
1586 BACKUP_TYPE_SCHEMA.clone()
1587 )
1588 .optional(
1589 "backup-id",
1590 BACKUP_ID_SCHEMA.clone()
1591 )
ca5d0b61
DM
1592 .optional(
1593 "backup-time",
bbf9e7e9 1594 BACKUP_TIME_SCHEMA.clone()
ca5d0b61 1595 )
2d9d143a
DM
1596 .optional(
1597 "chunk-size",
1598 IntegerSchema::new("Chunk size in KB. Must be a power of 2.")
1599 .minimum(64)
1600 .maximum(4096)
1601 .default(4096)
1602 )
ff5d3707 1603 ))
2665cef7 1604 .arg_param(vec!["backupspec"])
d0a03d40 1605 .completion_cb("repository", complete_repository)
49811347 1606 .completion_cb("backupspec", complete_backup_source)
6d0983db 1607 .completion_cb("keyfile", tools::complete_file_name)
49811347 1608 .completion_cb("chunk-size", complete_chunk_size);
f8838fe9 1609
ec34f7eb
DM
1610 let upload_log_cmd_def = CliCommand::new(
1611 ApiMethod::new(
1612 upload_log,
1613 ObjectSchema::new("Upload backup log file.")
1614 .required("snapshot", StringSchema::new("Snapshot path."))
1615 .required("logfile", StringSchema::new("The path to the log file you want to upload."))
1616 .optional("repository", REPO_URL_SCHEMA.clone())
1617 .optional(
1618 "keyfile",
1619 StringSchema::new("Path to encryption key. All data will be encrypted using this key."))
1620 ))
1621 .arg_param(vec!["snapshot", "logfile"])
543a260f 1622 .completion_cb("snapshot", complete_backup_snapshot)
ec34f7eb
DM
1623 .completion_cb("logfile", tools::complete_file_name)
1624 .completion_cb("keyfile", tools::complete_file_name)
1625 .completion_cb("repository", complete_repository);
1626
41c039e1
DM
1627 let list_cmd_def = CliCommand::new(
1628 ApiMethod::new(
812c6f87
DM
1629 list_backup_groups,
1630 ObjectSchema::new("List backup groups.")
2665cef7 1631 .optional("repository", REPO_URL_SCHEMA.clone())
34a816cc 1632 .optional("output-format", OUTPUT_FORMAT.clone())
41c039e1 1633 ))
d0a03d40 1634 .completion_cb("repository", complete_repository);
41c039e1 1635
184f17af
DM
1636 let snapshots_cmd_def = CliCommand::new(
1637 ApiMethod::new(
1638 list_snapshots,
1639 ObjectSchema::new("List backup snapshots.")
15c847f1 1640 .optional("group", StringSchema::new("Backup group."))
2665cef7 1641 .optional("repository", REPO_URL_SCHEMA.clone())
34a816cc 1642 .optional("output-format", OUTPUT_FORMAT.clone())
184f17af 1643 ))
2665cef7 1644 .arg_param(vec!["group"])
024f11bb 1645 .completion_cb("group", complete_backup_group)
d0a03d40 1646 .completion_cb("repository", complete_repository);
184f17af 1647
6f62c924
DM
1648 let forget_cmd_def = CliCommand::new(
1649 ApiMethod::new(
1650 forget_snapshots,
1651 ObjectSchema::new("Forget (remove) backup snapshots.")
6f62c924 1652 .required("snapshot", StringSchema::new("Snapshot path."))
2665cef7 1653 .optional("repository", REPO_URL_SCHEMA.clone())
6f62c924 1654 ))
2665cef7 1655 .arg_param(vec!["snapshot"])
b2388518 1656 .completion_cb("repository", complete_repository)
543a260f 1657 .completion_cb("snapshot", complete_backup_snapshot);
6f62c924 1658
8cc0d6af
DM
1659 let garbage_collect_cmd_def = CliCommand::new(
1660 ApiMethod::new(
1661 start_garbage_collection,
1662 ObjectSchema::new("Start garbage collection for a specific repository.")
2665cef7 1663 .optional("repository", REPO_URL_SCHEMA.clone())
8cc0d6af 1664 ))
d0a03d40 1665 .completion_cb("repository", complete_repository);
8cc0d6af 1666
9f912493
DM
1667 let restore_cmd_def = CliCommand::new(
1668 ApiMethod::new(
1669 restore,
1670 ObjectSchema::new("Restore backup repository.")
d5c34d98
DM
1671 .required("snapshot", StringSchema::new("Group/Snapshot path."))
1672 .required("archive-name", StringSchema::new("Backup archive name."))
bf125261
DM
1673 .required("target", StringSchema::new(r###"Target directory path. Use '-' to write to stdandard output.
1674
1675We do not extraxt '.pxar' archives when writing to stdandard output.
1676
1677"###
1678 ))
46d5aa0a
DM
1679 .optional(
1680 "allow-existing-dirs",
1681 BooleanSchema::new("Do not fail if directories already exists.").default(false))
2665cef7 1682 .optional("repository", REPO_URL_SCHEMA.clone())
86eda3eb
DM
1683 .optional("keyfile", StringSchema::new("Path to encryption key."))
1684 .optional(
1685 "verbose",
1686 BooleanSchema::new("Verbose output.").default(false)
1687 )
9f912493 1688 ))
2665cef7 1689 .arg_param(vec!["snapshot", "archive-name", "target"])
b2388518 1690 .completion_cb("repository", complete_repository)
08dc340a
DM
1691 .completion_cb("snapshot", complete_group_or_snapshot)
1692 .completion_cb("archive-name", complete_archive_name)
1693 .completion_cb("target", tools::complete_file_name);
9f912493 1694
52c171e4
DM
1695 let files_cmd_def = CliCommand::new(
1696 ApiMethod::new(
1697 list_snapshot_files,
1698 ObjectSchema::new("List snapshot files.")
1699 .required("snapshot", StringSchema::new("Snapshot path."))
cec17a3e 1700 .optional("repository", REPO_URL_SCHEMA.clone())
52c171e4
DM
1701 .optional("output-format", OUTPUT_FORMAT.clone())
1702 ))
1703 .arg_param(vec!["snapshot"])
1704 .completion_cb("repository", complete_repository)
543a260f 1705 .completion_cb("snapshot", complete_backup_snapshot);
52c171e4 1706
9049a8cf
DM
1707 let catalog_cmd_def = CliCommand::new(
1708 ApiMethod::new(
1709 dump_catalog,
1710 ObjectSchema::new("Dump catalog.")
1711 .required("snapshot", StringSchema::new("Snapshot path."))
1712 .optional("repository", REPO_URL_SCHEMA.clone())
1713 ))
1714 .arg_param(vec!["snapshot"])
1715 .completion_cb("repository", complete_repository)
1716 .completion_cb("snapshot", complete_backup_snapshot);
1717
83b7db02
DM
1718 let prune_cmd_def = CliCommand::new(
1719 ApiMethod::new(
1720 prune,
1721 proxmox_backup::api2::admin::datastore::add_common_prune_prameters(
1722 ObjectSchema::new("Prune backup repository.")
9fdc3ef4 1723 .required("group", StringSchema::new("Backup group."))
2665cef7 1724 .optional("repository", REPO_URL_SCHEMA.clone())
83b7db02
DM
1725 )
1726 ))
9fdc3ef4
DM
1727 .arg_param(vec!["group"])
1728 .completion_cb("group", complete_backup_group)
d0a03d40 1729 .completion_cb("repository", complete_repository);
9f912493 1730
34a816cc
DM
1731 let status_cmd_def = CliCommand::new(
1732 ApiMethod::new(
1733 status,
1734 ObjectSchema::new("Get repository status.")
1735 .optional("repository", REPO_URL_SCHEMA.clone())
1736 .optional("output-format", OUTPUT_FORMAT.clone())
1737 ))
1738 .completion_cb("repository", complete_repository);
1739
e240d8be
DM
1740 let login_cmd_def = CliCommand::new(
1741 ApiMethod::new(
1742 api_login,
1743 ObjectSchema::new("Try to login. If successful, store ticket.")
1744 .optional("repository", REPO_URL_SCHEMA.clone())
1745 ))
1746 .completion_cb("repository", complete_repository);
1747
1748 let logout_cmd_def = CliCommand::new(
1749 ApiMethod::new(
1750 api_logout,
1751 ObjectSchema::new("Logout (delete stored ticket).")
1752 .optional("repository", REPO_URL_SCHEMA.clone())
1753 ))
1754 .completion_cb("repository", complete_repository);
1755
41c039e1 1756 let cmd_def = CliCommandMap::new()
597a9203 1757 .insert("backup".to_owned(), backup_cmd_def.into())
ec34f7eb 1758 .insert("upload-log".to_owned(), upload_log_cmd_def.into())
6f62c924 1759 .insert("forget".to_owned(), forget_cmd_def.into())
9049a8cf 1760 .insert("catalog".to_owned(), catalog_cmd_def.into())
8cc0d6af 1761 .insert("garbage-collect".to_owned(), garbage_collect_cmd_def.into())
83b7db02 1762 .insert("list".to_owned(), list_cmd_def.into())
e240d8be
DM
1763 .insert("login".to_owned(), login_cmd_def.into())
1764 .insert("logout".to_owned(), logout_cmd_def.into())
184f17af 1765 .insert("prune".to_owned(), prune_cmd_def.into())
9f912493 1766 .insert("restore".to_owned(), restore_cmd_def.into())
f2401311 1767 .insert("snapshots".to_owned(), snapshots_cmd_def.into())
52c171e4 1768 .insert("files".to_owned(), files_cmd_def.into())
34a816cc 1769 .insert("status".to_owned(), status_cmd_def.into())
f2401311 1770 .insert("key".to_owned(), key_mgmt_cli().into());
a914a774 1771
e9722f8b
WB
1772 run_cli_command(cmd_def.into());
1773}
496a6784 1774
e9722f8b
WB
1775fn async_main<F: Future>(fut: F) -> <F as Future>::Output {
1776 let rt = tokio::runtime::Runtime::new().unwrap();
1777 let ret = rt.block_on(fut);
1778 rt.shutdown_now();
1779 ret
ff5d3707 1780}