]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-client.rs
Cargo.toml: update to latest hyper version
[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;
1c0472e8 6use chrono::{Local, TimeZone};
e9c9409a 7use std::path::{Path, PathBuf};
496a6784 8use std::collections::HashMap;
bf125261 9use std::io::Write;
ff5d3707 10
fe0e04c6 11use proxmox_backup::tools;
4de0e142 12use proxmox_backup::cli::*;
ef2f2efb 13use proxmox_backup::api_schema::*;
dc9a007b 14use proxmox_backup::api_schema::router::*;
151c6ce2 15use proxmox_backup::client::*;
247cdbce 16use proxmox_backup::backup::*;
86eda3eb
DM
17use proxmox_backup::pxar;
18
fe0e04c6
DM
19//use proxmox_backup::backup::image_index::*;
20//use proxmox_backup::config::datastore;
8968258b 21//use proxmox_backup::pxar::encoder::*;
728797d0 22//use proxmox_backup::backup::datastore::*;
23bb8780 23
f5f13ebc 24use serde_json::{json, Value};
1c0472e8 25//use hyper::Body;
33d64b81 26use std::sync::Arc;
ae0be2dd 27use regex::Regex;
d0a03d40 28use xdg::BaseDirectories;
ae0be2dd
DM
29
30use lazy_static::lazy_static;
5a2df000 31use futures::*;
c4ff3dce 32use tokio::sync::mpsc;
ae0be2dd
DM
33
34lazy_static! {
ec8a9bb9 35 static ref BACKUPSPEC_REGEX: Regex = Regex::new(r"^([a-zA-Z0-9_-]+\.(?:pxar|img|conf)):(.+)$").unwrap();
f2401311
DM
36
37 static ref REPO_URL_SCHEMA: Arc<Schema> = Arc::new(
38 StringSchema::new("Repository URL.")
39 .format(BACKUP_REPO_URL.clone())
40 .max_length(256)
41 .into()
42 );
ae0be2dd 43}
33d64b81 44
d0a03d40
DM
45
46fn record_repository(repo: &BackupRepository) {
47
48 let base = match BaseDirectories::with_prefix("proxmox-backup") {
49 Ok(v) => v,
50 _ => return,
51 };
52
53 // usually $HOME/.cache/proxmox-backup/repo-list
54 let path = match base.place_cache_file("repo-list") {
55 Ok(v) => v,
56 _ => return,
57 };
58
49cf9f3d 59 let mut data = tools::file_get_json(&path, None).unwrap_or(json!({}));
d0a03d40
DM
60
61 let repo = repo.to_string();
62
63 data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 };
64
65 let mut map = serde_json::map::Map::new();
66
67 loop {
68 let mut max_used = 0;
69 let mut max_repo = None;
70 for (repo, count) in data.as_object().unwrap() {
71 if map.contains_key(repo) { continue; }
72 if let Some(count) = count.as_i64() {
73 if count > max_used {
74 max_used = count;
75 max_repo = Some(repo);
76 }
77 }
78 }
79 if let Some(repo) = max_repo {
80 map.insert(repo.to_owned(), json!(max_used));
81 } else {
82 break;
83 }
84 if map.len() > 10 { // store max. 10 repos
85 break;
86 }
87 }
88
89 let new_data = json!(map);
90
91 let _ = tools::file_set_contents(path, new_data.to_string().as_bytes(), None);
92}
93
49811347 94fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
d0a03d40
DM
95
96 let mut result = vec![];
97
98 let base = match BaseDirectories::with_prefix("proxmox-backup") {
99 Ok(v) => v,
100 _ => return result,
101 };
102
103 // usually $HOME/.cache/proxmox-backup/repo-list
104 let path = match base.place_cache_file("repo-list") {
105 Ok(v) => v,
106 _ => return result,
107 };
108
49cf9f3d 109 let data = tools::file_get_json(&path, None).unwrap_or(json!({}));
d0a03d40
DM
110
111 if let Some(map) = data.as_object() {
49811347 112 for (repo, _count) in map {
d0a03d40
DM
113 result.push(repo.to_owned());
114 }
115 }
116
117 result
118}
119
17d6979a 120fn backup_directory<P: AsRef<Path>>(
c4ff3dce 121 client: &BackupClient,
17d6979a 122 dir_path: P,
247cdbce 123 archive_name: &str,
36898ffc 124 chunk_size: Option<usize>,
eed6db39 125 all_file_systems: bool,
219ef0e6 126 verbose: bool,
f98ac774 127 crypt_config: Option<Arc<CryptConfig>>,
247cdbce 128) -> Result<(), Error> {
33d64b81 129
c4ff3dce 130 let pxar_stream = PxarBackupStream::open(dir_path.as_ref(), all_file_systems, verbose)?;
36898ffc 131 let chunk_stream = ChunkStream::new(pxar_stream, chunk_size);
ff3d3100 132
c4ff3dce 133 let (tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks
5e7a09be 134
c4ff3dce
DM
135 let stream = rx
136 .map_err(Error::from)
137 .and_then(|x| x); // flatten
17d6979a 138
c4ff3dce
DM
139 // spawn chunker inside a separate task so that it can run parallel
140 tokio::spawn(
141 tx.send_all(chunk_stream.then(|r| Ok(r)))
1c0472e8 142 .map_err(|_| {}).map(|_| ())
c4ff3dce 143 );
17d6979a 144
f98ac774 145 client.upload_stream(archive_name, stream, "dynamic", None, crypt_config).wait()?;
bcd879cf
DM
146
147 Ok(())
148}
149
6af905c1
DM
150fn backup_image<P: AsRef<Path>>(
151 client: &BackupClient,
152 image_path: P,
153 archive_name: &str,
154 image_size: u64,
36898ffc 155 chunk_size: Option<usize>,
1c0472e8 156 _verbose: bool,
f98ac774 157 crypt_config: Option<Arc<CryptConfig>>,
6af905c1
DM
158) -> Result<(), Error> {
159
6af905c1
DM
160 let path = image_path.as_ref().to_owned();
161
162 let file = tokio::fs::File::open(path).wait()?;
163
164 let stream = tokio::codec::FramedRead::new(file, tokio::codec::BytesCodec::new())
165 .map_err(Error::from);
166
36898ffc 167 let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024));
6af905c1 168
f98ac774 169 client.upload_stream(archive_name, stream, "fixed", Some(image_size), crypt_config).wait()?;
6af905c1
DM
170
171 Ok(())
172}
173
6899dbfb 174fn strip_server_file_expenstions(list: Vec<String>) -> Vec<String> {
8e39232a
DM
175
176 let mut result = vec![];
177
178 for file in list.into_iter() {
179 if file.ends_with(".didx") {
180 result.push(file[..file.len()-5].to_owned());
181 } else if file.ends_with(".fidx") {
182 result.push(file[..file.len()-5].to_owned());
6899dbfb
DM
183 } else if file.ends_with(".blob") {
184 result.push(file[..file.len()-5].to_owned());
8e39232a
DM
185 } else {
186 result.push(file); // should not happen
187 }
188 }
189
190 result
191}
192
8968258b 193/* not used:
6049b71f
DM
194fn list_backups(
195 param: Value,
196 _info: &ApiMethod,
dd5495d6 197 _rpcenv: &mut dyn RpcEnvironment,
6049b71f 198) -> Result<Value, Error> {
41c039e1 199
33d64b81 200 let repo_url = tools::required_string_param(&param, "repository")?;
edd3c8c6 201 let repo: BackupRepository = repo_url.parse()?;
41c039e1 202
45cdce06 203 let mut client = HttpClient::new(repo.host(), repo.user())?;
41c039e1 204
d0a03d40 205 let path = format!("api2/json/admin/datastore/{}/backups", repo.store());
41c039e1 206
9e391bb7 207 let result = client.get(&path, None)?;
41c039e1 208
d0a03d40
DM
209 record_repository(&repo);
210
8c75372b
DM
211 // fixme: implement and use output formatter instead ..
212 let list = result["data"].as_array().unwrap();
213
214 for item in list {
215
49dc0740
DM
216 let id = item["backup-id"].as_str().unwrap();
217 let btype = item["backup-type"].as_str().unwrap();
218 let epoch = item["backup-time"].as_i64().unwrap();
e909522f 219
391d3107 220 let backup_dir = BackupDir::new(btype, id, epoch);
e909522f
DM
221
222 let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect();
6899dbfb 223 let files = strip_server_file_expenstions(files);
e909522f 224
8e39232a
DM
225 for filename in files {
226 let path = backup_dir.relative_path().to_str().unwrap().to_owned();
227 println!("{} | {}/{}", backup_dir.backup_time().format("%c"), path, filename);
8c75372b
DM
228 }
229 }
230
231 //Ok(result)
232 Ok(Value::Null)
41c039e1 233}
8968258b 234 */
41c039e1 235
812c6f87
DM
236fn list_backup_groups(
237 param: Value,
238 _info: &ApiMethod,
dd5495d6 239 _rpcenv: &mut dyn RpcEnvironment,
812c6f87
DM
240) -> Result<Value, Error> {
241
242 let repo_url = tools::required_string_param(&param, "repository")?;
edd3c8c6 243 let repo: BackupRepository = repo_url.parse()?;
812c6f87 244
45cdce06 245 let client = HttpClient::new(repo.host(), repo.user())?;
812c6f87 246
d0a03d40 247 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
812c6f87 248
9e391bb7 249 let mut result = client.get(&path, None).wait()?;
812c6f87 250
d0a03d40
DM
251 record_repository(&repo);
252
812c6f87 253 // fixme: implement and use output formatter instead ..
80822b95
DM
254 let list = result["data"].as_array_mut().unwrap();
255
256 list.sort_unstable_by(|a, b| {
257 let a_id = a["backup-id"].as_str().unwrap();
258 let a_backup_type = a["backup-type"].as_str().unwrap();
259 let b_id = b["backup-id"].as_str().unwrap();
260 let b_backup_type = b["backup-type"].as_str().unwrap();
261
262 let type_order = a_backup_type.cmp(b_backup_type);
263 if type_order == std::cmp::Ordering::Equal {
264 a_id.cmp(b_id)
265 } else {
266 type_order
267 }
268 });
812c6f87
DM
269
270 for item in list {
271
ad20d198
DM
272 let id = item["backup-id"].as_str().unwrap();
273 let btype = item["backup-type"].as_str().unwrap();
274 let epoch = item["last-backup"].as_i64().unwrap();
812c6f87 275 let last_backup = Local.timestamp(epoch, 0);
ad20d198 276 let backup_count = item["backup-count"].as_u64().unwrap();
812c6f87 277
1e9a94e5 278 let group = BackupGroup::new(btype, id);
812c6f87
DM
279
280 let path = group.group_path().to_str().unwrap().to_owned();
ad20d198 281
8e39232a 282 let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect();
6899dbfb 283 let files = strip_server_file_expenstions(files);
ad20d198 284
80822b95 285 println!("{:20} | {} | {:5} | {}", path, last_backup.format("%c"),
ad20d198 286 backup_count, tools::join(&files, ' '));
812c6f87
DM
287 }
288
289 //Ok(result)
290 Ok(Value::Null)
291}
292
184f17af
DM
293fn list_snapshots(
294 param: Value,
295 _info: &ApiMethod,
dd5495d6 296 _rpcenv: &mut dyn RpcEnvironment,
184f17af
DM
297) -> Result<Value, Error> {
298
299 let repo_url = tools::required_string_param(&param, "repository")?;
edd3c8c6 300 let repo: BackupRepository = repo_url.parse()?;
184f17af
DM
301
302 let path = tools::required_string_param(&param, "group")?;
303 let group = BackupGroup::parse(path)?;
304
45cdce06 305 let client = HttpClient::new(repo.host(), repo.user())?;
184f17af 306
9e391bb7 307 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
184f17af 308
9e391bb7
DM
309 let result = client.get(&path, Some(json!({
310 "backup-type": group.backup_type(),
311 "backup-id": group.backup_id(),
312 }))).wait()?;
184f17af 313
d0a03d40
DM
314 record_repository(&repo);
315
184f17af
DM
316 // fixme: implement and use output formatter instead ..
317 let list = result["data"].as_array().unwrap();
318
319 for item in list {
320
321 let id = item["backup-id"].as_str().unwrap();
322 let btype = item["backup-type"].as_str().unwrap();
323 let epoch = item["backup-time"].as_i64().unwrap();
184f17af 324
391d3107 325 let snapshot = BackupDir::new(btype, id, epoch);
184f17af
DM
326
327 let path = snapshot.relative_path().to_str().unwrap().to_owned();
328
8e39232a 329 let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect();
6899dbfb 330 let files = strip_server_file_expenstions(files);
184f17af 331
875fb1c0 332 println!("{} | {} | {}", path, snapshot.backup_time().format("%c"), tools::join(&files, ' '));
184f17af
DM
333 }
334
335 Ok(Value::Null)
336}
337
6f62c924
DM
338fn forget_snapshots(
339 param: Value,
340 _info: &ApiMethod,
dd5495d6 341 _rpcenv: &mut dyn RpcEnvironment,
6f62c924
DM
342) -> Result<Value, Error> {
343
344 let repo_url = tools::required_string_param(&param, "repository")?;
edd3c8c6 345 let repo: BackupRepository = repo_url.parse()?;
6f62c924
DM
346
347 let path = tools::required_string_param(&param, "snapshot")?;
348 let snapshot = BackupDir::parse(path)?;
349
45cdce06 350 let mut client = HttpClient::new(repo.host(), repo.user())?;
6f62c924 351
9e391bb7 352 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
6f62c924 353
9e391bb7
DM
354 let result = client.delete(&path, Some(json!({
355 "backup-type": snapshot.group().backup_type(),
356 "backup-id": snapshot.group().backup_id(),
357 "backup-time": snapshot.backup_time().timestamp(),
358 }))).wait()?;
6f62c924 359
d0a03d40
DM
360 record_repository(&repo);
361
6f62c924
DM
362 Ok(result)
363}
364
8cc0d6af
DM
365fn start_garbage_collection(
366 param: Value,
367 _info: &ApiMethod,
dd5495d6 368 _rpcenv: &mut dyn RpcEnvironment,
8cc0d6af
DM
369) -> Result<Value, Error> {
370
371 let repo_url = tools::required_string_param(&param, "repository")?;
edd3c8c6 372 let repo: BackupRepository = repo_url.parse()?;
8cc0d6af 373
45cdce06 374 let mut client = HttpClient::new(repo.host(), repo.user())?;
8cc0d6af 375
d0a03d40 376 let path = format!("api2/json/admin/datastore/{}/gc", repo.store());
8cc0d6af 377
5a2df000 378 let result = client.post(&path, None).wait()?;
8cc0d6af 379
d0a03d40
DM
380 record_repository(&repo);
381
8cc0d6af
DM
382 Ok(result)
383}
33d64b81 384
ae0be2dd
DM
385fn parse_backupspec(value: &str) -> Result<(&str, &str), Error> {
386
387 if let Some(caps) = BACKUPSPEC_REGEX.captures(value) {
388 return Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str()));
389 }
390 bail!("unable to parse directory specification '{}'", value);
391}
392
6049b71f
DM
393fn create_backup(
394 param: Value,
395 _info: &ApiMethod,
dd5495d6 396 _rpcenv: &mut dyn RpcEnvironment,
6049b71f 397) -> Result<Value, Error> {
ff5d3707 398
33d64b81 399 let repo_url = tools::required_string_param(&param, "repository")?;
ae0be2dd
DM
400
401 let backupspec_list = tools::required_array_param(&param, "backupspec")?;
a914a774 402
edd3c8c6 403 let repo: BackupRepository = repo_url.parse()?;
33d64b81 404
eed6db39
DM
405 let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false);
406
219ef0e6
DM
407 let verbose = param["verbose"].as_bool().unwrap_or(false);
408
36898ffc 409 let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize);
2d9d143a 410
247cdbce
DM
411 if let Some(size) = chunk_size_opt {
412 verify_chunk_size(size)?;
2d9d143a
DM
413 }
414
6d0983db
DM
415 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
416
fba30411
DM
417 let backup_id = param["host-id"].as_str().unwrap_or(&tools::nodename());
418
ae0be2dd 419 let mut upload_list = vec![];
a914a774 420
ec8a9bb9 421 enum BackupType { PXAR, IMAGE, CONFIG };
6af905c1 422
ae0be2dd
DM
423 for backupspec in backupspec_list {
424 let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?;
bcd879cf 425
eb1804c5
DM
426 use std::os::unix::fs::FileTypeExt;
427
428 let metadata = match std::fs::metadata(filename) {
429 Ok(m) => m,
ae0be2dd
DM
430 Err(err) => bail!("unable to access '{}' - {}", filename, err),
431 };
eb1804c5 432 let file_type = metadata.file_type();
23bb8780 433
ec8a9bb9 434 let extension = Path::new(target).extension().map(|s| s.to_str().unwrap()).unwrap();
bcd879cf 435
ec8a9bb9
DM
436 match extension {
437 "pxar" => {
438 if !file_type.is_dir() {
439 bail!("got unexpected file type (expected directory)");
440 }
441 upload_list.push((BackupType::PXAR, filename.to_owned(), target.to_owned(), 0));
442 }
443 "img" => {
eb1804c5 444
ec8a9bb9
DM
445 if !(file_type.is_file() || file_type.is_block_device()) {
446 bail!("got unexpected file type (expected file or block device)");
447 }
eb1804c5 448
ec8a9bb9 449 let size = tools::image_size(&PathBuf::from(filename))?;
23bb8780 450
ec8a9bb9 451 if size == 0 { bail!("got zero-sized file '{}'", filename); }
ae0be2dd 452
ec8a9bb9
DM
453 upload_list.push((BackupType::IMAGE, filename.to_owned(), target.to_owned(), size));
454 }
455 "conf" => {
456 if !file_type.is_file() {
457 bail!("got unexpected file type (expected regular file)");
458 }
459 upload_list.push((BackupType::CONFIG, filename.to_owned(), target.to_owned(), metadata.len()));
460 }
461 _ => {
462 bail!("got unknown archive extension '{}'", extension);
463 }
ae0be2dd
DM
464 }
465 }
466
cdebd467 467 let backup_time = Local.timestamp(Local::now().timestamp(), 0);
ae0be2dd 468
c4ff3dce 469 let client = HttpClient::new(repo.host(), repo.user())?;
d0a03d40
DM
470 record_repository(&repo);
471
cdebd467
DM
472 println!("Starting backup");
473 println!("Client name: {}", tools::nodename());
474 println!("Start Time: {}", backup_time.to_rfc3339());
51144821 475
bb823140
DM
476 let (crypt_config, rsa_encrypted_key) = match keyfile {
477 None => (None, None),
6d0983db 478 Some(path) => {
bb823140
DM
479 let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
480
481 let crypt_config = CryptConfig::new(key)?;
482
483 let path = master_pubkey_path()?;
484 if path.exists() {
485 let pem_data = proxmox_backup::tools::file_get_contents(&path)?;
486 let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
487 let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?;
488 (Some(Arc::new(crypt_config)), Some(enc_key))
489 } else {
490 (Some(Arc::new(crypt_config)), None)
491 }
6d0983db
DM
492 }
493 };
f98ac774 494
39e60bd6 495 let client = client.start_backup(repo.store(), "host", &backup_id, verbose).wait()?;
c4ff3dce 496
6af905c1
DM
497 for (backup_type, filename, target, size) in upload_list {
498 match backup_type {
ec8a9bb9
DM
499 BackupType::CONFIG => {
500 println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target);
9f46c7de 501 client.upload_blob_from_file(&filename, &target, crypt_config.clone(), true).wait()?;
ec8a9bb9 502 }
6af905c1
DM
503 BackupType::PXAR => {
504 println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target);
f98ac774
DM
505 backup_directory(
506 &client,
507 &filename,
508 &target,
509 chunk_size_opt,
510 all_file_systems,
511 verbose,
512 crypt_config.clone(),
513 )?;
6af905c1
DM
514 }
515 BackupType::IMAGE => {
516 println!("Upload image '{}' to '{:?}' as {}", filename, repo, target);
f98ac774
DM
517 backup_image(
518 &client,
519 &filename,
520 &target,
521 size,
522 chunk_size_opt,
523 verbose,
524 crypt_config.clone(),
525 )?;
6af905c1
DM
526 }
527 }
4818c8b6
DM
528 }
529
bb823140
DM
530 if let Some(rsa_encrypted_key) = rsa_encrypted_key {
531 let target = "rsa-encrypted.key";
532 println!("Upload RSA encoded key to '{:?}' as {}", repo, target);
533 client.upload_blob_from_data(rsa_encrypted_key, target, None, false).wait()?;
534
535 // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t
536 /*
537 let mut buffer2 = vec![0u8; rsa.size() as usize];
538 let pem_data = proxmox_backup::tools::file_get_contents("master-private.pem")?;
539 let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?;
540 let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?;
541 println!("TEST {} {:?}", len, buffer2);
542 */
9f46c7de
DM
543 }
544
c4ff3dce
DM
545 client.finish().wait()?;
546
cdebd467 547 let end_time = Local.timestamp(Local::now().timestamp(), 0);
3ec3ec3f
DM
548 let elapsed = end_time.signed_duration_since(backup_time);
549 println!("Duration: {}", elapsed);
550
cdebd467 551 println!("End Time: {}", end_time.to_rfc3339());
3d5c11e5 552
ff5d3707 553 Ok(Value::Null)
f98ea63d
DM
554}
555
d0a03d40 556fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
f98ea63d
DM
557
558 let mut result = vec![];
559
560 let data: Vec<&str> = arg.splitn(2, ':').collect();
561
bff11030 562 if data.len() != 2 {
8968258b
DM
563 result.push(String::from("root.pxar:/"));
564 result.push(String::from("etc.pxar:/etc"));
bff11030
DM
565 return result;
566 }
f98ea63d 567
496a6784 568 let files = tools::complete_file_name(data[1], param);
f98ea63d
DM
569
570 for file in files {
571 result.push(format!("{}:{}", data[0], file));
572 }
573
574 result
ff5d3707 575}
576
9f912493
DM
577fn restore(
578 param: Value,
579 _info: &ApiMethod,
dd5495d6 580 _rpcenv: &mut dyn RpcEnvironment,
9f912493
DM
581) -> Result<Value, Error> {
582
583 let repo_url = tools::required_string_param(&param, "repository")?;
edd3c8c6 584 let repo: BackupRepository = repo_url.parse()?;
9f912493 585
86eda3eb
DM
586 let verbose = param["verbose"].as_bool().unwrap_or(false);
587
d5c34d98
DM
588 let archive_name = tools::required_string_param(&param, "archive-name")?;
589
86eda3eb 590 let client = HttpClient::new(repo.host(), repo.user())?;
d0a03d40 591
d0a03d40 592 record_repository(&repo);
d5c34d98 593
9f912493 594 let path = tools::required_string_param(&param, "snapshot")?;
9f912493 595
86eda3eb 596 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
d5c34d98 597 let group = BackupGroup::parse(path)?;
9f912493 598
9e391bb7
DM
599 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
600 let result = client.get(&path, Some(json!({
d5c34d98
DM
601 "backup-type": group.backup_type(),
602 "backup-id": group.backup_id(),
9e391bb7 603 }))).wait()?;
9f912493 604
d5c34d98
DM
605 let list = result["data"].as_array().unwrap();
606 if list.len() == 0 {
607 bail!("backup group '{}' does not contain any snapshots:", path);
608 }
9f912493 609
86eda3eb
DM
610 let epoch = list[0]["backup-time"].as_i64().unwrap();
611 let backup_time = Local.timestamp(epoch, 0);
612 (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time)
d5c34d98
DM
613 } else {
614 let snapshot = BackupDir::parse(path)?;
86eda3eb
DM
615 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
616 };
9f912493 617
d5c34d98 618 let target = tools::required_string_param(&param, "target")?;
bf125261 619 let target = if target == "-" { None } else { Some(target) };
2ae7d196 620
86eda3eb 621 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
2ae7d196 622
86eda3eb
DM
623 let crypt_config = match keyfile {
624 None => None,
625 Some(path) => {
626 let (key, _) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
627 Some(Arc::new(CryptConfig::new(key)?))
628 }
629 };
d5c34d98 630
afb4cd28
DM
631 let server_archive_name = if archive_name.ends_with(".pxar") {
632 format!("{}.didx", archive_name)
633 } else if archive_name.ends_with(".img") {
634 format!("{}.fidx", archive_name)
635 } else {
f8100e96 636 format!("{}.blob", archive_name)
afb4cd28 637 };
9f912493 638
86eda3eb
DM
639 let client = client.start_backup_reader(repo.store(), &backup_type, &backup_id, backup_time, true).wait()?;
640
641 use std::os::unix::fs::OpenOptionsExt;
642
643 let tmpfile = std::fs::OpenOptions::new()
644 .write(true)
645 .read(true)
646 .custom_flags(libc::O_TMPFILE)
647 .open("/tmp")?;
648
f8100e96
DM
649 if server_archive_name.ends_with(".blob") {
650
651 let writer = Vec::with_capacity(1024*1024);
652 let blob_data = client.download(&server_archive_name, writer).wait()?;
653 let blob = DataBlob::from_raw(blob_data)?;
654 blob.verify_crc()?;
655
656 let raw_data = match crypt_config {
657 Some(ref crypt_config) => blob.decode(Some(crypt_config))?,
658 None => blob.decode(None)?,
659 };
660
bf125261
DM
661 if let Some(target) = target {
662 crate::tools::file_set_contents(target, &raw_data, None)?;
663 } else {
664 let stdout = std::io::stdout();
665 let mut writer = stdout.lock();
666 writer.write_all(&raw_data)
667 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
668 }
f8100e96
DM
669
670 } else if server_archive_name.ends_with(".didx") {
afb4cd28 671 let tmpfile = client.download(&server_archive_name, tmpfile).wait()?;
86eda3eb 672
afb4cd28
DM
673 let index = DynamicIndexReader::new(tmpfile)
674 .map_err(|err| format_err!("unable to read dynamic index '{}' - {}", archive_name, err))?;
86eda3eb 675
f4bf7dfc
DM
676 let most_used = index.find_most_used_chunks(8);
677
678 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
679
afb4cd28 680 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
86eda3eb 681
bf125261 682 if let Some(target) = target {
86eda3eb 683
bf125261
DM
684 let feature_flags = pxar::CA_FORMAT_DEFAULT;
685 let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags, |path| {
686 if verbose {
687 println!("{:?}", path);
688 }
689 Ok(())
690 });
691
692 decoder.restore(Path::new(target))?;
693 } else {
694 let stdout = std::io::stdout();
695 let mut writer = stdout.lock();
afb4cd28 696
bf125261
DM
697 std::io::copy(&mut reader, &mut writer)
698 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
699 }
afb4cd28
DM
700 } else if server_archive_name.ends_with(".fidx") {
701 let tmpfile = client.download(&server_archive_name, tmpfile).wait()?;
702
703 let index = FixedIndexReader::new(tmpfile)
704 .map_err(|err| format_err!("unable to read fixed index '{}' - {}", archive_name, err))?;
7dcbe051 705
f4bf7dfc
DM
706 let most_used = index.find_most_used_chunks(8);
707
708 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
709
afb4cd28
DM
710 let mut reader = BufferedFixedReader::new(index, chunk_reader);
711
bf125261
DM
712 if let Some(target) = target {
713 let mut writer = std::fs::OpenOptions::new()
714 .write(true)
715 .create(true)
716 .create_new(true)
717 .open(target)
718 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
719
720 std::io::copy(&mut reader, &mut writer)
721 .map_err(|err| format_err!("unable to store data - {}", err))?;
722 } else {
723 let stdout = std::io::stdout();
724 let mut writer = stdout.lock();
afb4cd28 725
bf125261
DM
726 std::io::copy(&mut reader, &mut writer)
727 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
728 }
45db6f89 729 } else {
f8100e96 730 bail!("unknown archive file extension (expected .pxar of .img)");
3031e44c 731 }
fef44d4f
DM
732
733 Ok(Value::Null)
45db6f89
DM
734}
735
83b7db02
DM
736fn prune(
737 mut param: Value,
738 _info: &ApiMethod,
dd5495d6 739 _rpcenv: &mut dyn RpcEnvironment,
83b7db02
DM
740) -> Result<Value, Error> {
741
742 let repo_url = tools::required_string_param(&param, "repository")?;
edd3c8c6 743 let repo: BackupRepository = repo_url.parse()?;
83b7db02 744
45cdce06 745 let mut client = HttpClient::new(repo.host(), repo.user())?;
83b7db02 746
d0a03d40 747 let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
83b7db02
DM
748
749 param.as_object_mut().unwrap().remove("repository");
750
5a2df000 751 let result = client.post(&path, Some(param)).wait()?;
83b7db02 752
d0a03d40
DM
753 record_repository(&repo);
754
83b7db02
DM
755 Ok(result)
756}
757
5a2df000 758// like get, but simply ignore errors and return Null instead
b2388518 759fn try_get(repo: &BackupRepository, url: &str) -> Value {
024f11bb 760
45cdce06
DM
761 let client = match HttpClient::new(repo.host(), repo.user()) {
762 Ok(v) => v,
763 _ => return Value::Null,
764 };
b2388518 765
9e391bb7 766 let mut resp = match client.get(url, None).wait() {
b2388518
DM
767 Ok(v) => v,
768 _ => return Value::Null,
769 };
770
771 if let Some(map) = resp.as_object_mut() {
772 if let Some(data) = map.remove("data") {
773 return data;
774 }
775 }
776 Value::Null
777}
778
779fn extract_repo(param: &HashMap<String, String>) -> Option<BackupRepository> {
024f11bb
DM
780
781 let repo_url = match param.get("repository") {
782 Some(v) => v,
b2388518 783 _ => return None,
024f11bb
DM
784 };
785
786 let repo: BackupRepository = match repo_url.parse() {
787 Ok(v) => v,
b2388518 788 _ => return None,
024f11bb
DM
789 };
790
b2388518
DM
791 Some(repo)
792}
024f11bb 793
b2388518 794fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
024f11bb 795
b2388518
DM
796 let mut result = vec![];
797
798 let repo = match extract_repo(param) {
799 Some(v) => v,
024f11bb
DM
800 _ => return result,
801 };
802
b2388518
DM
803 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
804
805 let data = try_get(&repo, &path);
806
807 if let Some(list) = data.as_array() {
024f11bb 808 for item in list {
98f0b972
DM
809 if let (Some(backup_id), Some(backup_type)) =
810 (item["backup-id"].as_str(), item["backup-type"].as_str())
811 {
812 result.push(format!("{}/{}", backup_type, backup_id));
024f11bb
DM
813 }
814 }
815 }
816
817 result
818}
819
b2388518
DM
820fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
821
822 let mut result = vec![];
823
824 let repo = match extract_repo(param) {
825 Some(v) => v,
826 _ => return result,
827 };
828
829 if arg.matches('/').count() < 2 {
830 let groups = complete_backup_group(arg, param);
831 for group in groups {
832 result.push(group.to_string());
833 result.push(format!("{}/", group));
834 }
835 return result;
836 }
837
838 let mut parts = arg.split('/');
839 let query = tools::json_object_to_query(json!({
840 "backup-type": parts.next().unwrap(),
841 "backup-id": parts.next().unwrap(),
842 })).unwrap();
843
844 let path = format!("api2/json/admin/datastore/{}/snapshots?{}", repo.store(), query);
845
846 let data = try_get(&repo, &path);
847
848 if let Some(list) = data.as_array() {
849 for item in list {
850 if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
851 (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64())
852 {
853 let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
854 result.push(snapshot.relative_path().to_str().unwrap().to_owned());
855 }
856 }
857 }
858
859 result
860}
861
45db6f89 862fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
08dc340a
DM
863
864 let mut result = vec![];
865
866 let repo = match extract_repo(param) {
867 Some(v) => v,
868 _ => return result,
869 };
870
871 let snapshot = match param.get("snapshot") {
872 Some(path) => {
873 match BackupDir::parse(path) {
874 Ok(v) => v,
875 _ => return result,
876 }
877 }
878 _ => return result,
879 };
880
881 let query = tools::json_object_to_query(json!({
882 "backup-type": snapshot.group().backup_type(),
883 "backup-id": snapshot.group().backup_id(),
884 "backup-time": snapshot.backup_time().timestamp(),
885 })).unwrap();
886
887 let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query);
888
889 let data = try_get(&repo, &path);
890
891 if let Some(list) = data.as_array() {
892 for item in list {
893 if let Some(filename) = item.as_str() {
894 result.push(filename.to_owned());
895 }
896 }
897 }
898
45db6f89
DM
899 result
900}
901
902fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
903
904 let result = complete_server_file_name(arg, param);
905
6899dbfb 906 strip_server_file_expenstions(result)
08dc340a
DM
907}
908
49811347
DM
909fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
910
911 let mut result = vec![];
912
913 let mut size = 64;
914 loop {
915 result.push(size.to_string());
916 size = size * 2;
917 if size > 4096 { break; }
918 }
919
920 result
921}
922
826f309b 923fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
ff5d3707 924
f2401311
DM
925 // fixme: implement other input methods
926
927 use std::env::VarError::*;
928 match std::env::var("PBS_ENCRYPTION_PASSWORD") {
826f309b 929 Ok(p) => return Ok(p.as_bytes().to_vec()),
f2401311
DM
930 Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
931 Err(NotPresent) => {
932 // Try another method
933 }
934 }
935
936 // If we're on a TTY, query the user for a password
937 if crate::tools::tty::stdin_isatty() {
826f309b 938 return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?);
f2401311
DM
939 }
940
941 bail!("no password input mechanism available");
942}
943
ac716234
DM
944fn key_create(
945 param: Value,
946 _info: &ApiMethod,
947 _rpcenv: &mut dyn RpcEnvironment,
948) -> Result<Value, Error> {
949
9b06db45
DM
950 let path = tools::required_string_param(&param, "path")?;
951 let path = PathBuf::from(path);
ac716234 952
181f097a 953 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
ac716234
DM
954
955 let key = proxmox::sys::linux::random_data(32)?;
956
181f097a
DM
957 if kdf == "scrypt" {
958 // always read passphrase from tty
959 if !crate::tools::tty::stdin_isatty() {
960 bail!("unable to read passphrase - no tty");
961 }
ac716234 962
181f097a
DM
963 let password = crate::tools::tty::read_password("Encryption Key Password: ")?;
964
ab44acff 965 let key_config = encrypt_key_with_passphrase(&key, &password)?;
37c5a175 966
ab44acff 967 store_key_config(&path, false, key_config)?;
181f097a
DM
968
969 Ok(Value::Null)
970 } else if kdf == "none" {
971 let created = Local.timestamp(Local::now().timestamp(), 0);
972
973 store_key_config(&path, false, KeyConfig {
974 kdf: None,
975 created,
ab44acff 976 modified: created,
181f097a
DM
977 data: key,
978 })?;
979
980 Ok(Value::Null)
981 } else {
982 unreachable!();
983 }
ac716234
DM
984}
985
9f46c7de
DM
986fn master_pubkey_path() -> Result<PathBuf, Error> {
987 let base = BaseDirectories::with_prefix("proxmox-backup")?;
988
989 // usually $HOME/.config/proxmox-backup/master-public.pem
990 let path = base.place_config_file("master-public.pem")?;
991
992 Ok(path)
993}
994
3ea8bfc9
DM
995fn key_import_master_pubkey(
996 param: Value,
997 _info: &ApiMethod,
998 _rpcenv: &mut dyn RpcEnvironment,
999) -> Result<Value, Error> {
1000
1001 let path = tools::required_string_param(&param, "path")?;
1002 let path = PathBuf::from(path);
1003
1004 let pem_data = proxmox_backup::tools::file_get_contents(&path)?;
1005
1006 if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
1007 bail!("Unable to decode PEM data - {}", err);
1008 }
1009
9f46c7de 1010 let target_path = master_pubkey_path()?;
3ea8bfc9
DM
1011
1012 proxmox_backup::tools::file_set_contents(&target_path, &pem_data, None)?;
1013
1014 println!("Imported public master key to {:?}", target_path);
1015
1016 Ok(Value::Null)
1017}
1018
37c5a175
DM
1019fn key_create_master_key(
1020 _param: Value,
1021 _info: &ApiMethod,
1022 _rpcenv: &mut dyn RpcEnvironment,
1023) -> Result<Value, Error> {
1024
1025 // we need a TTY to query the new password
1026 if !crate::tools::tty::stdin_isatty() {
1027 bail!("unable to create master key - no tty");
1028 }
1029
1030 let rsa = openssl::rsa::Rsa::generate(4096)?;
1031 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
1032
1033 let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?;
1034 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
1035
1036 if new_pw != verify_pw {
1037 bail!("Password verification fail!");
1038 }
1039
1040 if new_pw.len() < 5 {
1041 bail!("Password is too short!");
1042 }
1043
1044 let pub_key: Vec<u8> = pkey.public_key_to_pem()?;
1045 let filename_pub = "master-public.pem";
1046 println!("Writing public master key to {}", filename_pub);
1047 proxmox_backup::tools::file_set_contents(filename_pub, pub_key.as_slice(), None)?;
1048
1049 let cipher = openssl::symm::Cipher::aes_256_cbc();
1050 let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?;
1051
1052 let filename_priv = "master-private.pem";
1053 println!("Writing private master key to {}", filename_priv);
1054 proxmox_backup::tools::file_set_contents(filename_priv, priv_key.as_slice(), None)?;
1055
1056 Ok(Value::Null)
1057}
ac716234
DM
1058
1059fn key_change_passphrase(
1060 param: Value,
1061 _info: &ApiMethod,
1062 _rpcenv: &mut dyn RpcEnvironment,
1063) -> Result<Value, Error> {
1064
9b06db45
DM
1065 let path = tools::required_string_param(&param, "path")?;
1066 let path = PathBuf::from(path);
ac716234 1067
181f097a
DM
1068 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
1069
ac716234
DM
1070 // we need a TTY to query the new password
1071 if !crate::tools::tty::stdin_isatty() {
1072 bail!("unable to change passphrase - no tty");
1073 }
1074
ab44acff 1075 let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
ac716234 1076
181f097a 1077 if kdf == "scrypt" {
ac716234 1078
181f097a
DM
1079 let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?;
1080 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
ac716234 1081
181f097a
DM
1082 if new_pw != verify_pw {
1083 bail!("Password verification fail!");
1084 }
1085
1086 if new_pw.len() < 5 {
1087 bail!("Password is too short!");
1088 }
ac716234 1089
ab44acff
DM
1090 let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?;
1091 new_key_config.created = created; // keep original value
1092
1093 store_key_config(&path, true, new_key_config)?;
ac716234 1094
181f097a
DM
1095 Ok(Value::Null)
1096 } else if kdf == "none" {
ab44acff 1097 let modified = Local.timestamp(Local::now().timestamp(), 0);
181f097a
DM
1098
1099 store_key_config(&path, true, KeyConfig {
1100 kdf: None,
ab44acff
DM
1101 created, // keep original value
1102 modified,
6d0983db 1103 data: key.to_vec(),
181f097a
DM
1104 })?;
1105
1106 Ok(Value::Null)
1107 } else {
1108 unreachable!();
1109 }
f2401311
DM
1110}
1111
1112fn key_mgmt_cli() -> CliCommandMap {
1113
181f097a
DM
1114 let kdf_schema: Arc<Schema> = Arc::new(
1115 StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.")
1116 .format(Arc::new(ApiStringFormat::Enum(&["scrypt", "none"])))
1117 .default("scrypt")
1118 .into()
1119 );
1120
f2401311
DM
1121 let key_create_cmd_def = CliCommand::new(
1122 ApiMethod::new(
1123 key_create,
1124 ObjectSchema::new("Create a new encryption key.")
9b06db45 1125 .required("path", StringSchema::new("File system path."))
181f097a 1126 .optional("kdf", kdf_schema.clone())
f2401311 1127 ))
9b06db45
DM
1128 .arg_param(vec!["path"])
1129 .completion_cb("path", tools::complete_file_name);
f2401311 1130
ac716234
DM
1131 let key_change_passphrase_cmd_def = CliCommand::new(
1132 ApiMethod::new(
1133 key_change_passphrase,
1134 ObjectSchema::new("Change the passphrase required to decrypt the key.")
9b06db45 1135 .required("path", StringSchema::new("File system path."))
181f097a 1136 .optional("kdf", kdf_schema.clone())
9b06db45
DM
1137 ))
1138 .arg_param(vec!["path"])
1139 .completion_cb("path", tools::complete_file_name);
ac716234 1140
37c5a175
DM
1141 let key_create_master_key_cmd_def = CliCommand::new(
1142 ApiMethod::new(
1143 key_create_master_key,
1144 ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.")
1145 ));
1146
3ea8bfc9
DM
1147 let key_import_master_pubkey_cmd_def = CliCommand::new(
1148 ApiMethod::new(
1149 key_import_master_pubkey,
1150 ObjectSchema::new("Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.")
1151 .required("path", StringSchema::new("File system path."))
1152 ))
1153 .arg_param(vec!["path"])
1154 .completion_cb("path", tools::complete_file_name);
1155
f2401311 1156 let cmd_def = CliCommandMap::new()
ac716234 1157 .insert("create".to_owned(), key_create_cmd_def.into())
37c5a175 1158 .insert("create-master-key".to_owned(), key_create_master_key_cmd_def.into())
3ea8bfc9 1159 .insert("import-master-pubkey".to_owned(), key_import_master_pubkey_cmd_def.into())
ac716234 1160 .insert("change-passphrase".to_owned(), key_change_passphrase_cmd_def.into());
f2401311
DM
1161
1162 cmd_def
1163}
1164
f2401311 1165fn main() {
33d64b81 1166
25f1650b
DM
1167 let backup_source_schema: Arc<Schema> = Arc::new(
1168 StringSchema::new("Backup source specification ([<label>:<path>]).")
1169 .format(Arc::new(ApiStringFormat::Pattern(&BACKUPSPEC_REGEX)))
1170 .into()
1171 );
1172
597a9203 1173 let backup_cmd_def = CliCommand::new(
ff5d3707 1174 ApiMethod::new(
bcd879cf 1175 create_backup,
597a9203 1176 ObjectSchema::new("Create (host) backup.")
f2401311 1177 .required("repository", REPO_URL_SCHEMA.clone())
ae0be2dd
DM
1178 .required(
1179 "backupspec",
1180 ArraySchema::new(
74cdb521 1181 "List of backup source specifications ([<label.ext>:<path>] ...)",
25f1650b 1182 backup_source_schema,
ae0be2dd
DM
1183 ).min_length(1)
1184 )
6d0983db
DM
1185 .optional(
1186 "keyfile",
1187 StringSchema::new("Path to encryption key. All data will be encrypted using this key."))
219ef0e6
DM
1188 .optional(
1189 "verbose",
1190 BooleanSchema::new("Verbose output.").default(false))
fba30411
DM
1191 .optional(
1192 "host-id",
1193 StringSchema::new("Use specified ID for the backup group name ('host/<id>'). The default is the system hostname."))
2d9d143a
DM
1194 .optional(
1195 "chunk-size",
1196 IntegerSchema::new("Chunk size in KB. Must be a power of 2.")
1197 .minimum(64)
1198 .maximum(4096)
1199 .default(4096)
1200 )
ff5d3707 1201 ))
ae0be2dd 1202 .arg_param(vec!["repository", "backupspec"])
d0a03d40 1203 .completion_cb("repository", complete_repository)
49811347 1204 .completion_cb("backupspec", complete_backup_source)
6d0983db 1205 .completion_cb("keyfile", tools::complete_file_name)
49811347 1206 .completion_cb("chunk-size", complete_chunk_size);
f8838fe9 1207
41c039e1
DM
1208 let list_cmd_def = CliCommand::new(
1209 ApiMethod::new(
812c6f87
DM
1210 list_backup_groups,
1211 ObjectSchema::new("List backup groups.")
f2401311 1212 .required("repository", REPO_URL_SCHEMA.clone())
41c039e1 1213 ))
d0a03d40
DM
1214 .arg_param(vec!["repository"])
1215 .completion_cb("repository", complete_repository);
41c039e1 1216
184f17af
DM
1217 let snapshots_cmd_def = CliCommand::new(
1218 ApiMethod::new(
1219 list_snapshots,
1220 ObjectSchema::new("List backup snapshots.")
f2401311 1221 .required("repository", REPO_URL_SCHEMA.clone())
184f17af
DM
1222 .required("group", StringSchema::new("Backup group."))
1223 ))
d0a03d40 1224 .arg_param(vec!["repository", "group"])
024f11bb 1225 .completion_cb("group", complete_backup_group)
d0a03d40 1226 .completion_cb("repository", complete_repository);
184f17af 1227
6f62c924
DM
1228 let forget_cmd_def = CliCommand::new(
1229 ApiMethod::new(
1230 forget_snapshots,
1231 ObjectSchema::new("Forget (remove) backup snapshots.")
f2401311 1232 .required("repository", REPO_URL_SCHEMA.clone())
6f62c924
DM
1233 .required("snapshot", StringSchema::new("Snapshot path."))
1234 ))
d0a03d40 1235 .arg_param(vec!["repository", "snapshot"])
b2388518
DM
1236 .completion_cb("repository", complete_repository)
1237 .completion_cb("snapshot", complete_group_or_snapshot);
6f62c924 1238
8cc0d6af
DM
1239 let garbage_collect_cmd_def = CliCommand::new(
1240 ApiMethod::new(
1241 start_garbage_collection,
1242 ObjectSchema::new("Start garbage collection for a specific repository.")
f2401311 1243 .required("repository", REPO_URL_SCHEMA.clone())
8cc0d6af 1244 ))
d0a03d40
DM
1245 .arg_param(vec!["repository"])
1246 .completion_cb("repository", complete_repository);
8cc0d6af 1247
9f912493
DM
1248 let restore_cmd_def = CliCommand::new(
1249 ApiMethod::new(
1250 restore,
1251 ObjectSchema::new("Restore backup repository.")
f2401311 1252 .required("repository", REPO_URL_SCHEMA.clone())
d5c34d98
DM
1253 .required("snapshot", StringSchema::new("Group/Snapshot path."))
1254 .required("archive-name", StringSchema::new("Backup archive name."))
bf125261
DM
1255 .required("target", StringSchema::new(r###"Target directory path. Use '-' to write to stdandard output.
1256
1257We do not extraxt '.pxar' archives when writing to stdandard output.
1258
1259"###
1260 ))
86eda3eb
DM
1261 .optional("keyfile", StringSchema::new("Path to encryption key."))
1262 .optional(
1263 "verbose",
1264 BooleanSchema::new("Verbose output.").default(false)
1265 )
9f912493 1266 ))
d0a03d40 1267 .arg_param(vec!["repository", "snapshot", "archive-name", "target"])
b2388518 1268 .completion_cb("repository", complete_repository)
08dc340a
DM
1269 .completion_cb("snapshot", complete_group_or_snapshot)
1270 .completion_cb("archive-name", complete_archive_name)
1271 .completion_cb("target", tools::complete_file_name);
9f912493 1272
83b7db02
DM
1273 let prune_cmd_def = CliCommand::new(
1274 ApiMethod::new(
1275 prune,
1276 proxmox_backup::api2::admin::datastore::add_common_prune_prameters(
1277 ObjectSchema::new("Prune backup repository.")
f2401311 1278 .required("repository", REPO_URL_SCHEMA.clone())
83b7db02
DM
1279 )
1280 ))
d0a03d40
DM
1281 .arg_param(vec!["repository"])
1282 .completion_cb("repository", complete_repository);
9f912493 1283
41c039e1 1284 let cmd_def = CliCommandMap::new()
597a9203 1285 .insert("backup".to_owned(), backup_cmd_def.into())
6f62c924 1286 .insert("forget".to_owned(), forget_cmd_def.into())
8cc0d6af 1287 .insert("garbage-collect".to_owned(), garbage_collect_cmd_def.into())
83b7db02 1288 .insert("list".to_owned(), list_cmd_def.into())
184f17af 1289 .insert("prune".to_owned(), prune_cmd_def.into())
9f912493 1290 .insert("restore".to_owned(), restore_cmd_def.into())
f2401311
DM
1291 .insert("snapshots".to_owned(), snapshots_cmd_def.into())
1292 .insert("key".to_owned(), key_mgmt_cli().into());
a914a774 1293
5a2df000
DM
1294 hyper::rt::run(futures::future::lazy(move || {
1295 run_cli_command(cmd_def.into());
1296 Ok(())
1297 }));
496a6784 1298
ff5d3707 1299}