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