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