]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-client.rs
src/bin/proxmox-backup-client.rs - list_groups: use format_and_print_result_full()
[proxmox-backup.git] / src / bin / proxmox-backup-client.rs
CommitLineData
ff5d3707 1use failure::*;
70235f72
CE
2use nix::unistd::{fork, ForkResult, pipe};
3use std::os::unix::io::RawFd;
27c9affb 4use chrono::{Local, DateTime, Utc, TimeZone};
e9c9409a 5use std::path::{Path, PathBuf};
2eeaacb9 6use std::collections::{HashSet, HashMap};
70235f72 7use std::ffi::OsStr;
bb19af73 8use std::io::{Write, Seek, SeekFrom};
2761d6a4
DM
9use std::os::unix::fs::OpenOptionsExt;
10
552c2259 11use proxmox::{sortable, identity};
feaa1ad3 12use proxmox::tools::fs::{file_get_contents, file_get_json, replace_file, CreateOptions, image_size};
501f4fa2 13use proxmox::sys::linux::tty;
a47a02ae 14use proxmox::api::{ApiHandler, ApiMethod, RpcEnvironment};
3d482025 15use proxmox::api::schema::*;
7eea56ca 16use proxmox::api::cli::*;
5830c205 17use proxmox::api::api;
ff5d3707 18
fe0e04c6 19use proxmox_backup::tools;
bbf9e7e9 20use proxmox_backup::api2::types::*;
151c6ce2 21use proxmox_backup::client::*;
247cdbce 22use proxmox_backup::backup::*;
7926a3a1 23use proxmox_backup::pxar::{ self, catalog::* };
86eda3eb 24
fe0e04c6
DM
25//use proxmox_backup::backup::image_index::*;
26//use proxmox_backup::config::datastore;
8968258b 27//use proxmox_backup::pxar::encoder::*;
728797d0 28//use proxmox_backup::backup::datastore::*;
23bb8780 29
f5f13ebc 30use serde_json::{json, Value};
1c0472e8 31//use hyper::Body;
2761d6a4 32use std::sync::{Arc, Mutex};
255f378a 33//use regex::Regex;
d0a03d40 34use xdg::BaseDirectories;
ae0be2dd 35
5a2df000 36use futures::*;
c4ff3dce 37use tokio::sync::mpsc;
ae0be2dd 38
a05c0c6f 39const ENV_VAR_PBS_FINGERPRINT: &str = "PBS_FINGERPRINT";
d1c65727 40const ENV_VAR_PBS_PASSWORD: &str = "PBS_PASSWORD";
a05c0c6f 41
9ea4bce4 42proxmox::const_regex! {
255f378a 43 BACKUPSPEC_REGEX = r"^([a-zA-Z0-9_-]+\.(?:pxar|img|conf|log)):(.+)$";
ae0be2dd 44}
33d64b81 45
255f378a
DM
46const REPO_URL_SCHEMA: Schema = StringSchema::new("Repository URL.")
47 .format(&BACKUP_REPO_URL)
48 .max_length(256)
49 .schema();
d0a03d40 50
a47a02ae
DM
51const BACKUP_SOURCE_SCHEMA: Schema = StringSchema::new(
52 "Backup source specification ([<label>:<path>]).")
53 .format(&ApiStringFormat::Pattern(&BACKUPSPEC_REGEX))
54 .schema();
55
56const KEYFILE_SCHEMA: Schema = StringSchema::new(
57 "Path to encryption key. All data will be encrypted using this key.")
58 .schema();
59
60const CHUNK_SIZE_SCHEMA: Schema = IntegerSchema::new(
61 "Chunk size in KB. Must be a power of 2.")
62 .minimum(64)
63 .maximum(4096)
64 .default(4096)
65 .schema();
66
2665cef7
DM
67fn get_default_repository() -> Option<String> {
68 std::env::var("PBS_REPOSITORY").ok()
69}
70
71fn extract_repository_from_value(
72 param: &Value,
73) -> Result<BackupRepository, Error> {
74
75 let repo_url = param["repository"]
76 .as_str()
77 .map(String::from)
78 .or_else(get_default_repository)
79 .ok_or_else(|| format_err!("unable to get (default) repository"))?;
80
81 let repo: BackupRepository = repo_url.parse()?;
82
83 Ok(repo)
84}
85
86fn extract_repository_from_map(
87 param: &HashMap<String, String>,
88) -> Option<BackupRepository> {
89
90 param.get("repository")
91 .map(String::from)
92 .or_else(get_default_repository)
93 .and_then(|repo_url| repo_url.parse::<BackupRepository>().ok())
94}
95
d0a03d40
DM
96fn record_repository(repo: &BackupRepository) {
97
98 let base = match BaseDirectories::with_prefix("proxmox-backup") {
99 Ok(v) => v,
100 _ => return,
101 };
102
103 // usually $HOME/.cache/proxmox-backup/repo-list
104 let path = match base.place_cache_file("repo-list") {
105 Ok(v) => v,
106 _ => return,
107 };
108
11377a47 109 let mut data = file_get_json(&path, None).unwrap_or_else(|_| json!({}));
d0a03d40
DM
110
111 let repo = repo.to_string();
112
113 data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 };
114
115 let mut map = serde_json::map::Map::new();
116
117 loop {
118 let mut max_used = 0;
119 let mut max_repo = None;
120 for (repo, count) in data.as_object().unwrap() {
121 if map.contains_key(repo) { continue; }
122 if let Some(count) = count.as_i64() {
123 if count > max_used {
124 max_used = count;
125 max_repo = Some(repo);
126 }
127 }
128 }
129 if let Some(repo) = max_repo {
130 map.insert(repo.to_owned(), json!(max_used));
131 } else {
132 break;
133 }
134 if map.len() > 10 { // store max. 10 repos
135 break;
136 }
137 }
138
139 let new_data = json!(map);
140
feaa1ad3 141 let _ = replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new());
d0a03d40
DM
142}
143
49811347 144fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
d0a03d40
DM
145
146 let mut result = vec![];
147
148 let base = match BaseDirectories::with_prefix("proxmox-backup") {
149 Ok(v) => v,
150 _ => return result,
151 };
152
153 // usually $HOME/.cache/proxmox-backup/repo-list
154 let path = match base.place_cache_file("repo-list") {
155 Ok(v) => v,
156 _ => return result,
157 };
158
11377a47 159 let data = file_get_json(&path, None).unwrap_or_else(|_| json!({}));
d0a03d40
DM
160
161 if let Some(map) = data.as_object() {
49811347 162 for (repo, _count) in map {
d0a03d40
DM
163 result.push(repo.to_owned());
164 }
165 }
166
167 result
168}
169
c81b2b7c
DM
170fn render_backup_file_list(files: &[String]) -> String {
171 let mut files: Vec<String> = files.iter()
172 .map(|v| strip_server_file_expenstion(&v))
173 .collect();
174
175 files.sort();
176
177 tools::join(&files, ' ')
178}
179
d59dbeca
DM
180fn connect(server: &str, userid: &str) -> Result<HttpClient, Error> {
181
a05c0c6f
DM
182 let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
183
d1c65727
DM
184 use std::env::VarError::*;
185 let password = match std::env::var(ENV_VAR_PBS_PASSWORD) {
186 Ok(p) => Some(p),
187 Err(NotUnicode(_)) => bail!(format!("{} contains bad characters", ENV_VAR_PBS_PASSWORD)),
188 Err(NotPresent) => None,
189 };
190
d59dbeca 191 let options = HttpClientOptions::new()
5030b7ce 192 .prefix(Some("proxmox-backup".to_string()))
d1c65727 193 .password(password)
d59dbeca 194 .interactive(true)
a05c0c6f 195 .fingerprint(fingerprint)
5a74756c 196 .fingerprint_cache(true)
d59dbeca
DM
197 .ticket_cache(true);
198
199 HttpClient::new(server, userid, options)
200}
201
d105176f
DM
202async fn view_task_result(
203 client: HttpClient,
204 result: Value,
205 output_format: &str,
206) -> Result<(), Error> {
207 let data = &result["data"];
208 if output_format == "text" {
209 if let Some(upid) = data.as_str() {
210 display_task_log(client, upid, true).await?;
211 }
212 } else {
213 format_and_print_result(&data, &output_format);
214 }
215
216 Ok(())
217}
218
42af4b8f
DM
219async fn api_datastore_list_snapshots(
220 client: &HttpClient,
221 store: &str,
222 group: Option<BackupGroup>,
f24fc116 223) -> Result<Value, Error> {
42af4b8f
DM
224
225 let path = format!("api2/json/admin/datastore/{}/snapshots", store);
226
227 let mut args = json!({});
228 if let Some(group) = group {
229 args["backup-type"] = group.backup_type().into();
230 args["backup-id"] = group.backup_id().into();
231 }
232
233 let mut result = client.get(&path, Some(args)).await?;
234
f24fc116 235 Ok(result["data"].take())
42af4b8f
DM
236}
237
27c9affb
DM
238async fn api_datastore_latest_snapshot(
239 client: &HttpClient,
240 store: &str,
241 group: BackupGroup,
242) -> Result<(String, String, DateTime<Utc>), Error> {
243
f24fc116
DM
244 let list = api_datastore_list_snapshots(client, store, Some(group.clone())).await?;
245 let mut list: Vec<SnapshotListItem> = serde_json::from_value(list)?;
27c9affb
DM
246
247 if list.is_empty() {
248 bail!("backup group {:?} does not contain any snapshots.", group.group_path());
249 }
250
251 list.sort_unstable_by(|a, b| b.backup_time.cmp(&a.backup_time));
252
253 let backup_time = Utc.timestamp(list[0].backup_time, 0);
254
255 Ok((group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time))
256}
257
258
e9722f8b 259async fn backup_directory<P: AsRef<Path>>(
cf9271e2 260 client: &BackupWriter,
17d6979a 261 dir_path: P,
247cdbce 262 archive_name: &str,
36898ffc 263 chunk_size: Option<usize>,
2eeaacb9 264 device_set: Option<HashSet<u64>>,
219ef0e6 265 verbose: bool,
5b72c9b4 266 skip_lost_and_found: bool,
f98ac774 267 crypt_config: Option<Arc<CryptConfig>>,
f1d99e3f 268 catalog: Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>,
6fc053ed 269 entries_max: usize,
2c3891d1 270) -> Result<BackupStats, Error> {
33d64b81 271
6fc053ed
CE
272 let pxar_stream = PxarBackupStream::open(
273 dir_path.as_ref(),
274 device_set,
275 verbose,
276 skip_lost_and_found,
277 catalog,
278 entries_max,
279 )?;
e9722f8b 280 let mut chunk_stream = ChunkStream::new(pxar_stream, chunk_size);
ff3d3100 281
e9722f8b 282 let (mut tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks
5e7a09be 283
c4ff3dce 284 let stream = rx
e9722f8b 285 .map_err(Error::from);
17d6979a 286
c4ff3dce 287 // spawn chunker inside a separate task so that it can run parallel
e9722f8b 288 tokio::spawn(async move {
db0cb9ce
WB
289 while let Some(v) = chunk_stream.next().await {
290 let _ = tx.send(v).await;
291 }
e9722f8b 292 });
17d6979a 293
e9722f8b
WB
294 let stats = client
295 .upload_stream(archive_name, stream, "dynamic", None, crypt_config)
296 .await?;
bcd879cf 297
2c3891d1 298 Ok(stats)
bcd879cf
DM
299}
300
e9722f8b 301async fn backup_image<P: AsRef<Path>>(
cf9271e2 302 client: &BackupWriter,
6af905c1
DM
303 image_path: P,
304 archive_name: &str,
305 image_size: u64,
36898ffc 306 chunk_size: Option<usize>,
1c0472e8 307 _verbose: bool,
f98ac774 308 crypt_config: Option<Arc<CryptConfig>>,
2c3891d1 309) -> Result<BackupStats, Error> {
6af905c1 310
6af905c1
DM
311 let path = image_path.as_ref().to_owned();
312
e9722f8b 313 let file = tokio::fs::File::open(path).await?;
6af905c1 314
db0cb9ce 315 let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new())
6af905c1
DM
316 .map_err(Error::from);
317
36898ffc 318 let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024));
6af905c1 319
e9722f8b
WB
320 let stats = client
321 .upload_stream(archive_name, stream, "fixed", Some(image_size), crypt_config)
322 .await?;
6af905c1 323
2c3891d1 324 Ok(stats)
6af905c1
DM
325}
326
52c171e4
DM
327fn strip_server_file_expenstion(name: &str) -> String {
328
11377a47
DM
329 if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") {
330 name[..name.len()-5].to_owned()
52c171e4 331 } else {
11377a47 332 name.to_owned() // should not happen
8e39232a 333 }
8e39232a
DM
334}
335
a47a02ae
DM
336#[api(
337 input: {
338 properties: {
339 repository: {
340 schema: REPO_URL_SCHEMA,
341 optional: true,
342 },
343 "output-format": {
344 schema: OUTPUT_FORMAT,
345 optional: true,
346 },
347 }
348 }
349)]
350/// List backup groups.
351async fn list_backup_groups(param: Value) -> Result<Value, Error> {
812c6f87 352
c81b2b7c
DM
353 let output_format = get_output_format(&param);
354
2665cef7 355 let repo = extract_repository_from_value(&param)?;
812c6f87 356
d59dbeca 357 let client = connect(repo.host(), repo.user())?;
812c6f87 358
d0a03d40 359 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
812c6f87 360
8a8a4703 361 let mut result = client.get(&path, None).await?;
812c6f87 362
d0a03d40
DM
363 record_repository(&repo);
364
c81b2b7c
DM
365 let render_group_path = |_v: &Value, record: &Value| -> Result<String, Error> {
366 let item: GroupListItem = serde_json::from_value(record.to_owned())?;
367 let group = BackupGroup::new(item.backup_type, item.backup_id);
368 Ok(group.group_path().to_str().unwrap().to_owned())
369 };
812c6f87 370
c81b2b7c
DM
371 let render_backup_timestamp = |v: &Value, _record: &Value| -> Result<String, Error> {
372 let epoch = v.as_i64().unwrap();
fa5d6977 373 let last_backup = Utc.timestamp(epoch, 0);
c81b2b7c
DM
374 Ok(BackupDir::backup_time_to_string(last_backup))
375 };
812c6f87 376
c81b2b7c
DM
377 let render_files = |_v: &Value, record: &Value| -> Result<String, Error> {
378 let item: GroupListItem = serde_json::from_value(record.to_owned())?;
379 Ok(render_backup_file_list(&item.files))
380 };
812c6f87 381
c81b2b7c
DM
382 let options = default_table_format_options()
383 .sortby("backup-type", false)
384 .sortby("backup-id", false)
385 .column(ColumnConfig::new("backup-id").renderer(render_group_path).header("group"))
386 .column(ColumnConfig::new("last-backup").renderer(render_backup_timestamp))
387 .column(ColumnConfig::new("backup-count"))
388 .column(ColumnConfig::new("files").renderer(render_files));
ad20d198 389
c81b2b7c 390 let mut data: Value = result["data"].take();
ad20d198 391
c81b2b7c 392 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_GROUPS;
812c6f87 393
c81b2b7c 394 format_and_print_result_full(&mut data, info, &output_format, &options);
34a816cc 395
812c6f87
DM
396 Ok(Value::Null)
397}
398
a47a02ae
DM
399#[api(
400 input: {
401 properties: {
402 repository: {
403 schema: REPO_URL_SCHEMA,
404 optional: true,
405 },
406 group: {
407 type: String,
408 description: "Backup group.",
409 optional: true,
410 },
411 "output-format": {
412 schema: OUTPUT_FORMAT,
413 optional: true,
414 },
415 }
416 }
417)]
418/// List backup snapshots.
419async fn list_snapshots(param: Value) -> Result<Value, Error> {
184f17af 420
2665cef7 421 let repo = extract_repository_from_value(&param)?;
184f17af 422
c2043614 423 let output_format = get_output_format(&param);
34a816cc 424
d59dbeca 425 let client = connect(repo.host(), repo.user())?;
184f17af 426
42af4b8f
DM
427 let group = if let Some(path) = param["group"].as_str() {
428 Some(BackupGroup::parse(path)?)
429 } else {
430 None
431 };
184f17af 432
f24fc116 433 let mut data = api_datastore_list_snapshots(&client, repo.store(), group).await?;
184f17af 434
d0a03d40
DM
435 record_repository(&repo);
436
f24fc116
DM
437 let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> {
438 let item: SnapshotListItem = serde_json::from_value(record.to_owned())?;
af9d4afc 439 let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time);
f24fc116
DM
440 Ok(snapshot.relative_path().to_str().unwrap().to_owned())
441 };
184f17af 442
f24fc116
DM
443 let render_files = |_v: &Value, record: &Value| -> Result<String, Error> {
444 let item: SnapshotListItem = serde_json::from_value(record.to_owned())?;
c81b2b7c 445 Ok(render_backup_file_list(&item.files))
f24fc116
DM
446 };
447
c2043614 448 let options = default_table_format_options()
f24fc116
DM
449 .sortby("backup-type", false)
450 .sortby("backup-id", false)
451 .sortby("backup-time", false)
452 .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot"))
453 .column(ColumnConfig::new("size"))
454 .column(ColumnConfig::new("files").renderer(render_files))
455 ;
456
457 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOTS;
458
459 format_and_print_result_full(&mut data, info, &output_format, &options);
184f17af
DM
460
461 Ok(Value::Null)
462}
463
a47a02ae
DM
464#[api(
465 input: {
466 properties: {
467 repository: {
468 schema: REPO_URL_SCHEMA,
469 optional: true,
470 },
471 snapshot: {
472 type: String,
473 description: "Snapshot path.",
474 },
475 }
476 }
477)]
478/// Forget (remove) backup snapshots.
479async fn forget_snapshots(param: Value) -> Result<Value, Error> {
6f62c924 480
2665cef7 481 let repo = extract_repository_from_value(&param)?;
6f62c924
DM
482
483 let path = tools::required_string_param(&param, "snapshot")?;
484 let snapshot = BackupDir::parse(path)?;
485
d59dbeca 486 let mut client = connect(repo.host(), repo.user())?;
6f62c924 487
9e391bb7 488 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
6f62c924 489
8a8a4703
DM
490 let result = client.delete(&path, Some(json!({
491 "backup-type": snapshot.group().backup_type(),
492 "backup-id": snapshot.group().backup_id(),
493 "backup-time": snapshot.backup_time().timestamp(),
494 }))).await?;
6f62c924 495
d0a03d40
DM
496 record_repository(&repo);
497
6f62c924
DM
498 Ok(result)
499}
500
a47a02ae
DM
501#[api(
502 input: {
503 properties: {
504 repository: {
505 schema: REPO_URL_SCHEMA,
506 optional: true,
507 },
508 }
509 }
510)]
511/// Try to login. If successful, store ticket.
512async fn api_login(param: Value) -> Result<Value, Error> {
e240d8be
DM
513
514 let repo = extract_repository_from_value(&param)?;
515
d59dbeca 516 let client = connect(repo.host(), repo.user())?;
8a8a4703 517 client.login().await?;
e240d8be
DM
518
519 record_repository(&repo);
520
521 Ok(Value::Null)
522}
523
a47a02ae
DM
524#[api(
525 input: {
526 properties: {
527 repository: {
528 schema: REPO_URL_SCHEMA,
529 optional: true,
530 },
531 }
532 }
533)]
534/// Logout (delete stored ticket).
535fn api_logout(param: Value) -> Result<Value, Error> {
e240d8be
DM
536
537 let repo = extract_repository_from_value(&param)?;
538
5030b7ce 539 delete_ticket_info("proxmox-backup", repo.host(), repo.user())?;
e240d8be
DM
540
541 Ok(Value::Null)
542}
543
a47a02ae
DM
544#[api(
545 input: {
546 properties: {
547 repository: {
548 schema: REPO_URL_SCHEMA,
549 optional: true,
550 },
551 snapshot: {
552 type: String,
553 description: "Snapshot path.",
554 },
555 }
556 }
557)]
558/// Dump catalog.
559async fn dump_catalog(param: Value) -> Result<Value, Error> {
9049a8cf
DM
560
561 let repo = extract_repository_from_value(&param)?;
562
563 let path = tools::required_string_param(&param, "snapshot")?;
564 let snapshot = BackupDir::parse(path)?;
565
11377a47 566 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
9049a8cf
DM
567
568 let crypt_config = match keyfile {
569 None => None,
570 Some(path) => {
6d20a29d 571 let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
9025312a 572 Some(Arc::new(CryptConfig::new(key)?))
9049a8cf
DM
573 }
574 };
575
d59dbeca 576 let client = connect(repo.host(), repo.user())?;
9049a8cf 577
8a8a4703
DM
578 let client = BackupReader::start(
579 client,
580 crypt_config.clone(),
581 repo.store(),
582 &snapshot.group().backup_type(),
583 &snapshot.group().backup_id(),
584 snapshot.backup_time(),
585 true,
586 ).await?;
9049a8cf 587
8a8a4703 588 let manifest = client.download_manifest().await?;
d2267b11 589
8a8a4703 590 let index = client.download_dynamic_index(&manifest, CATALOG_NAME).await?;
bf6e3217 591
8a8a4703 592 let most_used = index.find_most_used_chunks(8);
bf6e3217 593
8a8a4703 594 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
bf6e3217 595
8a8a4703 596 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
9049a8cf 597
8a8a4703
DM
598 let mut catalogfile = std::fs::OpenOptions::new()
599 .write(true)
600 .read(true)
601 .custom_flags(libc::O_TMPFILE)
602 .open("/tmp")?;
d2267b11 603
8a8a4703
DM
604 std::io::copy(&mut reader, &mut catalogfile)
605 .map_err(|err| format_err!("unable to download catalog - {}", err))?;
a84ef4c2 606
8a8a4703 607 catalogfile.seek(SeekFrom::Start(0))?;
9049a8cf 608
8a8a4703 609 let mut catalog_reader = CatalogReader::new(catalogfile);
9049a8cf 610
8a8a4703 611 catalog_reader.dump()?;
e9722f8b 612
8a8a4703 613 record_repository(&repo);
9049a8cf
DM
614
615 Ok(Value::Null)
616}
617
a47a02ae
DM
618#[api(
619 input: {
620 properties: {
621 repository: {
622 schema: REPO_URL_SCHEMA,
623 optional: true,
624 },
625 snapshot: {
626 type: String,
627 description: "Snapshot path.",
628 },
629 "output-format": {
630 schema: OUTPUT_FORMAT,
631 optional: true,
632 },
633 }
634 }
635)]
636/// List snapshot files.
637async fn list_snapshot_files(param: Value) -> Result<Value, Error> {
52c171e4
DM
638
639 let repo = extract_repository_from_value(&param)?;
640
641 let path = tools::required_string_param(&param, "snapshot")?;
642 let snapshot = BackupDir::parse(path)?;
643
c2043614 644 let output_format = get_output_format(&param);
52c171e4 645
d59dbeca 646 let client = connect(repo.host(), repo.user())?;
52c171e4
DM
647
648 let path = format!("api2/json/admin/datastore/{}/files", repo.store());
649
8a8a4703
DM
650 let mut result = client.get(&path, Some(json!({
651 "backup-type": snapshot.group().backup_type(),
652 "backup-id": snapshot.group().backup_id(),
653 "backup-time": snapshot.backup_time().timestamp(),
654 }))).await?;
52c171e4
DM
655
656 record_repository(&repo);
657
ea5f547f 658 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOT_FILES;
52c171e4 659
ea5f547f
DM
660 let mut data: Value = result["data"].take();
661
c2043614 662 let options = default_table_format_options();
ea5f547f
DM
663
664 format_and_print_result_full(&mut data, info, &output_format, &options);
52c171e4
DM
665
666 Ok(Value::Null)
667}
668
a47a02ae 669#[api(
94913f35 670 input: {
a47a02ae
DM
671 properties: {
672 repository: {
673 schema: REPO_URL_SCHEMA,
674 optional: true,
675 },
94913f35
DM
676 "output-format": {
677 schema: OUTPUT_FORMAT,
678 optional: true,
679 },
680 },
681 },
a47a02ae
DM
682)]
683/// Start garbage collection for a specific repository.
684async fn start_garbage_collection(param: Value) -> Result<Value, Error> {
8cc0d6af 685
2665cef7 686 let repo = extract_repository_from_value(&param)?;
c2043614
DM
687
688 let output_format = get_output_format(&param);
8cc0d6af 689
d59dbeca 690 let mut client = connect(repo.host(), repo.user())?;
8cc0d6af 691
d0a03d40 692 let path = format!("api2/json/admin/datastore/{}/gc", repo.store());
8cc0d6af 693
8a8a4703 694 let result = client.post(&path, None).await?;
8cc0d6af 695
8a8a4703 696 record_repository(&repo);
d0a03d40 697
8a8a4703 698 view_task_result(client, result, &output_format).await?;
e5f7def4 699
e5f7def4 700 Ok(Value::Null)
8cc0d6af 701}
33d64b81 702
ae0be2dd
DM
703fn parse_backupspec(value: &str) -> Result<(&str, &str), Error> {
704
255f378a 705 if let Some(caps) = (BACKUPSPEC_REGEX.regex_obj)().captures(value) {
ae0be2dd
DM
706 return Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str()));
707 }
708 bail!("unable to parse directory specification '{}'", value);
709}
710
bf6e3217
DM
711fn spawn_catalog_upload(
712 client: Arc<BackupWriter>,
713 crypt_config: Option<Arc<CryptConfig>>,
714) -> Result<
715 (
f1d99e3f 716 Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>,
bf6e3217
DM
717 tokio::sync::oneshot::Receiver<Result<BackupStats, Error>>
718 ), Error>
719{
f1d99e3f
DM
720 let (catalog_tx, catalog_rx) = std::sync::mpsc::sync_channel(10); // allow to buffer 10 writes
721 let catalog_stream = crate::tools::StdChannelStream(catalog_rx);
bf6e3217
DM
722 let catalog_chunk_size = 512*1024;
723 let catalog_chunk_stream = ChunkStream::new(catalog_stream, Some(catalog_chunk_size));
724
f1d99e3f 725 let catalog = Arc::new(Mutex::new(CatalogWriter::new(crate::tools::StdChannelWriter::new(catalog_tx))?));
bf6e3217
DM
726
727 let (catalog_result_tx, catalog_result_rx) = tokio::sync::oneshot::channel();
728
729 tokio::spawn(async move {
730 let catalog_upload_result = client
731 .upload_stream(CATALOG_NAME, catalog_chunk_stream, "dynamic", None, crypt_config)
732 .await;
733
734 if let Err(ref err) = catalog_upload_result {
735 eprintln!("catalog upload error - {}", err);
736 client.cancel();
737 }
738
739 let _ = catalog_result_tx.send(catalog_upload_result);
740 });
741
742 Ok((catalog, catalog_result_rx))
743}
744
a47a02ae
DM
745#[api(
746 input: {
747 properties: {
748 backupspec: {
749 type: Array,
750 description: "List of backup source specifications ([<label.ext>:<path>] ...)",
751 items: {
752 schema: BACKUP_SOURCE_SCHEMA,
753 }
754 },
755 repository: {
756 schema: REPO_URL_SCHEMA,
757 optional: true,
758 },
759 "include-dev": {
760 description: "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.",
761 optional: true,
762 items: {
763 type: String,
764 description: "Path to file.",
765 }
766 },
767 keyfile: {
768 schema: KEYFILE_SCHEMA,
769 optional: true,
770 },
771 "skip-lost-and-found": {
772 type: Boolean,
773 description: "Skip lost+found directory.",
774 optional: true,
775 },
776 "backup-type": {
777 schema: BACKUP_TYPE_SCHEMA,
778 optional: true,
779 },
780 "backup-id": {
781 schema: BACKUP_ID_SCHEMA,
782 optional: true,
783 },
784 "backup-time": {
785 schema: BACKUP_TIME_SCHEMA,
786 optional: true,
787 },
788 "chunk-size": {
789 schema: CHUNK_SIZE_SCHEMA,
790 optional: true,
791 },
6fc053ed
CE
792 "entries-max": {
793 type: Integer,
794 description: "Max number of entries to hold in memory.",
795 optional: true,
796 default: pxar::ENCODER_MAX_ENTRIES as isize,
797 },
e02c3d46
DM
798 "verbose": {
799 type: Boolean,
800 description: "Verbose output.",
801 optional: true,
802 },
a47a02ae
DM
803 }
804 }
805)]
806/// Create (host) backup.
807async fn create_backup(
6049b71f
DM
808 param: Value,
809 _info: &ApiMethod,
dd5495d6 810 _rpcenv: &mut dyn RpcEnvironment,
6049b71f 811) -> Result<Value, Error> {
ff5d3707 812
2665cef7 813 let repo = extract_repository_from_value(&param)?;
ae0be2dd
DM
814
815 let backupspec_list = tools::required_array_param(&param, "backupspec")?;
a914a774 816
eed6db39
DM
817 let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false);
818
5b72c9b4
DM
819 let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false);
820
219ef0e6
DM
821 let verbose = param["verbose"].as_bool().unwrap_or(false);
822
ca5d0b61
DM
823 let backup_time_opt = param["backup-time"].as_i64();
824
36898ffc 825 let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize);
2d9d143a 826
247cdbce
DM
827 if let Some(size) = chunk_size_opt {
828 verify_chunk_size(size)?;
2d9d143a
DM
829 }
830
11377a47 831 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
6d0983db 832
f69adc81 833 let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename());
fba30411 834
bbf9e7e9 835 let backup_type = param["backup-type"].as_str().unwrap_or("host");
ca5d0b61 836
2eeaacb9
DM
837 let include_dev = param["include-dev"].as_array();
838
6fc053ed
CE
839 let entries_max = param["entries-max"].as_u64().unwrap_or(pxar::ENCODER_MAX_ENTRIES as u64);
840
2eeaacb9
DM
841 let mut devices = if all_file_systems { None } else { Some(HashSet::new()) };
842
843 if let Some(include_dev) = include_dev {
844 if all_file_systems {
845 bail!("option 'all-file-systems' conflicts with option 'include-dev'");
846 }
847
848 let mut set = HashSet::new();
849 for path in include_dev {
850 let path = path.as_str().unwrap();
851 let stat = nix::sys::stat::stat(path)
852 .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?;
853 set.insert(stat.st_dev);
854 }
855 devices = Some(set);
856 }
857
ae0be2dd 858 let mut upload_list = vec![];
a914a774 859
79679c2d 860 enum BackupType { PXAR, IMAGE, CONFIG, LOGFILE };
6af905c1 861
bf6e3217
DM
862 let mut upload_catalog = false;
863
ae0be2dd
DM
864 for backupspec in backupspec_list {
865 let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?;
bcd879cf 866
eb1804c5
DM
867 use std::os::unix::fs::FileTypeExt;
868
3fa71727
CE
869 let metadata = std::fs::metadata(filename)
870 .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?;
eb1804c5 871 let file_type = metadata.file_type();
23bb8780 872
4af0ee05 873 let extension = target.rsplit('.').next()
11377a47 874 .ok_or_else(|| format_err!("missing target file extenion '{}'", target))?;
bcd879cf 875
ec8a9bb9
DM
876 match extension {
877 "pxar" => {
878 if !file_type.is_dir() {
879 bail!("got unexpected file type (expected directory)");
880 }
4af0ee05 881 upload_list.push((BackupType::PXAR, filename.to_owned(), format!("{}.didx", target), 0));
bf6e3217 882 upload_catalog = true;
ec8a9bb9
DM
883 }
884 "img" => {
eb1804c5 885
ec8a9bb9
DM
886 if !(file_type.is_file() || file_type.is_block_device()) {
887 bail!("got unexpected file type (expected file or block device)");
888 }
eb1804c5 889
e18a6c9e 890 let size = image_size(&PathBuf::from(filename))?;
23bb8780 891
ec8a9bb9 892 if size == 0 { bail!("got zero-sized file '{}'", filename); }
ae0be2dd 893
4af0ee05 894 upload_list.push((BackupType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size));
ec8a9bb9
DM
895 }
896 "conf" => {
897 if !file_type.is_file() {
898 bail!("got unexpected file type (expected regular file)");
899 }
4af0ee05 900 upload_list.push((BackupType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len()));
ec8a9bb9 901 }
79679c2d
DM
902 "log" => {
903 if !file_type.is_file() {
904 bail!("got unexpected file type (expected regular file)");
905 }
4af0ee05 906 upload_list.push((BackupType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len()));
79679c2d 907 }
ec8a9bb9
DM
908 _ => {
909 bail!("got unknown archive extension '{}'", extension);
910 }
ae0be2dd
DM
911 }
912 }
913
11377a47 914 let backup_time = Utc.timestamp(backup_time_opt.unwrap_or_else(|| Utc::now().timestamp()), 0);
ae0be2dd 915
d59dbeca 916 let client = connect(repo.host(), repo.user())?;
d0a03d40
DM
917 record_repository(&repo);
918
ca5d0b61
DM
919 println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time));
920
f69adc81 921 println!("Client name: {}", proxmox::tools::nodename());
ca5d0b61
DM
922
923 let start_time = Local::now();
924
7a6cfbd9 925 println!("Starting protocol: {}", start_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
51144821 926
bb823140
DM
927 let (crypt_config, rsa_encrypted_key) = match keyfile {
928 None => (None, None),
6d0983db 929 Some(path) => {
6d20a29d 930 let (key, created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
bb823140
DM
931
932 let crypt_config = CryptConfig::new(key)?;
933
934 let path = master_pubkey_path()?;
935 if path.exists() {
e18a6c9e 936 let pem_data = file_get_contents(&path)?;
bb823140
DM
937 let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
938 let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?;
939 (Some(Arc::new(crypt_config)), Some(enc_key))
940 } else {
941 (Some(Arc::new(crypt_config)), None)
942 }
6d0983db
DM
943 }
944 };
f98ac774 945
8a8a4703
DM
946 let client = BackupWriter::start(
947 client,
948 repo.store(),
949 backup_type,
950 &backup_id,
951 backup_time,
952 verbose,
953 ).await?;
954
955 let snapshot = BackupDir::new(backup_type, backup_id, backup_time.timestamp());
956 let mut manifest = BackupManifest::new(snapshot);
957
958 let (catalog, catalog_result_rx) = spawn_catalog_upload(client.clone(), crypt_config.clone())?;
959
960 for (backup_type, filename, target, size) in upload_list {
961 match backup_type {
962 BackupType::CONFIG => {
963 println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target);
964 let stats = client
965 .upload_blob_from_file(&filename, &target, crypt_config.clone(), true)
966 .await?;
1e8da0a7 967 manifest.add_file(target, stats.size, stats.csum)?;
8a8a4703
DM
968 }
969 BackupType::LOGFILE => { // fixme: remove - not needed anymore ?
970 println!("Upload log file '{}' to '{:?}' as {}", filename, repo, target);
971 let stats = client
972 .upload_blob_from_file(&filename, &target, crypt_config.clone(), true)
973 .await?;
1e8da0a7 974 manifest.add_file(target, stats.size, stats.csum)?;
8a8a4703
DM
975 }
976 BackupType::PXAR => {
977 println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target);
978 catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?;
979 let stats = backup_directory(
980 &client,
981 &filename,
982 &target,
983 chunk_size_opt,
984 devices.clone(),
985 verbose,
986 skip_lost_and_found,
987 crypt_config.clone(),
988 catalog.clone(),
6fc053ed 989 entries_max as usize,
8a8a4703 990 ).await?;
1e8da0a7 991 manifest.add_file(target, stats.size, stats.csum)?;
8a8a4703
DM
992 catalog.lock().unwrap().end_directory()?;
993 }
994 BackupType::IMAGE => {
995 println!("Upload image '{}' to '{:?}' as {}", filename, repo, target);
996 let stats = backup_image(
997 &client,
998 &filename,
999 &target,
1000 size,
1001 chunk_size_opt,
1002 verbose,
1003 crypt_config.clone(),
1004 ).await?;
1e8da0a7 1005 manifest.add_file(target, stats.size, stats.csum)?;
6af905c1
DM
1006 }
1007 }
8a8a4703 1008 }
4818c8b6 1009
8a8a4703
DM
1010 // finalize and upload catalog
1011 if upload_catalog {
1012 let mutex = Arc::try_unwrap(catalog)
1013 .map_err(|_| format_err!("unable to get catalog (still used)"))?;
1014 let mut catalog = mutex.into_inner().unwrap();
bf6e3217 1015
8a8a4703 1016 catalog.finish()?;
2761d6a4 1017
8a8a4703 1018 drop(catalog); // close upload stream
2761d6a4 1019
8a8a4703 1020 let stats = catalog_result_rx.await??;
9d135fe6 1021
1e8da0a7 1022 manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum)?;
8a8a4703 1023 }
2761d6a4 1024
8a8a4703
DM
1025 if let Some(rsa_encrypted_key) = rsa_encrypted_key {
1026 let target = "rsa-encrypted.key";
1027 println!("Upload RSA encoded key to '{:?}' as {}", repo, target);
1028 let stats = client
1029 .upload_blob_from_data(rsa_encrypted_key, target, None, false, false)
1030 .await?;
1e8da0a7 1031 manifest.add_file(format!("{}.blob", target), stats.size, stats.csum)?;
8a8a4703
DM
1032
1033 // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t
1034 /*
1035 let mut buffer2 = vec![0u8; rsa.size() as usize];
1036 let pem_data = file_get_contents("master-private.pem")?;
1037 let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?;
1038 let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?;
1039 println!("TEST {} {:?}", len, buffer2);
1040 */
1041 }
9f46c7de 1042
8a8a4703
DM
1043 // create manifest (index.json)
1044 let manifest = manifest.into_json();
2c3891d1 1045
8a8a4703
DM
1046 println!("Upload index.json to '{:?}'", repo);
1047 let manifest = serde_json::to_string_pretty(&manifest)?.into();
1048 client
1049 .upload_blob_from_data(manifest, MANIFEST_BLOB_NAME, crypt_config.clone(), true, true)
1050 .await?;
2c3891d1 1051
8a8a4703 1052 client.finish().await?;
c4ff3dce 1053
8a8a4703
DM
1054 let end_time = Local::now();
1055 let elapsed = end_time.signed_duration_since(start_time);
1056 println!("Duration: {}", elapsed);
3ec3ec3f 1057
8a8a4703 1058 println!("End Time: {}", end_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
3d5c11e5 1059
8a8a4703 1060 Ok(Value::Null)
f98ea63d
DM
1061}
1062
d0a03d40 1063fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
f98ea63d
DM
1064
1065 let mut result = vec![];
1066
1067 let data: Vec<&str> = arg.splitn(2, ':').collect();
1068
bff11030 1069 if data.len() != 2 {
8968258b
DM
1070 result.push(String::from("root.pxar:/"));
1071 result.push(String::from("etc.pxar:/etc"));
bff11030
DM
1072 return result;
1073 }
f98ea63d 1074
496a6784 1075 let files = tools::complete_file_name(data[1], param);
f98ea63d
DM
1076
1077 for file in files {
1078 result.push(format!("{}:{}", data[0], file));
1079 }
1080
1081 result
ff5d3707 1082}
1083
88892ea8
DM
1084fn dump_image<W: Write>(
1085 client: Arc<BackupReader>,
1086 crypt_config: Option<Arc<CryptConfig>>,
1087 index: FixedIndexReader,
1088 mut writer: W,
fd04ca7a 1089 verbose: bool,
88892ea8
DM
1090) -> Result<(), Error> {
1091
1092 let most_used = index.find_most_used_chunks(8);
1093
1094 let mut chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1095
1096 // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy
1097 // and thus slows down reading. Instead, directly use RemoteChunkReader
fd04ca7a
DM
1098 let mut per = 0;
1099 let mut bytes = 0;
1100 let start_time = std::time::Instant::now();
1101
88892ea8
DM
1102 for pos in 0..index.index_count() {
1103 let digest = index.index_digest(pos).unwrap();
1104 let raw_data = chunk_reader.read_chunk(&digest)?;
1105 writer.write_all(&raw_data)?;
fd04ca7a
DM
1106 bytes += raw_data.len();
1107 if verbose {
1108 let next_per = ((pos+1)*100)/index.index_count();
1109 if per != next_per {
1110 eprintln!("progress {}% (read {} bytes, duration {} sec)",
1111 next_per, bytes, start_time.elapsed().as_secs());
1112 per = next_per;
1113 }
1114 }
88892ea8
DM
1115 }
1116
fd04ca7a
DM
1117 let end_time = std::time::Instant::now();
1118 let elapsed = end_time.duration_since(start_time);
1119 eprintln!("restore image complete (bytes={}, duration={:.2}s, speed={:.2}MB/s)",
1120 bytes,
1121 elapsed.as_secs_f64(),
1122 bytes as f64/(1024.0*1024.0*elapsed.as_secs_f64())
1123 );
1124
1125
88892ea8
DM
1126 Ok(())
1127}
1128
a47a02ae
DM
1129#[api(
1130 input: {
1131 properties: {
1132 repository: {
1133 schema: REPO_URL_SCHEMA,
1134 optional: true,
1135 },
1136 snapshot: {
1137 type: String,
1138 description: "Group/Snapshot path.",
1139 },
1140 "archive-name": {
1141 description: "Backup archive name.",
1142 type: String,
1143 },
1144 target: {
1145 type: String,
90c815bf 1146 description: r###"Target directory path. Use '-' to write to standard output.
8a8a4703 1147
5eee6d89 1148We do not extraxt '.pxar' archives when writing to standard output.
8a8a4703 1149
a47a02ae
DM
1150"###
1151 },
1152 "allow-existing-dirs": {
1153 type: Boolean,
1154 description: "Do not fail if directories already exists.",
1155 optional: true,
1156 },
1157 keyfile: {
1158 schema: KEYFILE_SCHEMA,
1159 optional: true,
1160 },
1161 }
1162 }
1163)]
1164/// Restore backup repository.
1165async fn restore(param: Value) -> Result<Value, Error> {
2665cef7 1166 let repo = extract_repository_from_value(&param)?;
9f912493 1167
86eda3eb
DM
1168 let verbose = param["verbose"].as_bool().unwrap_or(false);
1169
46d5aa0a
DM
1170 let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false);
1171
d5c34d98
DM
1172 let archive_name = tools::required_string_param(&param, "archive-name")?;
1173
d59dbeca 1174 let client = connect(repo.host(), repo.user())?;
d0a03d40 1175
d0a03d40 1176 record_repository(&repo);
d5c34d98 1177
9f912493 1178 let path = tools::required_string_param(&param, "snapshot")?;
9f912493 1179
86eda3eb 1180 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
d5c34d98 1181 let group = BackupGroup::parse(path)?;
27c9affb 1182 api_datastore_latest_snapshot(&client, repo.store(), group).await?
d5c34d98
DM
1183 } else {
1184 let snapshot = BackupDir::parse(path)?;
86eda3eb
DM
1185 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
1186 };
9f912493 1187
d5c34d98 1188 let target = tools::required_string_param(&param, "target")?;
bf125261 1189 let target = if target == "-" { None } else { Some(target) };
2ae7d196 1190
11377a47 1191 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
2ae7d196 1192
86eda3eb
DM
1193 let crypt_config = match keyfile {
1194 None => None,
1195 Some(path) => {
6d20a29d 1196 let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
86eda3eb
DM
1197 Some(Arc::new(CryptConfig::new(key)?))
1198 }
1199 };
d5c34d98 1200
afb4cd28
DM
1201 let server_archive_name = if archive_name.ends_with(".pxar") {
1202 format!("{}.didx", archive_name)
1203 } else if archive_name.ends_with(".img") {
1204 format!("{}.fidx", archive_name)
1205 } else {
f8100e96 1206 format!("{}.blob", archive_name)
afb4cd28 1207 };
9f912493 1208
296c50ba
DM
1209 let client = BackupReader::start(
1210 client,
1211 crypt_config.clone(),
1212 repo.store(),
1213 &backup_type,
1214 &backup_id,
1215 backup_time,
1216 true,
1217 ).await?;
86eda3eb 1218
f06b820a 1219 let manifest = client.download_manifest().await?;
02fcf372 1220
ad6e5a6f 1221 if server_archive_name == MANIFEST_BLOB_NAME {
f06b820a 1222 let backup_index_data = manifest.into_json().to_string();
02fcf372 1223 if let Some(target) = target {
feaa1ad3 1224 replace_file(target, backup_index_data.as_bytes(), CreateOptions::new())?;
02fcf372
DM
1225 } else {
1226 let stdout = std::io::stdout();
1227 let mut writer = stdout.lock();
296c50ba 1228 writer.write_all(backup_index_data.as_bytes())
02fcf372
DM
1229 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1230 }
1231
1232 } else if server_archive_name.ends_with(".blob") {
d2267b11 1233
bb19af73 1234 let mut reader = client.download_blob(&manifest, &server_archive_name).await?;
f8100e96 1235
bf125261 1236 if let Some(target) = target {
0d986280
DM
1237 let mut writer = std::fs::OpenOptions::new()
1238 .write(true)
1239 .create(true)
1240 .create_new(true)
1241 .open(target)
1242 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
1243 std::io::copy(&mut reader, &mut writer)?;
bf125261
DM
1244 } else {
1245 let stdout = std::io::stdout();
1246 let mut writer = stdout.lock();
0d986280 1247 std::io::copy(&mut reader, &mut writer)
bf125261
DM
1248 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1249 }
f8100e96
DM
1250
1251 } else if server_archive_name.ends_with(".didx") {
86eda3eb 1252
c3d84a22 1253 let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
df65bd3d 1254
f4bf7dfc
DM
1255 let most_used = index.find_most_used_chunks(8);
1256
1257 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1258
afb4cd28 1259 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
86eda3eb 1260
bf125261 1261 if let Some(target) = target {
86eda3eb 1262
47651f95 1263 let feature_flags = pxar::flags::DEFAULT;
f701d033
DM
1264 let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags);
1265 decoder.set_callback(move |path| {
bf125261 1266 if verbose {
fd04ca7a 1267 eprintln!("{:?}", path);
bf125261
DM
1268 }
1269 Ok(())
1270 });
6a879109
CE
1271 decoder.set_allow_existing_dirs(allow_existing_dirs);
1272
fa7e957c 1273 decoder.restore(Path::new(target), &Vec::new())?;
bf125261 1274 } else {
88892ea8
DM
1275 let mut writer = std::fs::OpenOptions::new()
1276 .write(true)
1277 .open("/dev/stdout")
1278 .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?;
afb4cd28 1279
bf125261
DM
1280 std::io::copy(&mut reader, &mut writer)
1281 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1282 }
afb4cd28 1283 } else if server_archive_name.ends_with(".fidx") {
afb4cd28 1284
72050500 1285 let index = client.download_fixed_index(&manifest, &server_archive_name).await?;
df65bd3d 1286
88892ea8
DM
1287 let mut writer = if let Some(target) = target {
1288 std::fs::OpenOptions::new()
bf125261
DM
1289 .write(true)
1290 .create(true)
1291 .create_new(true)
1292 .open(target)
88892ea8 1293 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?
bf125261 1294 } else {
88892ea8
DM
1295 std::fs::OpenOptions::new()
1296 .write(true)
1297 .open("/dev/stdout")
1298 .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?
1299 };
afb4cd28 1300
fd04ca7a 1301 dump_image(client.clone(), crypt_config.clone(), index, &mut writer, verbose)?;
88892ea8
DM
1302
1303 } else {
f8100e96 1304 bail!("unknown archive file extension (expected .pxar of .img)");
3031e44c 1305 }
fef44d4f
DM
1306
1307 Ok(Value::Null)
45db6f89
DM
1308}
1309
a47a02ae
DM
1310#[api(
1311 input: {
1312 properties: {
1313 repository: {
1314 schema: REPO_URL_SCHEMA,
1315 optional: true,
1316 },
1317 snapshot: {
1318 type: String,
1319 description: "Group/Snapshot path.",
1320 },
1321 logfile: {
1322 type: String,
1323 description: "The path to the log file you want to upload.",
1324 },
1325 keyfile: {
1326 schema: KEYFILE_SCHEMA,
1327 optional: true,
1328 },
1329 }
1330 }
1331)]
1332/// Upload backup log file.
1333async fn upload_log(param: Value) -> Result<Value, Error> {
ec34f7eb
DM
1334
1335 let logfile = tools::required_string_param(&param, "logfile")?;
1336 let repo = extract_repository_from_value(&param)?;
1337
1338 let snapshot = tools::required_string_param(&param, "snapshot")?;
1339 let snapshot = BackupDir::parse(snapshot)?;
1340
d59dbeca 1341 let mut client = connect(repo.host(), repo.user())?;
ec34f7eb 1342
11377a47 1343 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
ec34f7eb
DM
1344
1345 let crypt_config = match keyfile {
1346 None => None,
1347 Some(path) => {
6d20a29d 1348 let (key, _created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
ec34f7eb 1349 let crypt_config = CryptConfig::new(key)?;
9025312a 1350 Some(Arc::new(crypt_config))
ec34f7eb
DM
1351 }
1352 };
1353
e18a6c9e 1354 let data = file_get_contents(logfile)?;
ec34f7eb 1355
7123ff7d 1356 let blob = DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?;
ec34f7eb
DM
1357
1358 let raw_data = blob.into_inner();
1359
1360 let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store());
1361
1362 let args = json!({
1363 "backup-type": snapshot.group().backup_type(),
1364 "backup-id": snapshot.group().backup_id(),
1365 "backup-time": snapshot.backup_time().timestamp(),
1366 });
1367
1368 let body = hyper::Body::from(raw_data);
1369
8a8a4703 1370 client.upload("application/octet-stream", body, &path, Some(args)).await
ec34f7eb
DM
1371}
1372
032d3ad8
DM
1373const API_METHOD_PRUNE: ApiMethod = ApiMethod::new(
1374 &ApiHandler::Async(&prune),
1375 &ObjectSchema::new(
1376 "Prune a backup repository.",
1377 &proxmox_backup::add_common_prune_prameters!([
1378 ("dry-run", true, &BooleanSchema::new(
1379 "Just show what prune would do, but do not delete anything.")
1380 .schema()),
1381 ("group", false, &StringSchema::new("Backup group.").schema()),
1382 ], [
1383 ("output-format", true, &OUTPUT_FORMAT),
1384 ("repository", true, &REPO_URL_SCHEMA),
1385 ])
1386 )
1387);
1388
1389fn prune<'a>(
1390 param: Value,
1391 _info: &ApiMethod,
1392 _rpcenv: &'a mut dyn RpcEnvironment,
1393) -> proxmox::api::ApiFuture<'a> {
1394 async move {
1395 prune_async(param).await
1396 }.boxed()
1397}
83b7db02 1398
032d3ad8 1399async fn prune_async(mut param: Value) -> Result<Value, Error> {
2665cef7 1400 let repo = extract_repository_from_value(&param)?;
83b7db02 1401
d59dbeca 1402 let mut client = connect(repo.host(), repo.user())?;
83b7db02 1403
d0a03d40 1404 let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
83b7db02 1405
9fdc3ef4
DM
1406 let group = tools::required_string_param(&param, "group")?;
1407 let group = BackupGroup::parse(group)?;
c2043614
DM
1408
1409 let output_format = get_output_format(&param);
9fdc3ef4 1410
ea7a7ef2
DM
1411 param.as_object_mut().unwrap().remove("repository");
1412 param.as_object_mut().unwrap().remove("group");
163e9bbe 1413 param.as_object_mut().unwrap().remove("output-format");
ea7a7ef2
DM
1414
1415 param["backup-type"] = group.backup_type().into();
1416 param["backup-id"] = group.backup_id().into();
83b7db02 1417
87c42375 1418 let result = client.post(&path, Some(param)).await?;
74fa81b8 1419
87c42375 1420 record_repository(&repo);
3b03abfe 1421
87c42375 1422 view_task_result(client, result, &output_format).await?;
d0a03d40 1423
43a406fd 1424 Ok(Value::Null)
83b7db02
DM
1425}
1426
a47a02ae
DM
1427#[api(
1428 input: {
1429 properties: {
1430 repository: {
1431 schema: REPO_URL_SCHEMA,
1432 optional: true,
1433 },
1434 "output-format": {
1435 schema: OUTPUT_FORMAT,
1436 optional: true,
1437 },
1438 }
1439 }
1440)]
1441/// Get repository status.
1442async fn status(param: Value) -> Result<Value, Error> {
34a816cc
DM
1443
1444 let repo = extract_repository_from_value(&param)?;
1445
c2043614 1446 let output_format = get_output_format(&param);
34a816cc 1447
d59dbeca 1448 let client = connect(repo.host(), repo.user())?;
34a816cc
DM
1449
1450 let path = format!("api2/json/admin/datastore/{}/status", repo.store());
1451
1dc117bb 1452 let mut result = client.get(&path, None).await?;
390c5bdd 1453 let mut data = result["data"].take();
34a816cc
DM
1454
1455 record_repository(&repo);
1456
390c5bdd
DM
1457 let render_total_percentage = |v: &Value, record: &Value| -> Result<String, Error> {
1458 let v = v.as_u64().unwrap();
1459 let total = record["total"].as_u64().unwrap();
1460 let roundup = total/200;
1461 let per = ((v+roundup)*100)/total;
e23f5863
DM
1462 let info = format!(" ({} %)", per);
1463 Ok(format!("{} {:>8}", v, info))
390c5bdd 1464 };
1dc117bb 1465
c2043614 1466 let options = default_table_format_options()
be2425ff 1467 .noheader(true)
e23f5863 1468 .column(ColumnConfig::new("total").renderer(render_total_percentage))
390c5bdd
DM
1469 .column(ColumnConfig::new("used").renderer(render_total_percentage))
1470 .column(ColumnConfig::new("avail").renderer(render_total_percentage));
34a816cc 1471
ea5f547f 1472 let schema = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_STATUS;
390c5bdd
DM
1473
1474 format_and_print_result_full(&mut data, schema, &output_format, &options);
34a816cc
DM
1475
1476 Ok(Value::Null)
1477}
1478
5a2df000 1479// like get, but simply ignore errors and return Null instead
e9722f8b 1480async fn try_get(repo: &BackupRepository, url: &str) -> Value {
024f11bb 1481
a05c0c6f 1482 let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
d1c65727 1483 let password = std::env::var(ENV_VAR_PBS_PASSWORD).ok();
a05c0c6f 1484
d59dbeca 1485 let options = HttpClientOptions::new()
5030b7ce 1486 .prefix(Some("proxmox-backup".to_string()))
d1c65727 1487 .password(password)
d59dbeca 1488 .interactive(false)
a05c0c6f 1489 .fingerprint(fingerprint)
5a74756c 1490 .fingerprint_cache(true)
d59dbeca
DM
1491 .ticket_cache(true);
1492
1493 let client = match HttpClient::new(repo.host(), repo.user(), options) {
45cdce06
DM
1494 Ok(v) => v,
1495 _ => return Value::Null,
1496 };
b2388518 1497
e9722f8b 1498 let mut resp = match client.get(url, None).await {
b2388518
DM
1499 Ok(v) => v,
1500 _ => return Value::Null,
1501 };
1502
1503 if let Some(map) = resp.as_object_mut() {
1504 if let Some(data) = map.remove("data") {
1505 return data;
1506 }
1507 }
1508 Value::Null
1509}
1510
b2388518 1511fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
3f06d6fb 1512 proxmox_backup::tools::runtime::main(async { complete_backup_group_do(param).await })
e9722f8b
WB
1513}
1514
1515async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> {
024f11bb 1516
b2388518
DM
1517 let mut result = vec![];
1518
2665cef7 1519 let repo = match extract_repository_from_map(param) {
b2388518 1520 Some(v) => v,
024f11bb
DM
1521 _ => return result,
1522 };
1523
b2388518
DM
1524 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
1525
e9722f8b 1526 let data = try_get(&repo, &path).await;
b2388518
DM
1527
1528 if let Some(list) = data.as_array() {
024f11bb 1529 for item in list {
98f0b972
DM
1530 if let (Some(backup_id), Some(backup_type)) =
1531 (item["backup-id"].as_str(), item["backup-type"].as_str())
1532 {
1533 result.push(format!("{}/{}", backup_type, backup_id));
024f11bb
DM
1534 }
1535 }
1536 }
1537
1538 result
1539}
1540
b2388518 1541fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
3f06d6fb 1542 proxmox_backup::tools::runtime::main(async { complete_group_or_snapshot_do(arg, param).await })
e9722f8b
WB
1543}
1544
1545async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
b2388518 1546
b2388518 1547 if arg.matches('/').count() < 2 {
e9722f8b 1548 let groups = complete_backup_group_do(param).await;
543a260f 1549 let mut result = vec![];
b2388518
DM
1550 for group in groups {
1551 result.push(group.to_string());
1552 result.push(format!("{}/", group));
1553 }
1554 return result;
1555 }
1556
e9722f8b 1557 complete_backup_snapshot_do(param).await
543a260f 1558}
b2388518 1559
3fb53e07 1560fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
3f06d6fb 1561 proxmox_backup::tools::runtime::main(async { complete_backup_snapshot_do(param).await })
e9722f8b
WB
1562}
1563
1564async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> {
543a260f
DM
1565
1566 let mut result = vec![];
1567
1568 let repo = match extract_repository_from_map(param) {
1569 Some(v) => v,
1570 _ => return result,
1571 };
1572
1573 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
b2388518 1574
e9722f8b 1575 let data = try_get(&repo, &path).await;
b2388518
DM
1576
1577 if let Some(list) = data.as_array() {
1578 for item in list {
1579 if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
1580 (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64())
1581 {
1582 let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
1583 result.push(snapshot.relative_path().to_str().unwrap().to_owned());
1584 }
1585 }
1586 }
1587
1588 result
1589}
1590
45db6f89 1591fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
3f06d6fb 1592 proxmox_backup::tools::runtime::main(async { complete_server_file_name_do(param).await })
e9722f8b
WB
1593}
1594
1595async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> {
08dc340a
DM
1596
1597 let mut result = vec![];
1598
2665cef7 1599 let repo = match extract_repository_from_map(param) {
08dc340a
DM
1600 Some(v) => v,
1601 _ => return result,
1602 };
1603
1604 let snapshot = match param.get("snapshot") {
1605 Some(path) => {
1606 match BackupDir::parse(path) {
1607 Ok(v) => v,
1608 _ => return result,
1609 }
1610 }
1611 _ => return result,
1612 };
1613
1614 let query = tools::json_object_to_query(json!({
1615 "backup-type": snapshot.group().backup_type(),
1616 "backup-id": snapshot.group().backup_id(),
1617 "backup-time": snapshot.backup_time().timestamp(),
1618 })).unwrap();
1619
1620 let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query);
1621
e9722f8b 1622 let data = try_get(&repo, &path).await;
08dc340a
DM
1623
1624 if let Some(list) = data.as_array() {
1625 for item in list {
c4f025eb 1626 if let Some(filename) = item["filename"].as_str() {
08dc340a
DM
1627 result.push(filename.to_owned());
1628 }
1629 }
1630 }
1631
45db6f89
DM
1632 result
1633}
1634
1635fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
52c171e4 1636 complete_server_file_name(arg, param)
e9722f8b
WB
1637 .iter()
1638 .map(|v| strip_server_file_expenstion(&v))
1639 .collect()
08dc340a
DM
1640}
1641
0ec9e1b0
DM
1642fn complete_pxar_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1643 complete_server_file_name(arg, param)
1644 .iter()
1645 .filter_map(|v| {
1646 let name = strip_server_file_expenstion(&v);
1647 if name.ends_with(".pxar") {
1648 Some(name)
1649 } else {
1650 None
1651 }
1652 })
1653 .collect()
1654}
1655
49811347
DM
1656fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
1657
1658 let mut result = vec![];
1659
1660 let mut size = 64;
1661 loop {
1662 result.push(size.to_string());
11377a47 1663 size *= 2;
49811347
DM
1664 if size > 4096 { break; }
1665 }
1666
1667 result
1668}
1669
826f309b 1670fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
ff5d3707 1671
f2401311
DM
1672 // fixme: implement other input methods
1673
1674 use std::env::VarError::*;
1675 match std::env::var("PBS_ENCRYPTION_PASSWORD") {
826f309b 1676 Ok(p) => return Ok(p.as_bytes().to_vec()),
f2401311
DM
1677 Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"),
1678 Err(NotPresent) => {
1679 // Try another method
1680 }
1681 }
1682
1683 // If we're on a TTY, query the user for a password
501f4fa2
DM
1684 if tty::stdin_isatty() {
1685 return Ok(tty::read_password("Encryption Key Password: ")?);
f2401311
DM
1686 }
1687
1688 bail!("no password input mechanism available");
1689}
1690
ac716234
DM
1691fn key_create(
1692 param: Value,
1693 _info: &ApiMethod,
1694 _rpcenv: &mut dyn RpcEnvironment,
1695) -> Result<Value, Error> {
1696
9b06db45
DM
1697 let path = tools::required_string_param(&param, "path")?;
1698 let path = PathBuf::from(path);
ac716234 1699
181f097a 1700 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
ac716234
DM
1701
1702 let key = proxmox::sys::linux::random_data(32)?;
1703
181f097a
DM
1704 if kdf == "scrypt" {
1705 // always read passphrase from tty
501f4fa2 1706 if !tty::stdin_isatty() {
181f097a
DM
1707 bail!("unable to read passphrase - no tty");
1708 }
ac716234 1709
501f4fa2 1710 let password = tty::read_and_verify_password("Encryption Key Password: ")?;
181f097a 1711
ab44acff 1712 let key_config = encrypt_key_with_passphrase(&key, &password)?;
37c5a175 1713
ab44acff 1714 store_key_config(&path, false, key_config)?;
181f097a
DM
1715
1716 Ok(Value::Null)
1717 } else if kdf == "none" {
1718 let created = Local.timestamp(Local::now().timestamp(), 0);
1719
1720 store_key_config(&path, false, KeyConfig {
1721 kdf: None,
1722 created,
ab44acff 1723 modified: created,
181f097a
DM
1724 data: key,
1725 })?;
1726
1727 Ok(Value::Null)
1728 } else {
1729 unreachable!();
1730 }
ac716234
DM
1731}
1732
9f46c7de
DM
1733fn master_pubkey_path() -> Result<PathBuf, Error> {
1734 let base = BaseDirectories::with_prefix("proxmox-backup")?;
1735
1736 // usually $HOME/.config/proxmox-backup/master-public.pem
1737 let path = base.place_config_file("master-public.pem")?;
1738
1739 Ok(path)
1740}
1741
3ea8bfc9
DM
1742fn key_import_master_pubkey(
1743 param: Value,
1744 _info: &ApiMethod,
1745 _rpcenv: &mut dyn RpcEnvironment,
1746) -> Result<Value, Error> {
1747
1748 let path = tools::required_string_param(&param, "path")?;
1749 let path = PathBuf::from(path);
1750
e18a6c9e 1751 let pem_data = file_get_contents(&path)?;
3ea8bfc9
DM
1752
1753 if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) {
1754 bail!("Unable to decode PEM data - {}", err);
1755 }
1756
9f46c7de 1757 let target_path = master_pubkey_path()?;
3ea8bfc9 1758
feaa1ad3 1759 replace_file(&target_path, &pem_data, CreateOptions::new())?;
3ea8bfc9
DM
1760
1761 println!("Imported public master key to {:?}", target_path);
1762
1763 Ok(Value::Null)
1764}
1765
37c5a175
DM
1766fn key_create_master_key(
1767 _param: Value,
1768 _info: &ApiMethod,
1769 _rpcenv: &mut dyn RpcEnvironment,
1770) -> Result<Value, Error> {
1771
1772 // we need a TTY to query the new password
501f4fa2 1773 if !tty::stdin_isatty() {
37c5a175
DM
1774 bail!("unable to create master key - no tty");
1775 }
1776
1777 let rsa = openssl::rsa::Rsa::generate(4096)?;
1778 let pkey = openssl::pkey::PKey::from_rsa(rsa)?;
1779
37c5a175 1780
501f4fa2 1781 let password = String::from_utf8(tty::read_and_verify_password("Master Key Password: ")?)?;
37c5a175
DM
1782
1783 let pub_key: Vec<u8> = pkey.public_key_to_pem()?;
1784 let filename_pub = "master-public.pem";
1785 println!("Writing public master key to {}", filename_pub);
feaa1ad3 1786 replace_file(filename_pub, pub_key.as_slice(), CreateOptions::new())?;
37c5a175
DM
1787
1788 let cipher = openssl::symm::Cipher::aes_256_cbc();
cbe01dc5 1789 let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, password.as_bytes())?;
37c5a175
DM
1790
1791 let filename_priv = "master-private.pem";
1792 println!("Writing private master key to {}", filename_priv);
feaa1ad3 1793 replace_file(filename_priv, priv_key.as_slice(), CreateOptions::new())?;
37c5a175
DM
1794
1795 Ok(Value::Null)
1796}
ac716234
DM
1797
1798fn key_change_passphrase(
1799 param: Value,
1800 _info: &ApiMethod,
1801 _rpcenv: &mut dyn RpcEnvironment,
1802) -> Result<Value, Error> {
1803
9b06db45
DM
1804 let path = tools::required_string_param(&param, "path")?;
1805 let path = PathBuf::from(path);
ac716234 1806
181f097a
DM
1807 let kdf = param["kdf"].as_str().unwrap_or("scrypt");
1808
ac716234 1809 // we need a TTY to query the new password
501f4fa2 1810 if !tty::stdin_isatty() {
ac716234
DM
1811 bail!("unable to change passphrase - no tty");
1812 }
1813
6d20a29d 1814 let (key, created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
ac716234 1815
181f097a 1816 if kdf == "scrypt" {
ac716234 1817
501f4fa2 1818 let password = tty::read_and_verify_password("New Password: ")?;
ac716234 1819
cbe01dc5 1820 let mut new_key_config = encrypt_key_with_passphrase(&key, &password)?;
ab44acff
DM
1821 new_key_config.created = created; // keep original value
1822
1823 store_key_config(&path, true, new_key_config)?;
ac716234 1824
181f097a
DM
1825 Ok(Value::Null)
1826 } else if kdf == "none" {
ab44acff 1827 let modified = Local.timestamp(Local::now().timestamp(), 0);
181f097a
DM
1828
1829 store_key_config(&path, true, KeyConfig {
1830 kdf: None,
ab44acff
DM
1831 created, // keep original value
1832 modified,
6d0983db 1833 data: key.to_vec(),
181f097a
DM
1834 })?;
1835
1836 Ok(Value::Null)
1837 } else {
1838 unreachable!();
1839 }
f2401311
DM
1840}
1841
1842fn key_mgmt_cli() -> CliCommandMap {
1843
255f378a 1844 const KDF_SCHEMA: Schema =
181f097a 1845 StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.")
255f378a
DM
1846 .format(&ApiStringFormat::Enum(&["scrypt", "none"]))
1847 .default("scrypt")
1848 .schema();
1849
552c2259 1850 #[sortable]
255f378a
DM
1851 const API_METHOD_KEY_CREATE: ApiMethod = ApiMethod::new(
1852 &ApiHandler::Sync(&key_create),
1853 &ObjectSchema::new(
1854 "Create a new encryption key.",
552c2259 1855 &sorted!([
255f378a
DM
1856 ("path", false, &StringSchema::new("File system path.").schema()),
1857 ("kdf", true, &KDF_SCHEMA),
552c2259 1858 ]),
255f378a 1859 )
181f097a 1860 );
7074a0b3 1861
255f378a 1862 let key_create_cmd_def = CliCommand::new(&API_METHOD_KEY_CREATE)
49fddd98 1863 .arg_param(&["path"])
9b06db45 1864 .completion_cb("path", tools::complete_file_name);
f2401311 1865
552c2259 1866 #[sortable]
255f378a
DM
1867 const API_METHOD_KEY_CHANGE_PASSPHRASE: ApiMethod = ApiMethod::new(
1868 &ApiHandler::Sync(&key_change_passphrase),
1869 &ObjectSchema::new(
1870 "Change the passphrase required to decrypt the key.",
552c2259 1871 &sorted!([
255f378a
DM
1872 ("path", false, &StringSchema::new("File system path.").schema()),
1873 ("kdf", true, &KDF_SCHEMA),
552c2259 1874 ]),
255f378a
DM
1875 )
1876 );
7074a0b3 1877
255f378a 1878 let key_change_passphrase_cmd_def = CliCommand::new(&API_METHOD_KEY_CHANGE_PASSPHRASE)
49fddd98 1879 .arg_param(&["path"])
9b06db45 1880 .completion_cb("path", tools::complete_file_name);
ac716234 1881
255f378a
DM
1882 const API_METHOD_KEY_CREATE_MASTER_KEY: ApiMethod = ApiMethod::new(
1883 &ApiHandler::Sync(&key_create_master_key),
1884 &ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.", &[])
1885 );
7074a0b3 1886
255f378a
DM
1887 let key_create_master_key_cmd_def = CliCommand::new(&API_METHOD_KEY_CREATE_MASTER_KEY);
1888
552c2259 1889 #[sortable]
255f378a
DM
1890 const API_METHOD_KEY_IMPORT_MASTER_PUBKEY: ApiMethod = ApiMethod::new(
1891 &ApiHandler::Sync(&key_import_master_pubkey),
1892 &ObjectSchema::new(
1893 "Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.",
552c2259 1894 &sorted!([ ("path", false, &StringSchema::new("File system path.").schema()) ]),
255f378a
DM
1895 )
1896 );
7074a0b3 1897
255f378a 1898 let key_import_master_pubkey_cmd_def = CliCommand::new(&API_METHOD_KEY_IMPORT_MASTER_PUBKEY)
49fddd98 1899 .arg_param(&["path"])
3ea8bfc9
DM
1900 .completion_cb("path", tools::complete_file_name);
1901
11377a47 1902 CliCommandMap::new()
48ef3c33
DM
1903 .insert("create", key_create_cmd_def)
1904 .insert("create-master-key", key_create_master_key_cmd_def)
1905 .insert("import-master-pubkey", key_import_master_pubkey_cmd_def)
1906 .insert("change-passphrase", key_change_passphrase_cmd_def)
f2401311
DM
1907}
1908
70235f72
CE
1909fn mount(
1910 param: Value,
1911 _info: &ApiMethod,
1912 _rpcenv: &mut dyn RpcEnvironment,
1913) -> Result<Value, Error> {
1914 let verbose = param["verbose"].as_bool().unwrap_or(false);
1915 if verbose {
1916 // This will stay in foreground with debug output enabled as None is
1917 // passed for the RawFd.
3f06d6fb 1918 return proxmox_backup::tools::runtime::main(mount_do(param, None));
70235f72
CE
1919 }
1920
1921 // Process should be deamonized.
1922 // Make sure to fork before the async runtime is instantiated to avoid troubles.
1923 let pipe = pipe()?;
1924 match fork() {
11377a47 1925 Ok(ForkResult::Parent { .. }) => {
70235f72
CE
1926 nix::unistd::close(pipe.1).unwrap();
1927 // Blocks the parent process until we are ready to go in the child
1928 let _res = nix::unistd::read(pipe.0, &mut [0]).unwrap();
1929 Ok(Value::Null)
1930 }
1931 Ok(ForkResult::Child) => {
1932 nix::unistd::close(pipe.0).unwrap();
1933 nix::unistd::setsid().unwrap();
3f06d6fb 1934 proxmox_backup::tools::runtime::main(mount_do(param, Some(pipe.1)))
70235f72
CE
1935 }
1936 Err(_) => bail!("failed to daemonize process"),
1937 }
1938}
1939
1940async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
1941 let repo = extract_repository_from_value(&param)?;
1942 let archive_name = tools::required_string_param(&param, "archive-name")?;
1943 let target = tools::required_string_param(&param, "target")?;
d59dbeca 1944 let client = connect(repo.host(), repo.user())?;
70235f72
CE
1945
1946 record_repository(&repo);
1947
1948 let path = tools::required_string_param(&param, "snapshot")?;
1949 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
1950 let group = BackupGroup::parse(path)?;
27c9affb 1951 api_datastore_latest_snapshot(&client, repo.store(), group).await?
70235f72
CE
1952 } else {
1953 let snapshot = BackupDir::parse(path)?;
1954 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
1955 };
1956
11377a47 1957 let keyfile = param["keyfile"].as_str().map(PathBuf::from);
70235f72
CE
1958 let crypt_config = match keyfile {
1959 None => None,
1960 Some(path) => {
6d20a29d 1961 let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
70235f72
CE
1962 Some(Arc::new(CryptConfig::new(key)?))
1963 }
1964 };
1965
1966 let server_archive_name = if archive_name.ends_with(".pxar") {
1967 format!("{}.didx", archive_name)
1968 } else {
1969 bail!("Can only mount pxar archives.");
1970 };
1971
296c50ba
DM
1972 let client = BackupReader::start(
1973 client,
1974 crypt_config.clone(),
1975 repo.store(),
1976 &backup_type,
1977 &backup_id,
1978 backup_time,
1979 true,
1980 ).await?;
70235f72 1981
f06b820a 1982 let manifest = client.download_manifest().await?;
296c50ba 1983
70235f72 1984 if server_archive_name.ends_with(".didx") {
c3d84a22 1985 let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
70235f72
CE
1986 let most_used = index.find_most_used_chunks(8);
1987 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1988 let reader = BufferedDynamicReader::new(index, chunk_reader);
f701d033 1989 let decoder = pxar::Decoder::new(reader)?;
70235f72 1990 let options = OsStr::new("ro,default_permissions");
2a111910 1991 let mut session = pxar::fuse::Session::new(decoder, &options, pipe.is_none())
70235f72
CE
1992 .map_err(|err| format_err!("pxar mount failed: {}", err))?;
1993
1994 // Mount the session but not call fuse deamonize as this will cause
1995 // issues with the runtime after the fork
1996 let deamonize = false;
1997 session.mount(&Path::new(target), deamonize)?;
1998
1999 if let Some(pipe) = pipe {
2000 nix::unistd::chdir(Path::new("/")).unwrap();
2001 // Finish creation of deamon by redirecting filedescriptors.
2002 let nullfd = nix::fcntl::open(
2003 "/dev/null",
2004 nix::fcntl::OFlag::O_RDWR,
2005 nix::sys::stat::Mode::empty(),
2006 ).unwrap();
2007 nix::unistd::dup2(nullfd, 0).unwrap();
2008 nix::unistd::dup2(nullfd, 1).unwrap();
2009 nix::unistd::dup2(nullfd, 2).unwrap();
2010 if nullfd > 2 {
2011 nix::unistd::close(nullfd).unwrap();
2012 }
2013 // Signal the parent process that we are done with the setup and it can
2014 // terminate.
11377a47 2015 nix::unistd::write(pipe, &[0u8])?;
70235f72
CE
2016 nix::unistd::close(pipe).unwrap();
2017 }
2018
2019 let multithreaded = true;
2020 session.run_loop(multithreaded)?;
2021 } else {
2022 bail!("unknown archive file extension (expected .pxar)");
2023 }
2024
2025 Ok(Value::Null)
2026}
2027
78d54360
WB
2028#[api(
2029 input: {
2030 properties: {
2031 "snapshot": {
2032 type: String,
2033 description: "Group/Snapshot path.",
2034 },
2035 "archive-name": {
2036 type: String,
2037 description: "Backup archive name.",
2038 },
2039 "repository": {
2040 optional: true,
2041 schema: REPO_URL_SCHEMA,
2042 },
2043 "keyfile": {
2044 optional: true,
2045 type: String,
2046 description: "Path to encryption key.",
2047 },
2048 },
2049 },
2050)]
2051/// Shell to interactively inspect and restore snapshots.
2052async fn catalog_shell(param: Value) -> Result<(), Error> {
3cf73c4e 2053 let repo = extract_repository_from_value(&param)?;
d59dbeca 2054 let client = connect(repo.host(), repo.user())?;
3cf73c4e
CE
2055 let path = tools::required_string_param(&param, "snapshot")?;
2056 let archive_name = tools::required_string_param(&param, "archive-name")?;
2057
2058 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
2059 let group = BackupGroup::parse(path)?;
27c9affb 2060 api_datastore_latest_snapshot(&client, repo.store(), group).await?
3cf73c4e
CE
2061 } else {
2062 let snapshot = BackupDir::parse(path)?;
2063 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
2064 };
2065
2066 let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p));
2067 let crypt_config = match keyfile {
2068 None => None,
2069 Some(path) => {
6d20a29d 2070 let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
3cf73c4e
CE
2071 Some(Arc::new(CryptConfig::new(key)?))
2072 }
2073 };
2074
2075 let server_archive_name = if archive_name.ends_with(".pxar") {
2076 format!("{}.didx", archive_name)
2077 } else {
2078 bail!("Can only mount pxar archives.");
2079 };
2080
2081 let client = BackupReader::start(
2082 client,
2083 crypt_config.clone(),
2084 repo.store(),
2085 &backup_type,
2086 &backup_id,
2087 backup_time,
2088 true,
2089 ).await?;
2090
2091 let tmpfile = std::fs::OpenOptions::new()
2092 .write(true)
2093 .read(true)
2094 .custom_flags(libc::O_TMPFILE)
2095 .open("/tmp")?;
2096
2097 let manifest = client.download_manifest().await?;
2098
2099 let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
2100 let most_used = index.find_most_used_chunks(8);
2101 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config.clone(), most_used);
2102 let reader = BufferedDynamicReader::new(index, chunk_reader);
f701d033
DM
2103 let mut decoder = pxar::Decoder::new(reader)?;
2104 decoder.set_callback(|path| {
2105 println!("{:?}", path);
2106 Ok(())
2107 });
3cf73c4e
CE
2108
2109 let tmpfile = client.download(CATALOG_NAME, tmpfile).await?;
2110 let index = DynamicIndexReader::new(tmpfile)
2111 .map_err(|err| format_err!("unable to read catalog index - {}", err))?;
2112
2113 // Note: do not use values stored in index (not trusted) - instead, computed them again
2114 let (csum, size) = index.compute_csum();
2115 manifest.verify_file(CATALOG_NAME, &csum, size)?;
2116
2117 let most_used = index.find_most_used_chunks(8);
2118 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
2119 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
2120 let mut catalogfile = std::fs::OpenOptions::new()
2121 .write(true)
2122 .read(true)
2123 .custom_flags(libc::O_TMPFILE)
2124 .open("/tmp")?;
2125
2126 std::io::copy(&mut reader, &mut catalogfile)
2127 .map_err(|err| format_err!("unable to download catalog - {}", err))?;
2128
2129 catalogfile.seek(SeekFrom::Start(0))?;
2130 let catalog_reader = CatalogReader::new(catalogfile);
2131 let state = Shell::new(
2132 catalog_reader,
2133 &server_archive_name,
2134 decoder,
2135 )?;
2136
2137 println!("Starting interactive shell");
2138 state.shell()?;
2139
2140 record_repository(&repo);
2141
78d54360 2142 Ok(())
3cf73c4e
CE
2143}
2144
1c6ad6ef 2145fn catalog_mgmt_cli() -> CliCommandMap {
78d54360 2146 let catalog_shell_cmd_def = CliCommand::new(&API_METHOD_CATALOG_SHELL)
1c6ad6ef
DM
2147 .arg_param(&["snapshot", "archive-name"])
2148 .completion_cb("repository", complete_repository)
0ec9e1b0 2149 .completion_cb("archive-name", complete_pxar_archive_name)
1c6ad6ef
DM
2150 .completion_cb("snapshot", complete_group_or_snapshot);
2151
1c6ad6ef
DM
2152 let catalog_dump_cmd_def = CliCommand::new(&API_METHOD_DUMP_CATALOG)
2153 .arg_param(&["snapshot"])
2154 .completion_cb("repository", complete_repository)
2155 .completion_cb("snapshot", complete_backup_snapshot);
2156
2157 CliCommandMap::new()
48ef3c33
DM
2158 .insert("dump", catalog_dump_cmd_def)
2159 .insert("shell", catalog_shell_cmd_def)
1c6ad6ef
DM
2160}
2161
5830c205
DM
2162#[api(
2163 input: {
2164 properties: {
2165 repository: {
2166 schema: REPO_URL_SCHEMA,
2167 optional: true,
2168 },
2169 limit: {
2170 description: "The maximal number of tasks to list.",
2171 type: Integer,
2172 optional: true,
2173 minimum: 1,
2174 maximum: 1000,
2175 default: 50,
2176 },
2177 "output-format": {
2178 schema: OUTPUT_FORMAT,
2179 optional: true,
2180 },
2181 }
2182 }
2183)]
2184/// List running server tasks for this repo user
d6c4a119 2185async fn task_list(param: Value) -> Result<Value, Error> {
5830c205 2186
c2043614
DM
2187 let output_format = get_output_format(&param);
2188
d6c4a119 2189 let repo = extract_repository_from_value(&param)?;
d59dbeca 2190 let client = connect(repo.host(), repo.user())?;
5830c205 2191
d6c4a119 2192 let limit = param["limit"].as_u64().unwrap_or(50) as usize;
5830c205 2193
d6c4a119
DM
2194 let args = json!({
2195 "running": true,
2196 "start": 0,
2197 "limit": limit,
2198 "userfilter": repo.user(),
2199 "store": repo.store(),
2200 });
2201 let result = client.get("api2/json/nodes/localhost/tasks", Some(args)).await?;
5830c205 2202
d6c4a119 2203 let data = &result["data"];
5830c205 2204
d6c4a119
DM
2205 if output_format == "text" {
2206 for item in data.as_array().unwrap() {
2207 println!(
2208 "{} {}",
2209 item["upid"].as_str().unwrap(),
2210 item["status"].as_str().unwrap_or("running"),
2211 );
5830c205 2212 }
d6c4a119
DM
2213 } else {
2214 format_and_print_result(data, &output_format);
2215 }
5830c205
DM
2216
2217 Ok(Value::Null)
2218}
2219
2220#[api(
2221 input: {
2222 properties: {
2223 repository: {
2224 schema: REPO_URL_SCHEMA,
2225 optional: true,
2226 },
2227 upid: {
2228 schema: UPID_SCHEMA,
2229 },
2230 }
2231 }
2232)]
2233/// Display the task log.
d6c4a119 2234async fn task_log(param: Value) -> Result<Value, Error> {
5830c205 2235
d6c4a119
DM
2236 let repo = extract_repository_from_value(&param)?;
2237 let upid = tools::required_string_param(&param, "upid")?;
5830c205 2238
d59dbeca 2239 let client = connect(repo.host(), repo.user())?;
5830c205 2240
d6c4a119 2241 display_task_log(client, upid, true).await?;
5830c205
DM
2242
2243 Ok(Value::Null)
2244}
2245
3f1020b7
DM
2246#[api(
2247 input: {
2248 properties: {
2249 repository: {
2250 schema: REPO_URL_SCHEMA,
2251 optional: true,
2252 },
2253 upid: {
2254 schema: UPID_SCHEMA,
2255 },
2256 }
2257 }
2258)]
2259/// Try to stop a specific task.
d6c4a119 2260async fn task_stop(param: Value) -> Result<Value, Error> {
3f1020b7 2261
d6c4a119
DM
2262 let repo = extract_repository_from_value(&param)?;
2263 let upid_str = tools::required_string_param(&param, "upid")?;
3f1020b7 2264
d59dbeca 2265 let mut client = connect(repo.host(), repo.user())?;
3f1020b7 2266
d6c4a119
DM
2267 let path = format!("api2/json/nodes/localhost/tasks/{}", upid_str);
2268 let _ = client.delete(&path, None).await?;
3f1020b7
DM
2269
2270 Ok(Value::Null)
2271}
2272
5830c205
DM
2273fn task_mgmt_cli() -> CliCommandMap {
2274
2275 let task_list_cmd_def = CliCommand::new(&API_METHOD_TASK_LIST)
2276 .completion_cb("repository", complete_repository);
2277
2278 let task_log_cmd_def = CliCommand::new(&API_METHOD_TASK_LOG)
2279 .arg_param(&["upid"]);
2280
3f1020b7
DM
2281 let task_stop_cmd_def = CliCommand::new(&API_METHOD_TASK_STOP)
2282 .arg_param(&["upid"]);
2283
5830c205
DM
2284 CliCommandMap::new()
2285 .insert("log", task_log_cmd_def)
2286 .insert("list", task_list_cmd_def)
3f1020b7 2287 .insert("stop", task_stop_cmd_def)
5830c205 2288}
1c6ad6ef 2289
f2401311 2290fn main() {
33d64b81 2291
255f378a 2292 let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP)
49fddd98 2293 .arg_param(&["backupspec"])
d0a03d40 2294 .completion_cb("repository", complete_repository)
49811347 2295 .completion_cb("backupspec", complete_backup_source)
6d0983db 2296 .completion_cb("keyfile", tools::complete_file_name)
49811347 2297 .completion_cb("chunk-size", complete_chunk_size);
f8838fe9 2298
255f378a 2299 let upload_log_cmd_def = CliCommand::new(&API_METHOD_UPLOAD_LOG)
49fddd98 2300 .arg_param(&["snapshot", "logfile"])
543a260f 2301 .completion_cb("snapshot", complete_backup_snapshot)
ec34f7eb
DM
2302 .completion_cb("logfile", tools::complete_file_name)
2303 .completion_cb("keyfile", tools::complete_file_name)
2304 .completion_cb("repository", complete_repository);
2305
255f378a 2306 let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS)
d0a03d40 2307 .completion_cb("repository", complete_repository);
41c039e1 2308
255f378a 2309 let snapshots_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOTS)
49fddd98 2310 .arg_param(&["group"])
024f11bb 2311 .completion_cb("group", complete_backup_group)
d0a03d40 2312 .completion_cb("repository", complete_repository);
184f17af 2313
255f378a 2314 let forget_cmd_def = CliCommand::new(&API_METHOD_FORGET_SNAPSHOTS)
49fddd98 2315 .arg_param(&["snapshot"])
b2388518 2316 .completion_cb("repository", complete_repository)
543a260f 2317 .completion_cb("snapshot", complete_backup_snapshot);
6f62c924 2318
255f378a 2319 let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
d0a03d40 2320 .completion_cb("repository", complete_repository);
8cc0d6af 2321
255f378a 2322 let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE)
49fddd98 2323 .arg_param(&["snapshot", "archive-name", "target"])
b2388518 2324 .completion_cb("repository", complete_repository)
08dc340a
DM
2325 .completion_cb("snapshot", complete_group_or_snapshot)
2326 .completion_cb("archive-name", complete_archive_name)
2327 .completion_cb("target", tools::complete_file_name);
9f912493 2328
255f378a 2329 let files_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOT_FILES)
49fddd98 2330 .arg_param(&["snapshot"])
52c171e4 2331 .completion_cb("repository", complete_repository)
543a260f 2332 .completion_cb("snapshot", complete_backup_snapshot);
52c171e4 2333
255f378a 2334 let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE)
49fddd98 2335 .arg_param(&["group"])
9fdc3ef4 2336 .completion_cb("group", complete_backup_group)
d0a03d40 2337 .completion_cb("repository", complete_repository);
9f912493 2338
255f378a 2339 let status_cmd_def = CliCommand::new(&API_METHOD_STATUS)
34a816cc
DM
2340 .completion_cb("repository", complete_repository);
2341
255f378a 2342 let login_cmd_def = CliCommand::new(&API_METHOD_API_LOGIN)
e240d8be
DM
2343 .completion_cb("repository", complete_repository);
2344
255f378a 2345 let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT)
e240d8be 2346 .completion_cb("repository", complete_repository);
32efac1c 2347
552c2259 2348 #[sortable]
255f378a
DM
2349 const API_METHOD_MOUNT: ApiMethod = ApiMethod::new(
2350 &ApiHandler::Sync(&mount),
2351 &ObjectSchema::new(
2352 "Mount pxar archive.",
552c2259 2353 &sorted!([
255f378a
DM
2354 ("snapshot", false, &StringSchema::new("Group/Snapshot path.").schema()),
2355 ("archive-name", false, &StringSchema::new("Backup archive name.").schema()),
2356 ("target", false, &StringSchema::new("Target directory path.").schema()),
2357 ("repository", true, &REPO_URL_SCHEMA),
2358 ("keyfile", true, &StringSchema::new("Path to encryption key.").schema()),
2359 ("verbose", true, &BooleanSchema::new("Verbose output.").default(false).schema()),
552c2259 2360 ]),
255f378a
DM
2361 )
2362 );
7074a0b3 2363
255f378a 2364 let mount_cmd_def = CliCommand::new(&API_METHOD_MOUNT)
49fddd98 2365 .arg_param(&["snapshot", "archive-name", "target"])
70235f72
CE
2366 .completion_cb("repository", complete_repository)
2367 .completion_cb("snapshot", complete_group_or_snapshot)
0ec9e1b0 2368 .completion_cb("archive-name", complete_pxar_archive_name)
70235f72 2369 .completion_cb("target", tools::complete_file_name);
e240d8be 2370
3cf73c4e 2371
41c039e1 2372 let cmd_def = CliCommandMap::new()
48ef3c33
DM
2373 .insert("backup", backup_cmd_def)
2374 .insert("upload-log", upload_log_cmd_def)
2375 .insert("forget", forget_cmd_def)
2376 .insert("garbage-collect", garbage_collect_cmd_def)
2377 .insert("list", list_cmd_def)
2378 .insert("login", login_cmd_def)
2379 .insert("logout", logout_cmd_def)
2380 .insert("prune", prune_cmd_def)
2381 .insert("restore", restore_cmd_def)
2382 .insert("snapshots", snapshots_cmd_def)
2383 .insert("files", files_cmd_def)
2384 .insert("status", status_cmd_def)
2385 .insert("key", key_mgmt_cli())
2386 .insert("mount", mount_cmd_def)
5830c205
DM
2387 .insert("catalog", catalog_mgmt_cli())
2388 .insert("task", task_mgmt_cli());
48ef3c33 2389
d08bc483
DM
2390 run_cli_command(cmd_def, Some(|future| {
2391 proxmox_backup::tools::runtime::main(future)
2392 }));
ff5d3707 2393}