]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-client.rs
src/pxar/sequential_decoder.rs: adapt code for partial restore by match pattern
[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 296
34a816cc
DM
297 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
298
299 let mut result = vec![];
300
812c6f87
DM
301 for item in list {
302
ad20d198
DM
303 let id = item["backup-id"].as_str().unwrap();
304 let btype = item["backup-type"].as_str().unwrap();
305 let epoch = item["last-backup"].as_i64().unwrap();
812c6f87 306 let last_backup = Local.timestamp(epoch, 0);
ad20d198 307 let backup_count = item["backup-count"].as_u64().unwrap();
812c6f87 308
1e9a94e5 309 let group = BackupGroup::new(btype, id);
812c6f87
DM
310
311 let path = group.group_path().to_str().unwrap().to_owned();
ad20d198 312
8e39232a 313 let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect();
6899dbfb 314 let files = strip_server_file_expenstions(files);
ad20d198 315
34a816cc
DM
316 if output_format == "text" {
317 println!("{:20} | {} | {:5} | {}", path, last_backup.format("%c"),
318 backup_count, tools::join(&files, ' '));
319 } else {
320 result.push(json!({
321 "backup-type": btype,
322 "backup-id": id,
323 "last-backup": epoch,
324 "backup-count": backup_count,
325 "files": files,
326 }));
327 }
812c6f87
DM
328 }
329
34a816cc
DM
330 if output_format != "text" { format_and_print_result(result.into(), &output_format); }
331
812c6f87
DM
332 Ok(Value::Null)
333}
334
184f17af
DM
335fn list_snapshots(
336 param: Value,
337 _info: &ApiMethod,
dd5495d6 338 _rpcenv: &mut dyn RpcEnvironment,
184f17af
DM
339) -> Result<Value, Error> {
340
2665cef7 341 let repo = extract_repository_from_value(&param)?;
184f17af
DM
342
343 let path = tools::required_string_param(&param, "group")?;
344 let group = BackupGroup::parse(path)?;
345
34a816cc
DM
346 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
347
45cdce06 348 let client = HttpClient::new(repo.host(), repo.user())?;
184f17af 349
9e391bb7 350 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
184f17af 351
9e391bb7
DM
352 let result = client.get(&path, Some(json!({
353 "backup-type": group.backup_type(),
354 "backup-id": group.backup_id(),
355 }))).wait()?;
184f17af 356
d0a03d40
DM
357 record_repository(&repo);
358
184f17af
DM
359 let list = result["data"].as_array().unwrap();
360
34a816cc
DM
361 let mut result = vec![];
362
184f17af
DM
363 for item in list {
364
365 let id = item["backup-id"].as_str().unwrap();
366 let btype = item["backup-type"].as_str().unwrap();
367 let epoch = item["backup-time"].as_i64().unwrap();
184f17af 368
391d3107 369 let snapshot = BackupDir::new(btype, id, epoch);
184f17af
DM
370
371 let path = snapshot.relative_path().to_str().unwrap().to_owned();
372
8e39232a 373 let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect();
6899dbfb 374 let files = strip_server_file_expenstions(files);
184f17af 375
34a816cc
DM
376 if output_format == "text" {
377 println!("{} | {} | {}", path, snapshot.backup_time().format("%c"), tools::join(&files, ' '));
378 } else {
379 result.push(json!({
380 "backup-type": btype,
381 "backup-id": id,
382 "backup-time": epoch,
383 "files": files,
384 }));
385 }
184f17af
DM
386 }
387
34a816cc
DM
388 if output_format != "text" { format_and_print_result(result.into(), &output_format); }
389
184f17af
DM
390 Ok(Value::Null)
391}
392
6f62c924
DM
393fn forget_snapshots(
394 param: Value,
395 _info: &ApiMethod,
dd5495d6 396 _rpcenv: &mut dyn RpcEnvironment,
6f62c924
DM
397) -> Result<Value, Error> {
398
2665cef7 399 let repo = extract_repository_from_value(&param)?;
6f62c924
DM
400
401 let path = tools::required_string_param(&param, "snapshot")?;
402 let snapshot = BackupDir::parse(path)?;
403
45cdce06 404 let mut client = HttpClient::new(repo.host(), repo.user())?;
6f62c924 405
9e391bb7 406 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
6f62c924 407
9e391bb7
DM
408 let result = client.delete(&path, Some(json!({
409 "backup-type": snapshot.group().backup_type(),
410 "backup-id": snapshot.group().backup_id(),
411 "backup-time": snapshot.backup_time().timestamp(),
412 }))).wait()?;
6f62c924 413
d0a03d40
DM
414 record_repository(&repo);
415
6f62c924
DM
416 Ok(result)
417}
418
8cc0d6af
DM
419fn start_garbage_collection(
420 param: Value,
421 _info: &ApiMethod,
dd5495d6 422 _rpcenv: &mut dyn RpcEnvironment,
8cc0d6af
DM
423) -> Result<Value, Error> {
424
2665cef7 425 let repo = extract_repository_from_value(&param)?;
8cc0d6af 426
45cdce06 427 let mut client = HttpClient::new(repo.host(), repo.user())?;
8cc0d6af 428
d0a03d40 429 let path = format!("api2/json/admin/datastore/{}/gc", repo.store());
8cc0d6af 430
5a2df000 431 let result = client.post(&path, None).wait()?;
8cc0d6af 432
d0a03d40
DM
433 record_repository(&repo);
434
8cc0d6af
DM
435 Ok(result)
436}
33d64b81 437
ae0be2dd
DM
438fn parse_backupspec(value: &str) -> Result<(&str, &str), Error> {
439
440 if let Some(caps) = BACKUPSPEC_REGEX.captures(value) {
441 return Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str()));
442 }
443 bail!("unable to parse directory specification '{}'", value);
444}
445
6049b71f
DM
446fn create_backup(
447 param: Value,
448 _info: &ApiMethod,
dd5495d6 449 _rpcenv: &mut dyn RpcEnvironment,
6049b71f 450) -> Result<Value, Error> {
ff5d3707 451
2665cef7 452 let repo = extract_repository_from_value(&param)?;
ae0be2dd
DM
453
454 let backupspec_list = tools::required_array_param(&param, "backupspec")?;
a914a774 455
eed6db39
DM
456 let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false);
457
219ef0e6
DM
458 let verbose = param["verbose"].as_bool().unwrap_or(false);
459
36898ffc 460 let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize);
2d9d143a 461
247cdbce
DM
462 if let Some(size) = chunk_size_opt {
463 verify_chunk_size(size)?;
2d9d143a
DM
464 }
465
6d0983db
DM
466 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
467
fba30411
DM
468 let backup_id = param["host-id"].as_str().unwrap_or(&tools::nodename());
469
ae0be2dd 470 let mut upload_list = vec![];
a914a774 471
ec8a9bb9 472 enum BackupType { PXAR, IMAGE, CONFIG };
6af905c1 473
ae0be2dd
DM
474 for backupspec in backupspec_list {
475 let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?;
bcd879cf 476
eb1804c5
DM
477 use std::os::unix::fs::FileTypeExt;
478
479 let metadata = match std::fs::metadata(filename) {
480 Ok(m) => m,
ae0be2dd
DM
481 Err(err) => bail!("unable to access '{}' - {}", filename, err),
482 };
eb1804c5 483 let file_type = metadata.file_type();
23bb8780 484
ec8a9bb9 485 let extension = Path::new(target).extension().map(|s| s.to_str().unwrap()).unwrap();
bcd879cf 486
ec8a9bb9
DM
487 match extension {
488 "pxar" => {
489 if !file_type.is_dir() {
490 bail!("got unexpected file type (expected directory)");
491 }
492 upload_list.push((BackupType::PXAR, filename.to_owned(), target.to_owned(), 0));
493 }
494 "img" => {
eb1804c5 495
ec8a9bb9
DM
496 if !(file_type.is_file() || file_type.is_block_device()) {
497 bail!("got unexpected file type (expected file or block device)");
498 }
eb1804c5 499
ec8a9bb9 500 let size = tools::image_size(&PathBuf::from(filename))?;
23bb8780 501
ec8a9bb9 502 if size == 0 { bail!("got zero-sized file '{}'", filename); }
ae0be2dd 503
ec8a9bb9
DM
504 upload_list.push((BackupType::IMAGE, filename.to_owned(), target.to_owned(), size));
505 }
506 "conf" => {
507 if !file_type.is_file() {
508 bail!("got unexpected file type (expected regular file)");
509 }
510 upload_list.push((BackupType::CONFIG, filename.to_owned(), target.to_owned(), metadata.len()));
511 }
512 _ => {
513 bail!("got unknown archive extension '{}'", extension);
514 }
ae0be2dd
DM
515 }
516 }
517
cdebd467 518 let backup_time = Local.timestamp(Local::now().timestamp(), 0);
ae0be2dd 519
c4ff3dce 520 let client = HttpClient::new(repo.host(), repo.user())?;
d0a03d40
DM
521 record_repository(&repo);
522
cdebd467
DM
523 println!("Starting backup");
524 println!("Client name: {}", tools::nodename());
525 println!("Start Time: {}", backup_time.to_rfc3339());
51144821 526
bb823140
DM
527 let (crypt_config, rsa_encrypted_key) = match keyfile {
528 None => (None, None),
6d0983db 529 Some(path) => {
bb823140
DM
530 let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
531
532 let crypt_config = CryptConfig::new(key)?;
533
534 let path = master_pubkey_path()?;
535 if path.exists() {
536 let pem_data = proxmox_backup::tools::file_get_contents(&path)?;
537 let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
538 let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?;
539 (Some(Arc::new(crypt_config)), Some(enc_key))
540 } else {
541 (Some(Arc::new(crypt_config)), None)
542 }
6d0983db
DM
543 }
544 };
f98ac774 545
39e60bd6 546 let client = client.start_backup(repo.store(), "host", &backup_id, verbose).wait()?;
c4ff3dce 547
6af905c1
DM
548 for (backup_type, filename, target, size) in upload_list {
549 match backup_type {
ec8a9bb9
DM
550 BackupType::CONFIG => {
551 println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target);
9f46c7de 552 client.upload_blob_from_file(&filename, &target, crypt_config.clone(), true).wait()?;
ec8a9bb9 553 }
6af905c1
DM
554 BackupType::PXAR => {
555 println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target);
f98ac774
DM
556 backup_directory(
557 &client,
558 &filename,
559 &target,
560 chunk_size_opt,
561 all_file_systems,
562 verbose,
563 crypt_config.clone(),
564 )?;
6af905c1
DM
565 }
566 BackupType::IMAGE => {
567 println!("Upload image '{}' to '{:?}' as {}", filename, repo, target);
f98ac774
DM
568 backup_image(
569 &client,
570 &filename,
571 &target,
572 size,
573 chunk_size_opt,
574 verbose,
575 crypt_config.clone(),
576 )?;
6af905c1
DM
577 }
578 }
4818c8b6
DM
579 }
580
bb823140
DM
581 if let Some(rsa_encrypted_key) = rsa_encrypted_key {
582 let target = "rsa-encrypted.key";
583 println!("Upload RSA encoded key to '{:?}' as {}", repo, target);
584 client.upload_blob_from_data(rsa_encrypted_key, target, None, false).wait()?;
585
586 // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t
587 /*
588 let mut buffer2 = vec![0u8; rsa.size() as usize];
589 let pem_data = proxmox_backup::tools::file_get_contents("master-private.pem")?;
590 let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?;
591 let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?;
592 println!("TEST {} {:?}", len, buffer2);
593 */
9f46c7de
DM
594 }
595
c4ff3dce
DM
596 client.finish().wait()?;
597
cdebd467 598 let end_time = Local.timestamp(Local::now().timestamp(), 0);
3ec3ec3f
DM
599 let elapsed = end_time.signed_duration_since(backup_time);
600 println!("Duration: {}", elapsed);
601
cdebd467 602 println!("End Time: {}", end_time.to_rfc3339());
3d5c11e5 603
ff5d3707 604 Ok(Value::Null)
f98ea63d
DM
605}
606
d0a03d40 607fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
f98ea63d
DM
608
609 let mut result = vec![];
610
611 let data: Vec<&str> = arg.splitn(2, ':').collect();
612
bff11030 613 if data.len() != 2 {
8968258b
DM
614 result.push(String::from("root.pxar:/"));
615 result.push(String::from("etc.pxar:/etc"));
bff11030
DM
616 return result;
617 }
f98ea63d 618
496a6784 619 let files = tools::complete_file_name(data[1], param);
f98ea63d
DM
620
621 for file in files {
622 result.push(format!("{}:{}", data[0], file));
623 }
624
625 result
ff5d3707 626}
627
9f912493
DM
628fn restore(
629 param: Value,
630 _info: &ApiMethod,
dd5495d6 631 _rpcenv: &mut dyn RpcEnvironment,
9f912493
DM
632) -> Result<Value, Error> {
633
2665cef7 634 let repo = extract_repository_from_value(&param)?;
9f912493 635
86eda3eb
DM
636 let verbose = param["verbose"].as_bool().unwrap_or(false);
637
d5c34d98
DM
638 let archive_name = tools::required_string_param(&param, "archive-name")?;
639
86eda3eb 640 let client = HttpClient::new(repo.host(), repo.user())?;
d0a03d40 641
d0a03d40 642 record_repository(&repo);
d5c34d98 643
9f912493 644 let path = tools::required_string_param(&param, "snapshot")?;
9f912493 645
86eda3eb 646 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
d5c34d98 647 let group = BackupGroup::parse(path)?;
9f912493 648
9e391bb7
DM
649 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
650 let result = client.get(&path, Some(json!({
d5c34d98
DM
651 "backup-type": group.backup_type(),
652 "backup-id": group.backup_id(),
9e391bb7 653 }))).wait()?;
9f912493 654
d5c34d98
DM
655 let list = result["data"].as_array().unwrap();
656 if list.len() == 0 {
657 bail!("backup group '{}' does not contain any snapshots:", path);
658 }
9f912493 659
86eda3eb
DM
660 let epoch = list[0]["backup-time"].as_i64().unwrap();
661 let backup_time = Local.timestamp(epoch, 0);
662 (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time)
d5c34d98
DM
663 } else {
664 let snapshot = BackupDir::parse(path)?;
86eda3eb
DM
665 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
666 };
9f912493 667
d5c34d98 668 let target = tools::required_string_param(&param, "target")?;
bf125261 669 let target = if target == "-" { None } else { Some(target) };
2ae7d196 670
86eda3eb 671 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
2ae7d196 672
86eda3eb
DM
673 let crypt_config = match keyfile {
674 None => None,
675 Some(path) => {
676 let (key, _) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
677 Some(Arc::new(CryptConfig::new(key)?))
678 }
679 };
d5c34d98 680
afb4cd28
DM
681 let server_archive_name = if archive_name.ends_with(".pxar") {
682 format!("{}.didx", archive_name)
683 } else if archive_name.ends_with(".img") {
684 format!("{}.fidx", archive_name)
685 } else {
f8100e96 686 format!("{}.blob", archive_name)
afb4cd28 687 };
9f912493 688
86eda3eb
DM
689 let client = client.start_backup_reader(repo.store(), &backup_type, &backup_id, backup_time, true).wait()?;
690
691 use std::os::unix::fs::OpenOptionsExt;
692
693 let tmpfile = std::fs::OpenOptions::new()
694 .write(true)
695 .read(true)
696 .custom_flags(libc::O_TMPFILE)
697 .open("/tmp")?;
698
f8100e96
DM
699 if server_archive_name.ends_with(".blob") {
700
701 let writer = Vec::with_capacity(1024*1024);
702 let blob_data = client.download(&server_archive_name, writer).wait()?;
703 let blob = DataBlob::from_raw(blob_data)?;
704 blob.verify_crc()?;
705
706 let raw_data = match crypt_config {
707 Some(ref crypt_config) => blob.decode(Some(crypt_config))?,
708 None => blob.decode(None)?,
709 };
710
bf125261
DM
711 if let Some(target) = target {
712 crate::tools::file_set_contents(target, &raw_data, None)?;
713 } else {
714 let stdout = std::io::stdout();
715 let mut writer = stdout.lock();
716 writer.write_all(&raw_data)
717 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
718 }
f8100e96
DM
719
720 } else if server_archive_name.ends_with(".didx") {
afb4cd28 721 let tmpfile = client.download(&server_archive_name, tmpfile).wait()?;
86eda3eb 722
afb4cd28
DM
723 let index = DynamicIndexReader::new(tmpfile)
724 .map_err(|err| format_err!("unable to read dynamic index '{}' - {}", archive_name, err))?;
86eda3eb 725
f4bf7dfc
DM
726 let most_used = index.find_most_used_chunks(8);
727
728 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
729
afb4cd28 730 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
86eda3eb 731
bf125261 732 if let Some(target) = target {
86eda3eb 733
bf125261
DM
734 let feature_flags = pxar::CA_FORMAT_DEFAULT;
735 let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags, |path| {
736 if verbose {
737 println!("{:?}", path);
738 }
739 Ok(())
740 });
741
742 decoder.restore(Path::new(target))?;
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 }
afb4cd28
DM
750 } else if server_archive_name.ends_with(".fidx") {
751 let tmpfile = client.download(&server_archive_name, tmpfile).wait()?;
752
753 let index = FixedIndexReader::new(tmpfile)
754 .map_err(|err| format_err!("unable to read fixed index '{}' - {}", archive_name, err))?;
7dcbe051 755
f4bf7dfc
DM
756 let most_used = index.find_most_used_chunks(8);
757
758 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
759
afb4cd28
DM
760 let mut reader = BufferedFixedReader::new(index, chunk_reader);
761
bf125261
DM
762 if let Some(target) = target {
763 let mut writer = std::fs::OpenOptions::new()
764 .write(true)
765 .create(true)
766 .create_new(true)
767 .open(target)
768 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
769
770 std::io::copy(&mut reader, &mut writer)
771 .map_err(|err| format_err!("unable to store data - {}", err))?;
772 } else {
773 let stdout = std::io::stdout();
774 let mut writer = stdout.lock();
afb4cd28 775
bf125261
DM
776 std::io::copy(&mut reader, &mut writer)
777 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
778 }
45db6f89 779 } else {
f8100e96 780 bail!("unknown archive file extension (expected .pxar of .img)");
3031e44c 781 }
fef44d4f
DM
782
783 Ok(Value::Null)
45db6f89
DM
784}
785
83b7db02
DM
786fn prune(
787 mut param: Value,
788 _info: &ApiMethod,
dd5495d6 789 _rpcenv: &mut dyn RpcEnvironment,
83b7db02
DM
790) -> Result<Value, Error> {
791
2665cef7 792 let repo = extract_repository_from_value(&param)?;
83b7db02 793
45cdce06 794 let mut client = HttpClient::new(repo.host(), repo.user())?;
83b7db02 795
d0a03d40 796 let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
83b7db02
DM
797
798 param.as_object_mut().unwrap().remove("repository");
799
5a2df000 800 let result = client.post(&path, Some(param)).wait()?;
83b7db02 801
d0a03d40
DM
802 record_repository(&repo);
803
83b7db02
DM
804 Ok(result)
805}
806
34a816cc
DM
807fn status(
808 param: Value,
809 _info: &ApiMethod,
810 _rpcenv: &mut dyn RpcEnvironment,
811) -> Result<Value, Error> {
812
813 let repo = extract_repository_from_value(&param)?;
814
815 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
816
817 let client = HttpClient::new(repo.host(), repo.user())?;
818
819 let path = format!("api2/json/admin/datastore/{}/status", repo.store());
820
821 let result = client.get(&path, None).wait()?;
822 let data = &result["data"];
823
824 record_repository(&repo);
825
826 if output_format == "text" {
827 let total = data["total"].as_u64().unwrap();
828 let used = data["used"].as_u64().unwrap();
829 let avail = data["avail"].as_u64().unwrap();
830 let roundup = total/200;
831
832 println!(
833 "total: {} used: {} ({} %) available: {}",
834 total,
835 used,
836 ((used+roundup)*100)/total,
837 avail,
838 );
839 } else {
840 format_and_print_result(result, &output_format);
841 }
842
843 Ok(Value::Null)
844}
845
5a2df000 846// like get, but simply ignore errors and return Null instead
b2388518 847fn try_get(repo: &BackupRepository, url: &str) -> Value {
024f11bb 848
45cdce06
DM
849 let client = match HttpClient::new(repo.host(), repo.user()) {
850 Ok(v) => v,
851 _ => return Value::Null,
852 };
b2388518 853
9e391bb7 854 let mut resp = match client.get(url, None).wait() {
b2388518
DM
855 Ok(v) => v,
856 _ => return Value::Null,
857 };
858
859 if let Some(map) = resp.as_object_mut() {
860 if let Some(data) = map.remove("data") {
861 return data;
862 }
863 }
864 Value::Null
865}
866
b2388518 867fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
024f11bb 868
b2388518
DM
869 let mut result = vec![];
870
2665cef7 871 let repo = match extract_repository_from_map(param) {
b2388518 872 Some(v) => v,
024f11bb
DM
873 _ => return result,
874 };
875
b2388518
DM
876 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
877
878 let data = try_get(&repo, &path);
879
880 if let Some(list) = data.as_array() {
024f11bb 881 for item in list {
98f0b972
DM
882 if let (Some(backup_id), Some(backup_type)) =
883 (item["backup-id"].as_str(), item["backup-type"].as_str())
884 {
885 result.push(format!("{}/{}", backup_type, backup_id));
024f11bb
DM
886 }
887 }
888 }
889
890 result
891}
892
b2388518
DM
893fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
894
895 let mut result = vec![];
896
2665cef7 897 let repo = match extract_repository_from_map(param) {
b2388518
DM
898 Some(v) => v,
899 _ => return result,
900 };
901
902 if arg.matches('/').count() < 2 {
903 let groups = complete_backup_group(arg, param);
904 for group in groups {
905 result.push(group.to_string());
906 result.push(format!("{}/", group));
907 }
908 return result;
909 }
910
911 let mut parts = arg.split('/');
912 let query = tools::json_object_to_query(json!({
913 "backup-type": parts.next().unwrap(),
914 "backup-id": parts.next().unwrap(),
915 })).unwrap();
916
917 let path = format!("api2/json/admin/datastore/{}/snapshots?{}", repo.store(), query);
918
919 let data = try_get(&repo, &path);
920
921 if let Some(list) = data.as_array() {
922 for item in list {
923 if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
924 (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64())
925 {
926 let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
927 result.push(snapshot.relative_path().to_str().unwrap().to_owned());
928 }
929 }
930 }
931
932 result
933}
934
45db6f89 935fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
08dc340a
DM
936
937 let mut result = vec![];
938
2665cef7 939 let repo = match extract_repository_from_map(param) {
08dc340a
DM
940 Some(v) => v,
941 _ => return result,
942 };
943
944 let snapshot = match param.get("snapshot") {
945 Some(path) => {
946 match BackupDir::parse(path) {
947 Ok(v) => v,
948 _ => return result,
949 }
950 }
951 _ => return result,
952 };
953
954 let query = tools::json_object_to_query(json!({
955 "backup-type": snapshot.group().backup_type(),
956 "backup-id": snapshot.group().backup_id(),
957 "backup-time": snapshot.backup_time().timestamp(),
958 })).unwrap();
959
960 let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query);
961
962 let data = try_get(&repo, &path);
963
964 if let Some(list) = data.as_array() {
965 for item in list {
966 if let Some(filename) = item.as_str() {
967 result.push(filename.to_owned());
968 }
969 }
970 }
971
45db6f89
DM
972 result
973}
974
975fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
976
977 let result = complete_server_file_name(arg, param);
978
6899dbfb 979 strip_server_file_expenstions(result)
08dc340a
DM
980}
981
49811347
DM
982fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
983
984 let mut result = vec![];
985
986 let mut size = 64;
987 loop {
988 result.push(size.to_string());
989 size = size * 2;
990 if size > 4096 { break; }
991 }
992
993 result
994}
995
826f309b 996fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
ff5d3707 997
f2401311
DM
998 // fixme: implement other input methods
999
1000 use std::env::VarError::*;
1001 match std::env::var("PBS_ENCRYPTION_PASSWORD") {
826f309b 1002 Ok(p) => return Ok(p.as_bytes().to_vec()),
f2401311
DM
1003 Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
1004 Err(NotPresent) => {
1005 // Try another method
1006 }
1007 }
1008
1009 // If we're on a TTY, query the user for a password
1010 if crate::tools::tty::stdin_isatty() {
826f309b 1011 return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?);
f2401311
DM
1012 }
1013
1014 bail!("no password input mechanism available");
1015}
1016
ac716234
DM
1017fn key_create(
1018 param: Value,
1019 _info: &ApiMethod,
1020 _rpcenv: &mut dyn RpcEnvironment,
1021) -> Result<Value, Error> {
1022
9b06db45
DM
1023 let path = tools::required_string_param(&param, "path")?;
1024 let path = PathBuf::from(path);
ac716234 1025
181f097a 1026 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
ac716234
DM
1027
1028 let key = proxmox::sys::linux::random_data(32)?;
1029
181f097a
DM
1030 if kdf == "scrypt" {
1031 // always read passphrase from tty
1032 if !crate::tools::tty::stdin_isatty() {
1033 bail!("unable to read passphrase - no tty");
1034 }
ac716234 1035
181f097a
DM
1036 let password = crate::tools::tty::read_password("Encryption Key Password: ")?;
1037
ab44acff 1038 let key_config = encrypt_key_with_passphrase(&key, &password)?;
37c5a175 1039
ab44acff 1040 store_key_config(&path, false, key_config)?;
181f097a
DM
1041
1042 Ok(Value::Null)
1043 } else if kdf == "none" {
1044 let created = Local.timestamp(Local::now().timestamp(), 0);
1045
1046 store_key_config(&path, false, KeyConfig {
1047 kdf: None,
1048 created,
ab44acff 1049 modified: created,
181f097a
DM
1050 data: key,
1051 })?;
1052
1053 Ok(Value::Null)
1054 } else {
1055 unreachable!();
1056 }
ac716234
DM
1057}
1058
9f46c7de
DM
1059fn master_pubkey_path() -> Result<PathBuf, Error> {
1060 let base = BaseDirectories::with_prefix("proxmox-backup")?;
1061
1062 // usually $HOME/.config/proxmox-backup/master-public.pem
1063 let path = base.place_config_file("master-public.pem")?;
1064
1065 Ok(path)
1066}
1067
3ea8bfc9
DM
1068fn key_import_master_pubkey(
1069 param: Value,
1070 _info: &ApiMethod,
1071 _rpcenv: &mut dyn RpcEnvironment,
1072) -> Result<Value, Error> {
1073
1074 let path = tools::required_string_param(&param, "path")?;
1075 let path = PathBuf::from(path);
1076
1077 let pem_data = proxmox_backup::tools::file_get_contents(&path)?;
1078
1079 if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
1080 bail!("Unable to decode PEM data - {}", err);
1081 }
1082
9f46c7de 1083 let target_path = master_pubkey_path()?;
3ea8bfc9
DM
1084
1085 proxmox_backup::tools::file_set_contents(&target_path, &pem_data, None)?;
1086
1087 println!("Imported public master key to {:?}", target_path);
1088
1089 Ok(Value::Null)
1090}
1091
37c5a175
DM
1092fn key_create_master_key(
1093 _param: Value,
1094 _info: &ApiMethod,
1095 _rpcenv: &mut dyn RpcEnvironment,
1096) -> Result<Value, Error> {
1097
1098 // we need a TTY to query the new password
1099 if !crate::tools::tty::stdin_isatty() {
1100 bail!("unable to create master key - no tty");
1101 }
1102
1103 let rsa = openssl::rsa::Rsa::generate(4096)?;
1104 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
1105
1106 let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?;
1107 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
1108
1109 if new_pw != verify_pw {
1110 bail!("Password verification fail!");
1111 }
1112
1113 if new_pw.len() < 5 {
1114 bail!("Password is too short!");
1115 }
1116
1117 let pub_key: Vec<u8> = pkey.public_key_to_pem()?;
1118 let filename_pub = "master-public.pem";
1119 println!("Writing public master key to {}", filename_pub);
1120 proxmox_backup::tools::file_set_contents(filename_pub, pub_key.as_slice(), None)?;
1121
1122 let cipher = openssl::symm::Cipher::aes_256_cbc();
1123 let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?;
1124
1125 let filename_priv = "master-private.pem";
1126 println!("Writing private master key to {}", filename_priv);
1127 proxmox_backup::tools::file_set_contents(filename_priv, priv_key.as_slice(), None)?;
1128
1129 Ok(Value::Null)
1130}
ac716234
DM
1131
1132fn key_change_passphrase(
1133 param: Value,
1134 _info: &ApiMethod,
1135 _rpcenv: &mut dyn RpcEnvironment,
1136) -> Result<Value, Error> {
1137
9b06db45
DM
1138 let path = tools::required_string_param(&param, "path")?;
1139 let path = PathBuf::from(path);
ac716234 1140
181f097a
DM
1141 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
1142
ac716234
DM
1143 // we need a TTY to query the new password
1144 if !crate::tools::tty::stdin_isatty() {
1145 bail!("unable to change passphrase - no tty");
1146 }
1147
ab44acff 1148 let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?;
ac716234 1149
181f097a 1150 if kdf == "scrypt" {
ac716234 1151
181f097a
DM
1152 let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?;
1153 let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?;
ac716234 1154
181f097a
DM
1155 if new_pw != verify_pw {
1156 bail!("Password verification fail!");
1157 }
1158
1159 if new_pw.len() < 5 {
1160 bail!("Password is too short!");
1161 }
ac716234 1162
ab44acff
DM
1163 let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?;
1164 new_key_config.created = created; // keep original value
1165
1166 store_key_config(&path, true, new_key_config)?;
ac716234 1167
181f097a
DM
1168 Ok(Value::Null)
1169 } else if kdf == "none" {
ab44acff 1170 let modified = Local.timestamp(Local::now().timestamp(), 0);
181f097a
DM
1171
1172 store_key_config(&path, true, KeyConfig {
1173 kdf: None,
ab44acff
DM
1174 created, // keep original value
1175 modified,
6d0983db 1176 data: key.to_vec(),
181f097a
DM
1177 })?;
1178
1179 Ok(Value::Null)
1180 } else {
1181 unreachable!();
1182 }
f2401311
DM
1183}
1184
1185fn key_mgmt_cli() -> CliCommandMap {
1186
181f097a
DM
1187 let kdf_schema: Arc<Schema> = Arc::new(
1188 StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.")
1189 .format(Arc::new(ApiStringFormat::Enum(&["scrypt", "none"])))
1190 .default("scrypt")
1191 .into()
1192 );
1193
f2401311
DM
1194 let key_create_cmd_def = CliCommand::new(
1195 ApiMethod::new(
1196 key_create,
1197 ObjectSchema::new("Create a new encryption key.")
9b06db45 1198 .required("path", StringSchema::new("File system path."))
181f097a 1199 .optional("kdf", kdf_schema.clone())
f2401311 1200 ))
9b06db45
DM
1201 .arg_param(vec!["path"])
1202 .completion_cb("path", tools::complete_file_name);
f2401311 1203
ac716234
DM
1204 let key_change_passphrase_cmd_def = CliCommand::new(
1205 ApiMethod::new(
1206 key_change_passphrase,
1207 ObjectSchema::new("Change the passphrase required to decrypt the key.")
9b06db45 1208 .required("path", StringSchema::new("File system path."))
181f097a 1209 .optional("kdf", kdf_schema.clone())
9b06db45
DM
1210 ))
1211 .arg_param(vec!["path"])
1212 .completion_cb("path", tools::complete_file_name);
ac716234 1213
37c5a175
DM
1214 let key_create_master_key_cmd_def = CliCommand::new(
1215 ApiMethod::new(
1216 key_create_master_key,
1217 ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.")
1218 ));
1219
3ea8bfc9
DM
1220 let key_import_master_pubkey_cmd_def = CliCommand::new(
1221 ApiMethod::new(
1222 key_import_master_pubkey,
1223 ObjectSchema::new("Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.")
1224 .required("path", StringSchema::new("File system path."))
1225 ))
1226 .arg_param(vec!["path"])
1227 .completion_cb("path", tools::complete_file_name);
1228
f2401311 1229 let cmd_def = CliCommandMap::new()
ac716234 1230 .insert("create".to_owned(), key_create_cmd_def.into())
37c5a175 1231 .insert("create-master-key".to_owned(), key_create_master_key_cmd_def.into())
3ea8bfc9 1232 .insert("import-master-pubkey".to_owned(), key_import_master_pubkey_cmd_def.into())
ac716234 1233 .insert("change-passphrase".to_owned(), key_change_passphrase_cmd_def.into());
f2401311
DM
1234
1235 cmd_def
1236}
1237
f2401311 1238fn main() {
33d64b81 1239
25f1650b
DM
1240 let backup_source_schema: Arc<Schema> = Arc::new(
1241 StringSchema::new("Backup source specification ([<label>:<path>]).")
1242 .format(Arc::new(ApiStringFormat::Pattern(&BACKUPSPEC_REGEX)))
1243 .into()
1244 );
1245
597a9203 1246 let backup_cmd_def = CliCommand::new(
ff5d3707 1247 ApiMethod::new(
bcd879cf 1248 create_backup,
597a9203 1249 ObjectSchema::new("Create (host) backup.")
ae0be2dd
DM
1250 .required(
1251 "backupspec",
1252 ArraySchema::new(
74cdb521 1253 "List of backup source specifications ([<label.ext>:<path>] ...)",
25f1650b 1254 backup_source_schema,
ae0be2dd
DM
1255 ).min_length(1)
1256 )
2665cef7 1257 .optional("repository", REPO_URL_SCHEMA.clone())
6d0983db
DM
1258 .optional(
1259 "keyfile",
1260 StringSchema::new("Path to encryption key. All data will be encrypted using this key."))
219ef0e6
DM
1261 .optional(
1262 "verbose",
1263 BooleanSchema::new("Verbose output.").default(false))
fba30411
DM
1264 .optional(
1265 "host-id",
1266 StringSchema::new("Use specified ID for the backup group name ('host/<id>'). The default is the system hostname."))
2d9d143a
DM
1267 .optional(
1268 "chunk-size",
1269 IntegerSchema::new("Chunk size in KB. Must be a power of 2.")
1270 .minimum(64)
1271 .maximum(4096)
1272 .default(4096)
1273 )
ff5d3707 1274 ))
2665cef7 1275 .arg_param(vec!["backupspec"])
d0a03d40 1276 .completion_cb("repository", complete_repository)
49811347 1277 .completion_cb("backupspec", complete_backup_source)
6d0983db 1278 .completion_cb("keyfile", tools::complete_file_name)
49811347 1279 .completion_cb("chunk-size", complete_chunk_size);
f8838fe9 1280
41c039e1
DM
1281 let list_cmd_def = CliCommand::new(
1282 ApiMethod::new(
812c6f87
DM
1283 list_backup_groups,
1284 ObjectSchema::new("List backup groups.")
2665cef7 1285 .optional("repository", REPO_URL_SCHEMA.clone())
34a816cc 1286 .optional("output-format", OUTPUT_FORMAT.clone())
41c039e1 1287 ))
d0a03d40 1288 .completion_cb("repository", complete_repository);
41c039e1 1289
184f17af
DM
1290 let snapshots_cmd_def = CliCommand::new(
1291 ApiMethod::new(
1292 list_snapshots,
1293 ObjectSchema::new("List backup snapshots.")
184f17af 1294 .required("group", StringSchema::new("Backup group."))
2665cef7 1295 .optional("repository", REPO_URL_SCHEMA.clone())
34a816cc 1296 .optional("output-format", OUTPUT_FORMAT.clone())
184f17af 1297 ))
2665cef7 1298 .arg_param(vec!["group"])
024f11bb 1299 .completion_cb("group", complete_backup_group)
d0a03d40 1300 .completion_cb("repository", complete_repository);
184f17af 1301
6f62c924
DM
1302 let forget_cmd_def = CliCommand::new(
1303 ApiMethod::new(
1304 forget_snapshots,
1305 ObjectSchema::new("Forget (remove) backup snapshots.")
6f62c924 1306 .required("snapshot", StringSchema::new("Snapshot path."))
2665cef7 1307 .optional("repository", REPO_URL_SCHEMA.clone())
6f62c924 1308 ))
2665cef7 1309 .arg_param(vec!["snapshot"])
b2388518
DM
1310 .completion_cb("repository", complete_repository)
1311 .completion_cb("snapshot", complete_group_or_snapshot);
6f62c924 1312
8cc0d6af
DM
1313 let garbage_collect_cmd_def = CliCommand::new(
1314 ApiMethod::new(
1315 start_garbage_collection,
1316 ObjectSchema::new("Start garbage collection for a specific repository.")
2665cef7 1317 .optional("repository", REPO_URL_SCHEMA.clone())
8cc0d6af 1318 ))
d0a03d40 1319 .completion_cb("repository", complete_repository);
8cc0d6af 1320
9f912493
DM
1321 let restore_cmd_def = CliCommand::new(
1322 ApiMethod::new(
1323 restore,
1324 ObjectSchema::new("Restore backup repository.")
d5c34d98
DM
1325 .required("snapshot", StringSchema::new("Group/Snapshot path."))
1326 .required("archive-name", StringSchema::new("Backup archive name."))
bf125261
DM
1327 .required("target", StringSchema::new(r###"Target directory path. Use '-' to write to stdandard output.
1328
1329We do not extraxt '.pxar' archives when writing to stdandard output.
1330
1331"###
1332 ))
2665cef7 1333 .optional("repository", REPO_URL_SCHEMA.clone())
86eda3eb
DM
1334 .optional("keyfile", StringSchema::new("Path to encryption key."))
1335 .optional(
1336 "verbose",
1337 BooleanSchema::new("Verbose output.").default(false)
1338 )
9f912493 1339 ))
2665cef7 1340 .arg_param(vec!["snapshot", "archive-name", "target"])
b2388518 1341 .completion_cb("repository", complete_repository)
08dc340a
DM
1342 .completion_cb("snapshot", complete_group_or_snapshot)
1343 .completion_cb("archive-name", complete_archive_name)
1344 .completion_cb("target", tools::complete_file_name);
9f912493 1345
83b7db02
DM
1346 let prune_cmd_def = CliCommand::new(
1347 ApiMethod::new(
1348 prune,
1349 proxmox_backup::api2::admin::datastore::add_common_prune_prameters(
1350 ObjectSchema::new("Prune backup repository.")
2665cef7 1351 .optional("repository", REPO_URL_SCHEMA.clone())
83b7db02
DM
1352 )
1353 ))
d0a03d40 1354 .completion_cb("repository", complete_repository);
9f912493 1355
34a816cc
DM
1356 let status_cmd_def = CliCommand::new(
1357 ApiMethod::new(
1358 status,
1359 ObjectSchema::new("Get repository status.")
1360 .optional("repository", REPO_URL_SCHEMA.clone())
1361 .optional("output-format", OUTPUT_FORMAT.clone())
1362 ))
1363 .completion_cb("repository", complete_repository);
1364
41c039e1 1365 let cmd_def = CliCommandMap::new()
597a9203 1366 .insert("backup".to_owned(), backup_cmd_def.into())
6f62c924 1367 .insert("forget".to_owned(), forget_cmd_def.into())
8cc0d6af 1368 .insert("garbage-collect".to_owned(), garbage_collect_cmd_def.into())
83b7db02 1369 .insert("list".to_owned(), list_cmd_def.into())
184f17af 1370 .insert("prune".to_owned(), prune_cmd_def.into())
9f912493 1371 .insert("restore".to_owned(), restore_cmd_def.into())
f2401311 1372 .insert("snapshots".to_owned(), snapshots_cmd_def.into())
34a816cc 1373 .insert("status".to_owned(), status_cmd_def.into())
f2401311 1374 .insert("key".to_owned(), key_mgmt_cli().into());
a914a774 1375
5a2df000
DM
1376 hyper::rt::run(futures::future::lazy(move || {
1377 run_cli_command(cmd_def.into());
1378 Ok(())
1379 }));
496a6784 1380
ff5d3707 1381}