]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-client.rs
src/bin/proxmox-backup-client.rs: code cleanup - factor out some functions
[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
a40220c0
DM
853async fn download_index_blob(client: Arc<BackupReader>, crypt_config: Option<Arc<CryptConfig>>) -> Result<Vec<u8>, Error> {
854
855 let index_data = client.download(INDEX_BLOB_NAME, Vec::with_capacity(64*1024)).await?;
856 let blob = DataBlob::from_raw(index_data)?;
857 blob.verify_crc()?;
858 blob.decode(crypt_config)
859}
860
861fn verify_index_file(backup_index: &Value, name: &str, csum: &[u8; 32], size: u64) -> Result<(), Error> {
862
863 let files = backup_index["files"]
864 .as_array()
865 .ok_or_else(|| format_err!("mailformed index - missing 'files' property"))?;
866
867 let info = files.iter().find(|v| {
868 match v["filename"].as_str() {
869 Some(filename) => filename == name,
870 None => false,
871 }
872 });
873
874 let info = match info {
875 None => bail!("index does not contain file '{}'", name),
876 Some(info) => info,
877 };
878
879 match info["size"].as_u64() {
880 None => bail!("index does not contain property 'size' for file '{}'", name),
881 Some(expected_size) => {
882 if expected_size != size {
883 bail!("verify index failed - wrong size for file '{}'", name);
884 }
885 }
886 };
887
888 match info["csum"].as_str() {
889 None => bail!("index does not contain property 'csum' for file '{}'", name),
890 Some(expected_csum) => {
891 let expected_csum = &proxmox::tools::hex_to_digest(expected_csum)?;
892 if expected_csum != csum {
893 bail!("verify index failed - wrong checksum for file '{}'", name);
894 }
895 }
896 };
897
898 Ok(())
899}
900
e9722f8b 901async fn restore_do(param: Value) -> Result<Value, Error> {
2665cef7 902 let repo = extract_repository_from_value(&param)?;
9f912493 903
86eda3eb
DM
904 let verbose = param["verbose"].as_bool().unwrap_or(false);
905
46d5aa0a
DM
906 let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false);
907
d5c34d98
DM
908 let archive_name = tools::required_string_param(&param, "archive-name")?;
909
86eda3eb 910 let client = HttpClient::new(repo.host(), repo.user())?;
d0a03d40 911
d0a03d40 912 record_repository(&repo);
d5c34d98 913
9f912493 914 let path = tools::required_string_param(&param, "snapshot")?;
9f912493 915
86eda3eb 916 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
d5c34d98 917 let group = BackupGroup::parse(path)?;
9f912493 918
9e391bb7
DM
919 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
920 let result = client.get(&path, Some(json!({
d5c34d98
DM
921 "backup-type": group.backup_type(),
922 "backup-id": group.backup_id(),
e9722f8b 923 }))).await?;
9f912493 924
d5c34d98
DM
925 let list = result["data"].as_array().unwrap();
926 if list.len() == 0 {
927 bail!("backup group '{}' does not contain any snapshots:", path);
928 }
9f912493 929
86eda3eb 930 let epoch = list[0]["backup-time"].as_i64().unwrap();
fa5d6977 931 let backup_time = Utc.timestamp(epoch, 0);
86eda3eb 932 (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time)
d5c34d98
DM
933 } else {
934 let snapshot = BackupDir::parse(path)?;
86eda3eb
DM
935 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
936 };
9f912493 937
d5c34d98 938 let target = tools::required_string_param(&param, "target")?;
bf125261 939 let target = if target == "-" { None } else { Some(target) };
2ae7d196 940
86eda3eb 941 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
2ae7d196 942
86eda3eb
DM
943 let crypt_config = match keyfile {
944 None => None,
945 Some(path) => {
946 let (key, _) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
947 Some(Arc::new(CryptConfig::new(key)?))
948 }
949 };
d5c34d98 950
afb4cd28
DM
951 let server_archive_name = if archive_name.ends_with(".pxar") {
952 format!("{}.didx", archive_name)
953 } else if archive_name.ends_with(".img") {
954 format!("{}.fidx", archive_name)
955 } else {
f8100e96 956 format!("{}.blob", archive_name)
afb4cd28 957 };
9f912493 958
e9722f8b
WB
959 let client = client
960 .start_backup_reader(repo.store(), &backup_type, &backup_id, backup_time, true)
961 .await?;
86eda3eb 962
86eda3eb
DM
963 let tmpfile = std::fs::OpenOptions::new()
964 .write(true)
965 .read(true)
966 .custom_flags(libc::O_TMPFILE)
967 .open("/tmp")?;
968
df65bd3d 969
a40220c0
DM
970 let backup_index_data = download_index_blob(client.clone(), crypt_config.clone()).await?;
971 let backup_index: Value = serde_json::from_slice(&backup_index_data[..])?;
02fcf372
DM
972
973 if server_archive_name == INDEX_BLOB_NAME {
974 if let Some(target) = target {
975 file_set_contents(target, &backup_index_data, None)?;
976 } else {
977 let stdout = std::io::stdout();
978 let mut writer = stdout.lock();
979 writer.write_all(&backup_index_data)
980 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
981 }
982
983 } else if server_archive_name.ends_with(".blob") {
2b92971f 984 let mut tmpfile = client.download(&server_archive_name, tmpfile).await?;
0d986280
DM
985 tmpfile.seek(SeekFrom::Start(0))?;
986 let mut reader = DataBlobReader::new(tmpfile, crypt_config)?;
f8100e96 987
bf125261 988 if let Some(target) = target {
0d986280
DM
989 let mut writer = std::fs::OpenOptions::new()
990 .write(true)
991 .create(true)
992 .create_new(true)
993 .open(target)
994 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
995 std::io::copy(&mut reader, &mut writer)?;
bf125261
DM
996 } else {
997 let stdout = std::io::stdout();
998 let mut writer = stdout.lock();
0d986280 999 std::io::copy(&mut reader, &mut writer)
bf125261
DM
1000 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1001 }
f8100e96
DM
1002
1003 } else if server_archive_name.ends_with(".didx") {
e9722f8b 1004 let tmpfile = client.download(&server_archive_name, tmpfile).await?;
86eda3eb 1005
afb4cd28
DM
1006 let index = DynamicIndexReader::new(tmpfile)
1007 .map_err(|err| format_err!("unable to read dynamic index '{}' - {}", archive_name, err))?;
86eda3eb 1008
df65bd3d
DM
1009 // Note: do not use values stored in index (not trusted) - instead, computed them again
1010 let (csum, size) = index.compute_csum();
1011
a40220c0 1012 verify_index_file(&backup_index, &server_archive_name, &csum, size)?;
df65bd3d 1013
f4bf7dfc
DM
1014 let most_used = index.find_most_used_chunks(8);
1015
1016 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1017
afb4cd28 1018 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
86eda3eb 1019
bf125261 1020 if let Some(target) = target {
86eda3eb 1021
47651f95 1022 let feature_flags = pxar::flags::DEFAULT;
bf125261
DM
1023 let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags, |path| {
1024 if verbose {
1025 println!("{:?}", path);
1026 }
1027 Ok(())
1028 });
6a879109
CE
1029 decoder.set_allow_existing_dirs(allow_existing_dirs);
1030
bf125261 1031
fa7e957c 1032 decoder.restore(Path::new(target), &Vec::new())?;
bf125261
DM
1033 } else {
1034 let stdout = std::io::stdout();
1035 let mut writer = stdout.lock();
afb4cd28 1036
bf125261
DM
1037 std::io::copy(&mut reader, &mut writer)
1038 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1039 }
afb4cd28 1040 } else if server_archive_name.ends_with(".fidx") {
e9722f8b 1041 let tmpfile = client.download(&server_archive_name, tmpfile).await?;
afb4cd28
DM
1042
1043 let index = FixedIndexReader::new(tmpfile)
1044 .map_err(|err| format_err!("unable to read fixed index '{}' - {}", archive_name, err))?;
7dcbe051 1045
df65bd3d
DM
1046 // Note: do not use values stored in index (not trusted) - instead, computed them again
1047 let (csum, size) = index.compute_csum();
1048
a40220c0 1049 verify_index_file(&backup_index, &server_archive_name, &csum, size)?;
df65bd3d 1050
f4bf7dfc
DM
1051 let most_used = index.find_most_used_chunks(8);
1052
1053 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1054
afb4cd28
DM
1055 let mut reader = BufferedFixedReader::new(index, chunk_reader);
1056
bf125261
DM
1057 if let Some(target) = target {
1058 let mut writer = std::fs::OpenOptions::new()
1059 .write(true)
1060 .create(true)
1061 .create_new(true)
1062 .open(target)
1063 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
1064
1065 std::io::copy(&mut reader, &mut writer)
1066 .map_err(|err| format_err!("unable to store data - {}", err))?;
1067 } else {
1068 let stdout = std::io::stdout();
1069 let mut writer = stdout.lock();
afb4cd28 1070
bf125261
DM
1071 std::io::copy(&mut reader, &mut writer)
1072 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1073 }
45db6f89 1074 } else {
f8100e96 1075 bail!("unknown archive file extension (expected .pxar of .img)");
3031e44c 1076 }
fef44d4f
DM
1077
1078 Ok(Value::Null)
45db6f89
DM
1079}
1080
ec34f7eb
DM
1081fn upload_log(
1082 param: Value,
1083 _info: &ApiMethod,
1084 _rpcenv: &mut dyn RpcEnvironment,
1085) -> Result<Value, Error> {
1086
1087 let logfile = tools::required_string_param(&param, "logfile")?;
1088 let repo = extract_repository_from_value(&param)?;
1089
1090 let snapshot = tools::required_string_param(&param, "snapshot")?;
1091 let snapshot = BackupDir::parse(snapshot)?;
1092
1093 let mut client = HttpClient::new(repo.host(), repo.user())?;
1094
1095 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
1096
1097 let crypt_config = match keyfile {
1098 None => None,
1099 Some(path) => {
1100 let (key, _created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
1101 let crypt_config = CryptConfig::new(key)?;
9025312a 1102 Some(Arc::new(crypt_config))
ec34f7eb
DM
1103 }
1104 };
1105
e18a6c9e 1106 let data = file_get_contents(logfile)?;
ec34f7eb 1107
9025312a 1108 let blob = DataBlob::encode(&data, crypt_config, true)?;
ec34f7eb
DM
1109
1110 let raw_data = blob.into_inner();
1111
1112 let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store());
1113
1114 let args = json!({
1115 "backup-type": snapshot.group().backup_type(),
1116 "backup-id": snapshot.group().backup_id(),
1117 "backup-time": snapshot.backup_time().timestamp(),
1118 });
1119
1120 let body = hyper::Body::from(raw_data);
1121
e9722f8b
WB
1122 async_main(async move {
1123 client.upload("application/octet-stream", body, &path, Some(args)).await
1124 })
ec34f7eb
DM
1125}
1126
83b7db02 1127fn prune(
ea7a7ef2 1128 mut param: Value,
83b7db02 1129 _info: &ApiMethod,
dd5495d6 1130 _rpcenv: &mut dyn RpcEnvironment,
83b7db02
DM
1131) -> Result<Value, Error> {
1132
2665cef7 1133 let repo = extract_repository_from_value(&param)?;
83b7db02 1134
45cdce06 1135 let mut client = HttpClient::new(repo.host(), repo.user())?;
83b7db02 1136
d0a03d40 1137 let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
83b7db02 1138
9fdc3ef4
DM
1139 let group = tools::required_string_param(&param, "group")?;
1140 let group = BackupGroup::parse(group)?;
1141
ea7a7ef2
DM
1142 param.as_object_mut().unwrap().remove("repository");
1143 param.as_object_mut().unwrap().remove("group");
1144
1145 param["backup-type"] = group.backup_type().into();
1146 param["backup-id"] = group.backup_id().into();
83b7db02 1147
e9722f8b 1148 let _result = async_main(async move { client.post(&path, Some(param)).await })?;
83b7db02 1149
d0a03d40
DM
1150 record_repository(&repo);
1151
43a406fd 1152 Ok(Value::Null)
83b7db02
DM
1153}
1154
34a816cc
DM
1155fn status(
1156 param: Value,
1157 _info: &ApiMethod,
1158 _rpcenv: &mut dyn RpcEnvironment,
1159) -> Result<Value, Error> {
1160
1161 let repo = extract_repository_from_value(&param)?;
1162
1163 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
1164
1165 let client = HttpClient::new(repo.host(), repo.user())?;
1166
1167 let path = format!("api2/json/admin/datastore/{}/status", repo.store());
1168
e9722f8b 1169 let result = async_main(async move { client.get(&path, None).await })?;
34a816cc
DM
1170 let data = &result["data"];
1171
1172 record_repository(&repo);
1173
1174 if output_format == "text" {
1175 let total = data["total"].as_u64().unwrap();
1176 let used = data["used"].as_u64().unwrap();
1177 let avail = data["avail"].as_u64().unwrap();
1178 let roundup = total/200;
1179
1180 println!(
1181 "total: {} used: {} ({} %) available: {}",
1182 total,
1183 used,
1184 ((used+roundup)*100)/total,
1185 avail,
1186 );
1187 } else {
f6ede796 1188 format_and_print_result(data, &output_format);
34a816cc
DM
1189 }
1190
1191 Ok(Value::Null)
1192}
1193
5a2df000 1194// like get, but simply ignore errors and return Null instead
e9722f8b 1195async fn try_get(repo: &BackupRepository, url: &str) -> Value {
024f11bb 1196
45cdce06
DM
1197 let client = match HttpClient::new(repo.host(), repo.user()) {
1198 Ok(v) => v,
1199 _ => return Value::Null,
1200 };
b2388518 1201
e9722f8b 1202 let mut resp = match client.get(url, None).await {
b2388518
DM
1203 Ok(v) => v,
1204 _ => return Value::Null,
1205 };
1206
1207 if let Some(map) = resp.as_object_mut() {
1208 if let Some(data) = map.remove("data") {
1209 return data;
1210 }
1211 }
1212 Value::Null
1213}
1214
b2388518 1215fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
e9722f8b
WB
1216 async_main(async { complete_backup_group_do(param).await })
1217}
1218
1219async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> {
024f11bb 1220
b2388518
DM
1221 let mut result = vec![];
1222
2665cef7 1223 let repo = match extract_repository_from_map(param) {
b2388518 1224 Some(v) => v,
024f11bb
DM
1225 _ => return result,
1226 };
1227
b2388518
DM
1228 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
1229
e9722f8b 1230 let data = try_get(&repo, &path).await;
b2388518
DM
1231
1232 if let Some(list) = data.as_array() {
024f11bb 1233 for item in list {
98f0b972
DM
1234 if let (Some(backup_id), Some(backup_type)) =
1235 (item["backup-id"].as_str(), item["backup-type"].as_str())
1236 {
1237 result.push(format!("{}/{}", backup_type, backup_id));
024f11bb
DM
1238 }
1239 }
1240 }
1241
1242 result
1243}
1244
b2388518 1245fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
e9722f8b
WB
1246 async_main(async { complete_group_or_snapshot_do(arg, param).await })
1247}
1248
1249async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
b2388518 1250
b2388518 1251 if arg.matches('/').count() < 2 {
e9722f8b 1252 let groups = complete_backup_group_do(param).await;
543a260f 1253 let mut result = vec![];
b2388518
DM
1254 for group in groups {
1255 result.push(group.to_string());
1256 result.push(format!("{}/", group));
1257 }
1258 return result;
1259 }
1260
e9722f8b 1261 complete_backup_snapshot_do(param).await
543a260f 1262}
b2388518 1263
3fb53e07 1264fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
e9722f8b
WB
1265 async_main(async { complete_backup_snapshot_do(param).await })
1266}
1267
1268async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> {
543a260f
DM
1269
1270 let mut result = vec![];
1271
1272 let repo = match extract_repository_from_map(param) {
1273 Some(v) => v,
1274 _ => return result,
1275 };
1276
1277 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
b2388518 1278
e9722f8b 1279 let data = try_get(&repo, &path).await;
b2388518
DM
1280
1281 if let Some(list) = data.as_array() {
1282 for item in list {
1283 if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
1284 (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64())
1285 {
1286 let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
1287 result.push(snapshot.relative_path().to_str().unwrap().to_owned());
1288 }
1289 }
1290 }
1291
1292 result
1293}
1294
45db6f89 1295fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
e9722f8b
WB
1296 async_main(async { complete_server_file_name_do(param).await })
1297}
1298
1299async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> {
08dc340a
DM
1300
1301 let mut result = vec![];
1302
2665cef7 1303 let repo = match extract_repository_from_map(param) {
08dc340a
DM
1304 Some(v) => v,
1305 _ => return result,
1306 };
1307
1308 let snapshot = match param.get("snapshot") {
1309 Some(path) => {
1310 match BackupDir::parse(path) {
1311 Ok(v) => v,
1312 _ => return result,
1313 }
1314 }
1315 _ => return result,
1316 };
1317
1318 let query = tools::json_object_to_query(json!({
1319 "backup-type": snapshot.group().backup_type(),
1320 "backup-id": snapshot.group().backup_id(),
1321 "backup-time": snapshot.backup_time().timestamp(),
1322 })).unwrap();
1323
1324 let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query);
1325
e9722f8b 1326 let data = try_get(&repo, &path).await;
08dc340a
DM
1327
1328 if let Some(list) = data.as_array() {
1329 for item in list {
c4f025eb 1330 if let Some(filename) = item["filename"].as_str() {
08dc340a
DM
1331 result.push(filename.to_owned());
1332 }
1333 }
1334 }
1335
45db6f89
DM
1336 result
1337}
1338
1339fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
52c171e4 1340 complete_server_file_name(arg, param)
e9722f8b
WB
1341 .iter()
1342 .map(|v| strip_server_file_expenstion(&v))
1343 .collect()
08dc340a
DM
1344}
1345
49811347
DM
1346fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
1347
1348 let mut result = vec![];
1349
1350 let mut size = 64;
1351 loop {
1352 result.push(size.to_string());
1353 size = size * 2;
1354 if size > 4096 { break; }
1355 }
1356
1357 result
1358}
1359
826f309b 1360fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
ff5d3707 1361
f2401311
DM
1362 // fixme: implement other input methods
1363
1364 use std::env::VarError::*;
1365 match std::env::var("PBS_ENCRYPTION_PASSWORD") {
826f309b 1366 Ok(p) => return Ok(p.as_bytes().to_vec()),
f2401311
DM
1367 Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
1368 Err(NotPresent) => {
1369 // Try another method
1370 }
1371 }
1372
1373 // If we're on a TTY, query the user for a password
1374 if crate::tools::tty::stdin_isatty() {
826f309b 1375 return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?);
f2401311
DM
1376 }
1377
1378 bail!("no password input mechanism available");
1379}
1380
ac716234
DM
1381fn key_create(
1382 param: Value,
1383 _info: &ApiMethod,
1384 _rpcenv: &mut dyn RpcEnvironment,
1385) -> Result<Value, Error> {
1386
9b06db45
DM
1387 let path = tools::required_string_param(&param, "path")?;
1388 let path = PathBuf::from(path);
ac716234 1389
181f097a 1390 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
ac716234
DM
1391
1392 let key = proxmox::sys::linux::random_data(32)?;
1393
181f097a
DM
1394 if kdf == "scrypt" {
1395 // always read passphrase from tty
1396 if !crate::tools::tty::stdin_isatty() {
1397 bail!("unable to read passphrase - no tty");
1398 }
ac716234 1399
181f097a
DM
1400 let password = crate::tools::tty::read_password("Encryption Key Password: ")?;
1401
ab44acff 1402 let key_config = encrypt_key_with_passphrase(&key, &password)?;
37c5a175 1403
ab44acff 1404 store_key_config(&path, false, key_config)?;
181f097a
DM
1405
1406 Ok(Value::Null)
1407 } else if kdf == "none" {
1408 let created = Local.timestamp(Local::now().timestamp(), 0);
1409
1410 store_key_config(&path, false, KeyConfig {
1411 kdf: None,
1412 created,
ab44acff 1413 modified: created,
181f097a
DM
1414 data: key,
1415 })?;
1416
1417 Ok(Value::Null)
1418 } else {
1419 unreachable!();
1420 }
ac716234
DM
1421}
1422
9f46c7de
DM
1423fn master_pubkey_path() -> Result<PathBuf, Error> {
1424 let base = BaseDirectories::with_prefix("proxmox-backup")?;
1425
1426 // usually $HOME/.config/proxmox-backup/master-public.pem
1427 let path = base.place_config_file("master-public.pem")?;
1428
1429 Ok(path)
1430}
1431
3ea8bfc9
DM
1432fn key_import_master_pubkey(
1433 param: Value,
1434 _info: &ApiMethod,
1435 _rpcenv: &mut dyn RpcEnvironment,
1436) -> Result<Value, Error> {
1437
1438 let path = tools::required_string_param(&param, "path")?;
1439 let path = PathBuf::from(path);
1440
e18a6c9e 1441 let pem_data = file_get_contents(&path)?;
3ea8bfc9
DM
1442
1443 if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
1444 bail!("Unable to decode PEM data - {}", err);
1445 }
1446
9f46c7de 1447 let target_path = master_pubkey_path()?;
3ea8bfc9 1448
e18a6c9e 1449 file_set_contents(&target_path, &pem_data, None)?;
3ea8bfc9
DM
1450
1451 println!("Imported public master key to {:?}", target_path);
1452
1453 Ok(Value::Null)
1454}
1455
37c5a175
DM
1456fn key_create_master_key(
1457 _param: Value,
1458 _info: &ApiMethod,
1459 _rpcenv: &mut dyn RpcEnvironment,
1460) -> Result<Value, Error> {
1461
1462 // we need a TTY to query the new password
1463 if !crate::tools::tty::stdin_isatty() {
1464 bail!("unable to create master key - no tty");
1465 }
1466
1467 let rsa = openssl::rsa::Rsa::generate(4096)?;
1468 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
1469
1470 let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?;
1471 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
1472
1473 if new_pw != verify_pw {
1474 bail!("Password verification fail!");
1475 }
1476
1477 if new_pw.len() < 5 {
1478 bail!("Password is too short!");
1479 }
1480
1481 let pub_key: Vec<u8> = pkey.public_key_to_pem()?;
1482 let filename_pub = "master-public.pem";
1483 println!("Writing public master key to {}", filename_pub);
e18a6c9e 1484 file_set_contents(filename_pub, pub_key.as_slice(), None)?;
37c5a175
DM
1485
1486 let cipher = openssl::symm::Cipher::aes_256_cbc();
1487 let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?;
1488
1489 let filename_priv = "master-private.pem";
1490 println!("Writing private master key to {}", filename_priv);
e18a6c9e 1491 file_set_contents(filename_priv, priv_key.as_slice(), None)?;
37c5a175
DM
1492
1493 Ok(Value::Null)
1494}
ac716234
DM
1495
1496fn key_change_passphrase(
1497 param: Value,
1498 _info: &ApiMethod,
1499 _rpcenv: &mut dyn RpcEnvironment,
1500) -> Result<Value, Error> {
1501
9b06db45
DM
1502 let path = tools::required_string_param(&param, "path")?;
1503 let path = PathBuf::from(path);
ac716234 1504
181f097a
DM
1505 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
1506
ac716234
DM
1507 // we need a TTY to query the new password
1508 if !crate::tools::tty::stdin_isatty() {
1509 bail!("unable to change passphrase - no tty");
1510 }
1511
ab44acff 1512 let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
ac716234 1513
181f097a 1514 if kdf == "scrypt" {
ac716234 1515
181f097a
DM
1516 let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?;
1517 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
ac716234 1518
181f097a
DM
1519 if new_pw != verify_pw {
1520 bail!("Password verification fail!");
1521 }
1522
1523 if new_pw.len() < 5 {
1524 bail!("Password is too short!");
1525 }
ac716234 1526
ab44acff
DM
1527 let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?;
1528 new_key_config.created = created; // keep original value
1529
1530 store_key_config(&path, true, new_key_config)?;
ac716234 1531
181f097a
DM
1532 Ok(Value::Null)
1533 } else if kdf == "none" {
ab44acff 1534 let modified = Local.timestamp(Local::now().timestamp(), 0);
181f097a
DM
1535
1536 store_key_config(&path, true, KeyConfig {
1537 kdf: None,
ab44acff
DM
1538 created, // keep original value
1539 modified,
6d0983db 1540 data: key.to_vec(),
181f097a
DM
1541 })?;
1542
1543 Ok(Value::Null)
1544 } else {
1545 unreachable!();
1546 }
f2401311
DM
1547}
1548
1549fn key_mgmt_cli() -> CliCommandMap {
1550
181f097a
DM
1551 let kdf_schema: Arc<Schema> = Arc::new(
1552 StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.")
1553 .format(Arc::new(ApiStringFormat::Enum(&["scrypt", "none"])))
1554 .default("scrypt")
1555 .into()
1556 );
1557
f2401311
DM
1558 let key_create_cmd_def = CliCommand::new(
1559 ApiMethod::new(
1560 key_create,
1561 ObjectSchema::new("Create a new encryption key.")
9b06db45 1562 .required("path", StringSchema::new("File system path."))
181f097a 1563 .optional("kdf", kdf_schema.clone())
f2401311 1564 ))
9b06db45
DM
1565 .arg_param(vec!["path"])
1566 .completion_cb("path", tools::complete_file_name);
f2401311 1567
ac716234
DM
1568 let key_change_passphrase_cmd_def = CliCommand::new(
1569 ApiMethod::new(
1570 key_change_passphrase,
1571 ObjectSchema::new("Change the passphrase required to decrypt the key.")
9b06db45 1572 .required("path", StringSchema::new("File system path."))
181f097a 1573 .optional("kdf", kdf_schema.clone())
9b06db45
DM
1574 ))
1575 .arg_param(vec!["path"])
1576 .completion_cb("path", tools::complete_file_name);
ac716234 1577
37c5a175
DM
1578 let key_create_master_key_cmd_def = CliCommand::new(
1579 ApiMethod::new(
1580 key_create_master_key,
1581 ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.")
1582 ));
1583
3ea8bfc9
DM
1584 let key_import_master_pubkey_cmd_def = CliCommand::new(
1585 ApiMethod::new(
1586 key_import_master_pubkey,
1587 ObjectSchema::new("Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.")
1588 .required("path", StringSchema::new("File system path."))
1589 ))
1590 .arg_param(vec!["path"])
1591 .completion_cb("path", tools::complete_file_name);
1592
f2401311 1593 let cmd_def = CliCommandMap::new()
ac716234 1594 .insert("create".to_owned(), key_create_cmd_def.into())
37c5a175 1595 .insert("create-master-key".to_owned(), key_create_master_key_cmd_def.into())
3ea8bfc9 1596 .insert("import-master-pubkey".to_owned(), key_import_master_pubkey_cmd_def.into())
ac716234 1597 .insert("change-passphrase".to_owned(), key_change_passphrase_cmd_def.into());
f2401311
DM
1598
1599 cmd_def
1600}
1601
f2401311 1602fn main() {
33d64b81 1603
25f1650b
DM
1604 let backup_source_schema: Arc<Schema> = Arc::new(
1605 StringSchema::new("Backup source specification ([<label>:<path>]).")
1606 .format(Arc::new(ApiStringFormat::Pattern(&BACKUPSPEC_REGEX)))
1607 .into()
1608 );
1609
597a9203 1610 let backup_cmd_def = CliCommand::new(
ff5d3707 1611 ApiMethod::new(
bcd879cf 1612 create_backup,
597a9203 1613 ObjectSchema::new("Create (host) backup.")
ae0be2dd
DM
1614 .required(
1615 "backupspec",
1616 ArraySchema::new(
74cdb521 1617 "List of backup source specifications ([<label.ext>:<path>] ...)",
25f1650b 1618 backup_source_schema,
ae0be2dd
DM
1619 ).min_length(1)
1620 )
2665cef7 1621 .optional("repository", REPO_URL_SCHEMA.clone())
2eeaacb9
DM
1622 .optional(
1623 "include-dev",
1624 ArraySchema::new(
1625 "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.",
1626 StringSchema::new("Path to file.").into()
1627 )
1628 )
6d0983db
DM
1629 .optional(
1630 "keyfile",
1631 StringSchema::new("Path to encryption key. All data will be encrypted using this key."))
219ef0e6
DM
1632 .optional(
1633 "verbose",
1634 BooleanSchema::new("Verbose output.").default(false))
5b72c9b4
DM
1635 .optional(
1636 "skip-lost-and-found",
1637 BooleanSchema::new("Skip lost+found directory").default(false))
fba30411 1638 .optional(
bbf9e7e9
DM
1639 "backup-type",
1640 BACKUP_TYPE_SCHEMA.clone()
1641 )
1642 .optional(
1643 "backup-id",
1644 BACKUP_ID_SCHEMA.clone()
1645 )
ca5d0b61
DM
1646 .optional(
1647 "backup-time",
bbf9e7e9 1648 BACKUP_TIME_SCHEMA.clone()
ca5d0b61 1649 )
2d9d143a
DM
1650 .optional(
1651 "chunk-size",
1652 IntegerSchema::new("Chunk size in KB. Must be a power of 2.")
1653 .minimum(64)
1654 .maximum(4096)
1655 .default(4096)
1656 )
ff5d3707 1657 ))
2665cef7 1658 .arg_param(vec!["backupspec"])
d0a03d40 1659 .completion_cb("repository", complete_repository)
49811347 1660 .completion_cb("backupspec", complete_backup_source)
6d0983db 1661 .completion_cb("keyfile", tools::complete_file_name)
49811347 1662 .completion_cb("chunk-size", complete_chunk_size);
f8838fe9 1663
ec34f7eb
DM
1664 let upload_log_cmd_def = CliCommand::new(
1665 ApiMethod::new(
1666 upload_log,
1667 ObjectSchema::new("Upload backup log file.")
1668 .required("snapshot", StringSchema::new("Snapshot path."))
1669 .required("logfile", StringSchema::new("The path to the log file you want to upload."))
1670 .optional("repository", REPO_URL_SCHEMA.clone())
1671 .optional(
1672 "keyfile",
1673 StringSchema::new("Path to encryption key. All data will be encrypted using this key."))
1674 ))
1675 .arg_param(vec!["snapshot", "logfile"])
543a260f 1676 .completion_cb("snapshot", complete_backup_snapshot)
ec34f7eb
DM
1677 .completion_cb("logfile", tools::complete_file_name)
1678 .completion_cb("keyfile", tools::complete_file_name)
1679 .completion_cb("repository", complete_repository);
1680
41c039e1
DM
1681 let list_cmd_def = CliCommand::new(
1682 ApiMethod::new(
812c6f87
DM
1683 list_backup_groups,
1684 ObjectSchema::new("List backup groups.")
2665cef7 1685 .optional("repository", REPO_URL_SCHEMA.clone())
34a816cc 1686 .optional("output-format", OUTPUT_FORMAT.clone())
41c039e1 1687 ))
d0a03d40 1688 .completion_cb("repository", complete_repository);
41c039e1 1689
184f17af
DM
1690 let snapshots_cmd_def = CliCommand::new(
1691 ApiMethod::new(
1692 list_snapshots,
1693 ObjectSchema::new("List backup snapshots.")
15c847f1 1694 .optional("group", StringSchema::new("Backup group."))
2665cef7 1695 .optional("repository", REPO_URL_SCHEMA.clone())
34a816cc 1696 .optional("output-format", OUTPUT_FORMAT.clone())
184f17af 1697 ))
2665cef7 1698 .arg_param(vec!["group"])
024f11bb 1699 .completion_cb("group", complete_backup_group)
d0a03d40 1700 .completion_cb("repository", complete_repository);
184f17af 1701
6f62c924
DM
1702 let forget_cmd_def = CliCommand::new(
1703 ApiMethod::new(
1704 forget_snapshots,
1705 ObjectSchema::new("Forget (remove) backup snapshots.")
6f62c924 1706 .required("snapshot", StringSchema::new("Snapshot path."))
2665cef7 1707 .optional("repository", REPO_URL_SCHEMA.clone())
6f62c924 1708 ))
2665cef7 1709 .arg_param(vec!["snapshot"])
b2388518 1710 .completion_cb("repository", complete_repository)
543a260f 1711 .completion_cb("snapshot", complete_backup_snapshot);
6f62c924 1712
8cc0d6af
DM
1713 let garbage_collect_cmd_def = CliCommand::new(
1714 ApiMethod::new(
1715 start_garbage_collection,
1716 ObjectSchema::new("Start garbage collection for a specific repository.")
2665cef7 1717 .optional("repository", REPO_URL_SCHEMA.clone())
8cc0d6af 1718 ))
d0a03d40 1719 .completion_cb("repository", complete_repository);
8cc0d6af 1720
9f912493
DM
1721 let restore_cmd_def = CliCommand::new(
1722 ApiMethod::new(
1723 restore,
1724 ObjectSchema::new("Restore backup repository.")
d5c34d98
DM
1725 .required("snapshot", StringSchema::new("Group/Snapshot path."))
1726 .required("archive-name", StringSchema::new("Backup archive name."))
bf125261
DM
1727 .required("target", StringSchema::new(r###"Target directory path. Use '-' to write to stdandard output.
1728
1729We do not extraxt '.pxar' archives when writing to stdandard output.
1730
1731"###
1732 ))
46d5aa0a
DM
1733 .optional(
1734 "allow-existing-dirs",
1735 BooleanSchema::new("Do not fail if directories already exists.").default(false))
2665cef7 1736 .optional("repository", REPO_URL_SCHEMA.clone())
86eda3eb
DM
1737 .optional("keyfile", StringSchema::new("Path to encryption key."))
1738 .optional(
1739 "verbose",
1740 BooleanSchema::new("Verbose output.").default(false)
1741 )
9f912493 1742 ))
2665cef7 1743 .arg_param(vec!["snapshot", "archive-name", "target"])
b2388518 1744 .completion_cb("repository", complete_repository)
08dc340a
DM
1745 .completion_cb("snapshot", complete_group_or_snapshot)
1746 .completion_cb("archive-name", complete_archive_name)
1747 .completion_cb("target", tools::complete_file_name);
9f912493 1748
52c171e4
DM
1749 let files_cmd_def = CliCommand::new(
1750 ApiMethod::new(
1751 list_snapshot_files,
1752 ObjectSchema::new("List snapshot files.")
1753 .required("snapshot", StringSchema::new("Snapshot path."))
cec17a3e 1754 .optional("repository", REPO_URL_SCHEMA.clone())
52c171e4
DM
1755 .optional("output-format", OUTPUT_FORMAT.clone())
1756 ))
1757 .arg_param(vec!["snapshot"])
1758 .completion_cb("repository", complete_repository)
543a260f 1759 .completion_cb("snapshot", complete_backup_snapshot);
52c171e4 1760
9049a8cf
DM
1761 let catalog_cmd_def = CliCommand::new(
1762 ApiMethod::new(
1763 dump_catalog,
1764 ObjectSchema::new("Dump catalog.")
1765 .required("snapshot", StringSchema::new("Snapshot path."))
1766 .optional("repository", REPO_URL_SCHEMA.clone())
1767 ))
1768 .arg_param(vec!["snapshot"])
1769 .completion_cb("repository", complete_repository)
1770 .completion_cb("snapshot", complete_backup_snapshot);
1771
83b7db02
DM
1772 let prune_cmd_def = CliCommand::new(
1773 ApiMethod::new(
1774 prune,
1775 proxmox_backup::api2::admin::datastore::add_common_prune_prameters(
1776 ObjectSchema::new("Prune backup repository.")
9fdc3ef4 1777 .required("group", StringSchema::new("Backup group."))
2665cef7 1778 .optional("repository", REPO_URL_SCHEMA.clone())
83b7db02
DM
1779 )
1780 ))
9fdc3ef4
DM
1781 .arg_param(vec!["group"])
1782 .completion_cb("group", complete_backup_group)
d0a03d40 1783 .completion_cb("repository", complete_repository);
9f912493 1784
34a816cc
DM
1785 let status_cmd_def = CliCommand::new(
1786 ApiMethod::new(
1787 status,
1788 ObjectSchema::new("Get repository status.")
1789 .optional("repository", REPO_URL_SCHEMA.clone())
1790 .optional("output-format", OUTPUT_FORMAT.clone())
1791 ))
1792 .completion_cb("repository", complete_repository);
1793
e240d8be
DM
1794 let login_cmd_def = CliCommand::new(
1795 ApiMethod::new(
1796 api_login,
1797 ObjectSchema::new("Try to login. If successful, store ticket.")
1798 .optional("repository", REPO_URL_SCHEMA.clone())
1799 ))
1800 .completion_cb("repository", complete_repository);
1801
1802 let logout_cmd_def = CliCommand::new(
1803 ApiMethod::new(
1804 api_logout,
1805 ObjectSchema::new("Logout (delete stored ticket).")
1806 .optional("repository", REPO_URL_SCHEMA.clone())
1807 ))
1808 .completion_cb("repository", complete_repository);
1809
41c039e1 1810 let cmd_def = CliCommandMap::new()
597a9203 1811 .insert("backup".to_owned(), backup_cmd_def.into())
ec34f7eb 1812 .insert("upload-log".to_owned(), upload_log_cmd_def.into())
6f62c924 1813 .insert("forget".to_owned(), forget_cmd_def.into())
9049a8cf 1814 .insert("catalog".to_owned(), catalog_cmd_def.into())
8cc0d6af 1815 .insert("garbage-collect".to_owned(), garbage_collect_cmd_def.into())
83b7db02 1816 .insert("list".to_owned(), list_cmd_def.into())
e240d8be
DM
1817 .insert("login".to_owned(), login_cmd_def.into())
1818 .insert("logout".to_owned(), logout_cmd_def.into())
184f17af 1819 .insert("prune".to_owned(), prune_cmd_def.into())
9f912493 1820 .insert("restore".to_owned(), restore_cmd_def.into())
f2401311 1821 .insert("snapshots".to_owned(), snapshots_cmd_def.into())
52c171e4 1822 .insert("files".to_owned(), files_cmd_def.into())
34a816cc 1823 .insert("status".to_owned(), status_cmd_def.into())
f2401311 1824 .insert("key".to_owned(), key_mgmt_cli().into());
a914a774 1825
e9722f8b
WB
1826 run_cli_command(cmd_def.into());
1827}
496a6784 1828
e9722f8b
WB
1829fn async_main<F: Future>(fut: F) -> <F as Future>::Output {
1830 let rt = tokio::runtime::Runtime::new().unwrap();
1831 let ret = rt.block_on(fut);
1832 rt.shutdown_now();
1833 ret
ff5d3707 1834}