]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-client.rs
pxar: less confusing logic
[proxmox-backup.git] / src / bin / proxmox-backup-client.rs
CommitLineData
2eeaacb9 1use std::collections::{HashSet, HashMap};
c443f58b 2use std::io::{self, Write, Seek, SeekFrom};
c443f58b
WB
3use std::path::{Path, PathBuf};
4use std::pin::Pin;
5use std::sync::{Arc, Mutex};
a6f87283 6use std::task::Context;
c443f58b
WB
7
8use anyhow::{bail, format_err, Error};
9use chrono::{Local, DateTime, Utc, TimeZone};
10use futures::future::FutureExt;
c443f58b 11use futures::stream::{StreamExt, TryStreamExt};
c443f58b 12use serde_json::{json, Value};
c443f58b
WB
13use tokio::sync::mpsc;
14use xdg::BaseDirectories;
2761d6a4 15
c443f58b 16use pathpatterns::{MatchEntry, MatchType, PatternFlag};
feaa1ad3 17use proxmox::tools::fs::{file_get_contents, file_get_json, replace_file, CreateOptions, image_size};
a47a02ae 18use proxmox::api::{ApiHandler, ApiMethod, RpcEnvironment};
3d482025 19use proxmox::api::schema::*;
7eea56ca 20use proxmox::api::cli::*;
5830c205 21use proxmox::api::api;
a6f87283 22use pxar::accessor::{MaybeReady, ReadAt, ReadAtOperation};
ff5d3707 23
fe0e04c6 24use proxmox_backup::tools;
bbf9e7e9 25use proxmox_backup::api2::types::*;
151c6ce2 26use proxmox_backup::client::*;
c443f58b 27use proxmox_backup::pxar::catalog::*;
4d16badf
WB
28use proxmox_backup::backup::{
29 archive_type,
4d16badf 30 load_and_decrypt_key,
4d16badf
WB
31 verify_chunk_size,
32 ArchiveType,
8e6e18b7 33 AsyncReadChunk,
4d16badf
WB
34 BackupDir,
35 BackupGroup,
36 BackupManifest,
37 BufferedDynamicReader,
f28d9088 38 CATALOG_NAME,
4d16badf
WB
39 CatalogReader,
40 CatalogWriter,
4d16badf
WB
41 ChunkStream,
42 CryptConfig,
f28d9088 43 CryptMode,
4d16badf
WB
44 DataBlob,
45 DynamicIndexReader,
46 FixedChunkStream,
47 FixedIndexReader,
48 IndexFile,
4d16badf 49 MANIFEST_BLOB_NAME,
4d16badf
WB
50 Shell,
51};
ae0be2dd 52
caea8d61
DM
53mod proxmox_backup_client;
54use proxmox_backup_client::*;
55
a05c0c6f 56const ENV_VAR_PBS_FINGERPRINT: &str = "PBS_FINGERPRINT";
d1c65727 57const ENV_VAR_PBS_PASSWORD: &str = "PBS_PASSWORD";
a05c0c6f 58
33d64b81 59
caea8d61 60pub const REPO_URL_SCHEMA: Schema = StringSchema::new("Repository URL.")
255f378a
DM
61 .format(&BACKUP_REPO_URL)
62 .max_length(256)
63 .schema();
d0a03d40 64
caea8d61 65pub const KEYFILE_SCHEMA: Schema = StringSchema::new(
a47a02ae
DM
66 "Path to encryption key. All data will be encrypted using this key.")
67 .schema();
68
96ee8577
WB
69pub const ENCRYPTION_SCHEMA: Schema = BooleanSchema::new(
70 "Explicitly enable or disable encryption. \
71 (Allows disabling encryption when a default key file is present.)")
72 .schema();
73
a47a02ae
DM
74const CHUNK_SIZE_SCHEMA: Schema = IntegerSchema::new(
75 "Chunk size in KB. Must be a power of 2.")
76 .minimum(64)
77 .maximum(4096)
78 .default(4096)
79 .schema();
80
2665cef7
DM
81fn get_default_repository() -> Option<String> {
82 std::env::var("PBS_REPOSITORY").ok()
83}
84
caea8d61 85pub fn extract_repository_from_value(
2665cef7
DM
86 param: &Value,
87) -> Result<BackupRepository, Error> {
88
89 let repo_url = param["repository"]
90 .as_str()
91 .map(String::from)
92 .or_else(get_default_repository)
93 .ok_or_else(|| format_err!("unable to get (default) repository"))?;
94
95 let repo: BackupRepository = repo_url.parse()?;
96
97 Ok(repo)
98}
99
100fn extract_repository_from_map(
101 param: &HashMap<String, String>,
102) -> Option<BackupRepository> {
103
104 param.get("repository")
105 .map(String::from)
106 .or_else(get_default_repository)
107 .and_then(|repo_url| repo_url.parse::<BackupRepository>().ok())
108}
109
d0a03d40
DM
110fn record_repository(repo: &BackupRepository) {
111
112 let base = match BaseDirectories::with_prefix("proxmox-backup") {
113 Ok(v) => v,
114 _ => return,
115 };
116
117 // usually $HOME/.cache/proxmox-backup/repo-list
118 let path = match base.place_cache_file("repo-list") {
119 Ok(v) => v,
120 _ => return,
121 };
122
11377a47 123 let mut data = file_get_json(&path, None).unwrap_or_else(|_| json!({}));
d0a03d40
DM
124
125 let repo = repo.to_string();
126
127 data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 };
128
129 let mut map = serde_json::map::Map::new();
130
131 loop {
132 let mut max_used = 0;
133 let mut max_repo = None;
134 for (repo, count) in data.as_object().unwrap() {
135 if map.contains_key(repo) { continue; }
136 if let Some(count) = count.as_i64() {
137 if count > max_used {
138 max_used = count;
139 max_repo = Some(repo);
140 }
141 }
142 }
143 if let Some(repo) = max_repo {
144 map.insert(repo.to_owned(), json!(max_used));
145 } else {
146 break;
147 }
148 if map.len() > 10 { // store max. 10 repos
149 break;
150 }
151 }
152
153 let new_data = json!(map);
154
feaa1ad3 155 let _ = replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new());
d0a03d40
DM
156}
157
43abba4b 158pub fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
d0a03d40
DM
159
160 let mut result = vec![];
161
162 let base = match BaseDirectories::with_prefix("proxmox-backup") {
163 Ok(v) => v,
164 _ => return result,
165 };
166
167 // usually $HOME/.cache/proxmox-backup/repo-list
168 let path = match base.place_cache_file("repo-list") {
169 Ok(v) => v,
170 _ => return result,
171 };
172
11377a47 173 let data = file_get_json(&path, None).unwrap_or_else(|_| json!({}));
d0a03d40
DM
174
175 if let Some(map) = data.as_object() {
49811347 176 for (repo, _count) in map {
d0a03d40
DM
177 result.push(repo.to_owned());
178 }
179 }
180
181 result
182}
183
d59dbeca
DM
184fn connect(server: &str, userid: &str) -> Result<HttpClient, Error> {
185
a05c0c6f
DM
186 let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
187
d1c65727
DM
188 use std::env::VarError::*;
189 let password = match std::env::var(ENV_VAR_PBS_PASSWORD) {
190 Ok(p) => Some(p),
191 Err(NotUnicode(_)) => bail!(format!("{} contains bad characters", ENV_VAR_PBS_PASSWORD)),
192 Err(NotPresent) => None,
193 };
194
d59dbeca 195 let options = HttpClientOptions::new()
5030b7ce 196 .prefix(Some("proxmox-backup".to_string()))
d1c65727 197 .password(password)
d59dbeca 198 .interactive(true)
a05c0c6f 199 .fingerprint(fingerprint)
5a74756c 200 .fingerprint_cache(true)
d59dbeca
DM
201 .ticket_cache(true);
202
203 HttpClient::new(server, userid, options)
204}
205
d105176f
DM
206async fn view_task_result(
207 client: HttpClient,
208 result: Value,
209 output_format: &str,
210) -> Result<(), Error> {
211 let data = &result["data"];
212 if output_format == "text" {
213 if let Some(upid) = data.as_str() {
214 display_task_log(client, upid, true).await?;
215 }
216 } else {
217 format_and_print_result(&data, &output_format);
218 }
219
220 Ok(())
221}
222
42af4b8f
DM
223async fn api_datastore_list_snapshots(
224 client: &HttpClient,
225 store: &str,
226 group: Option<BackupGroup>,
f24fc116 227) -> Result<Value, Error> {
42af4b8f
DM
228
229 let path = format!("api2/json/admin/datastore/{}/snapshots", store);
230
231 let mut args = json!({});
232 if let Some(group) = group {
233 args["backup-type"] = group.backup_type().into();
234 args["backup-id"] = group.backup_id().into();
235 }
236
237 let mut result = client.get(&path, Some(args)).await?;
238
f24fc116 239 Ok(result["data"].take())
42af4b8f
DM
240}
241
43abba4b 242pub async fn api_datastore_latest_snapshot(
27c9affb
DM
243 client: &HttpClient,
244 store: &str,
245 group: BackupGroup,
246) -> Result<(String, String, DateTime<Utc>), Error> {
247
f24fc116
DM
248 let list = api_datastore_list_snapshots(client, store, Some(group.clone())).await?;
249 let mut list: Vec<SnapshotListItem> = serde_json::from_value(list)?;
27c9affb
DM
250
251 if list.is_empty() {
252 bail!("backup group {:?} does not contain any snapshots.", group.group_path());
253 }
254
255 list.sort_unstable_by(|a, b| b.backup_time.cmp(&a.backup_time));
256
257 let backup_time = Utc.timestamp(list[0].backup_time, 0);
258
259 Ok((group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time))
260}
261
e9722f8b 262async fn backup_directory<P: AsRef<Path>>(
cf9271e2 263 client: &BackupWriter,
b957aa81 264 previous_manifest: Option<Arc<BackupManifest>>,
17d6979a 265 dir_path: P,
247cdbce 266 archive_name: &str,
36898ffc 267 chunk_size: Option<usize>,
2eeaacb9 268 device_set: Option<HashSet<u64>>,
219ef0e6 269 verbose: bool,
5b72c9b4 270 skip_lost_and_found: bool,
f1d99e3f 271 catalog: Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>,
c443f58b 272 exclude_pattern: Vec<MatchEntry>,
6fc053ed 273 entries_max: usize,
2c3891d1 274) -> Result<BackupStats, Error> {
33d64b81 275
6fc053ed
CE
276 let pxar_stream = PxarBackupStream::open(
277 dir_path.as_ref(),
278 device_set,
279 verbose,
280 skip_lost_and_found,
281 catalog,
189996cf 282 exclude_pattern,
6fc053ed
CE
283 entries_max,
284 )?;
e9722f8b 285 let mut chunk_stream = ChunkStream::new(pxar_stream, chunk_size);
ff3d3100 286
e9722f8b 287 let (mut tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks
5e7a09be 288
c4ff3dce 289 let stream = rx
e9722f8b 290 .map_err(Error::from);
17d6979a 291
c4ff3dce 292 // spawn chunker inside a separate task so that it can run parallel
e9722f8b 293 tokio::spawn(async move {
db0cb9ce
WB
294 while let Some(v) = chunk_stream.next().await {
295 let _ = tx.send(v).await;
296 }
e9722f8b 297 });
17d6979a 298
e9722f8b 299 let stats = client
b957aa81 300 .upload_stream(previous_manifest, archive_name, stream, "dynamic", None)
e9722f8b 301 .await?;
bcd879cf 302
2c3891d1 303 Ok(stats)
bcd879cf
DM
304}
305
e9722f8b 306async fn backup_image<P: AsRef<Path>>(
cf9271e2 307 client: &BackupWriter,
b957aa81 308 previous_manifest: Option<Arc<BackupManifest>>,
6af905c1
DM
309 image_path: P,
310 archive_name: &str,
311 image_size: u64,
36898ffc 312 chunk_size: Option<usize>,
1c0472e8 313 _verbose: bool,
2c3891d1 314) -> Result<BackupStats, Error> {
6af905c1 315
6af905c1
DM
316 let path = image_path.as_ref().to_owned();
317
e9722f8b 318 let file = tokio::fs::File::open(path).await?;
6af905c1 319
db0cb9ce 320 let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new())
6af905c1
DM
321 .map_err(Error::from);
322
36898ffc 323 let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024));
6af905c1 324
e9722f8b 325 let stats = client
b957aa81 326 .upload_stream(previous_manifest, archive_name, stream, "fixed", Some(image_size))
e9722f8b 327 .await?;
6af905c1 328
2c3891d1 329 Ok(stats)
6af905c1
DM
330}
331
a47a02ae
DM
332#[api(
333 input: {
334 properties: {
335 repository: {
336 schema: REPO_URL_SCHEMA,
337 optional: true,
338 },
339 "output-format": {
340 schema: OUTPUT_FORMAT,
341 optional: true,
342 },
343 }
344 }
345)]
346/// List backup groups.
347async fn list_backup_groups(param: Value) -> Result<Value, Error> {
812c6f87 348
c81b2b7c
DM
349 let output_format = get_output_format(&param);
350
2665cef7 351 let repo = extract_repository_from_value(&param)?;
812c6f87 352
d59dbeca 353 let client = connect(repo.host(), repo.user())?;
812c6f87 354
d0a03d40 355 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
812c6f87 356
8a8a4703 357 let mut result = client.get(&path, None).await?;
812c6f87 358
d0a03d40
DM
359 record_repository(&repo);
360
c81b2b7c
DM
361 let render_group_path = |_v: &Value, record: &Value| -> Result<String, Error> {
362 let item: GroupListItem = serde_json::from_value(record.to_owned())?;
363 let group = BackupGroup::new(item.backup_type, item.backup_id);
364 Ok(group.group_path().to_str().unwrap().to_owned())
365 };
812c6f87 366
18deda40
DM
367 let render_last_backup = |_v: &Value, record: &Value| -> Result<String, Error> {
368 let item: GroupListItem = serde_json::from_value(record.to_owned())?;
369 let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.last_backup);
370 Ok(snapshot.relative_path().to_str().unwrap().to_owned())
c81b2b7c 371 };
812c6f87 372
c81b2b7c
DM
373 let render_files = |_v: &Value, record: &Value| -> Result<String, Error> {
374 let item: GroupListItem = serde_json::from_value(record.to_owned())?;
4939255f 375 Ok(tools::format::render_backup_file_list(&item.files))
c81b2b7c 376 };
812c6f87 377
c81b2b7c
DM
378 let options = default_table_format_options()
379 .sortby("backup-type", false)
380 .sortby("backup-id", false)
381 .column(ColumnConfig::new("backup-id").renderer(render_group_path).header("group"))
18deda40
DM
382 .column(
383 ColumnConfig::new("last-backup")
384 .renderer(render_last_backup)
385 .header("last snapshot")
386 .right_align(false)
387 )
c81b2b7c
DM
388 .column(ColumnConfig::new("backup-count"))
389 .column(ColumnConfig::new("files").renderer(render_files));
ad20d198 390
c81b2b7c 391 let mut data: Value = result["data"].take();
ad20d198 392
c81b2b7c 393 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_GROUPS;
812c6f87 394
c81b2b7c 395 format_and_print_result_full(&mut data, info, &output_format, &options);
34a816cc 396
812c6f87
DM
397 Ok(Value::Null)
398}
399
a47a02ae
DM
400#[api(
401 input: {
402 properties: {
403 repository: {
404 schema: REPO_URL_SCHEMA,
405 optional: true,
406 },
407 group: {
408 type: String,
409 description: "Backup group.",
410 optional: true,
411 },
412 "output-format": {
413 schema: OUTPUT_FORMAT,
414 optional: true,
415 },
416 }
417 }
418)]
419/// List backup snapshots.
420async fn list_snapshots(param: Value) -> Result<Value, Error> {
184f17af 421
2665cef7 422 let repo = extract_repository_from_value(&param)?;
184f17af 423
c2043614 424 let output_format = get_output_format(&param);
34a816cc 425
d59dbeca 426 let client = connect(repo.host(), repo.user())?;
184f17af 427
d6d3b353
DM
428 let group: Option<BackupGroup> = if let Some(path) = param["group"].as_str() {
429 Some(path.parse()?)
42af4b8f
DM
430 } else {
431 None
432 };
184f17af 433
f24fc116 434 let mut data = api_datastore_list_snapshots(&client, repo.store(), group).await?;
184f17af 435
d0a03d40
DM
436 record_repository(&repo);
437
f24fc116
DM
438 let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> {
439 let item: SnapshotListItem = serde_json::from_value(record.to_owned())?;
af9d4afc 440 let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time);
f24fc116
DM
441 Ok(snapshot.relative_path().to_str().unwrap().to_owned())
442 };
184f17af 443
f24fc116
DM
444 let render_files = |_v: &Value, record: &Value| -> Result<String, Error> {
445 let item: SnapshotListItem = serde_json::from_value(record.to_owned())?;
1c090810
DC
446 let mut filenames = Vec::new();
447 for file in &item.files {
448 filenames.push(file.filename.to_string());
449 }
450 Ok(tools::format::render_backup_file_list(&filenames[..]))
f24fc116
DM
451 };
452
c2043614 453 let options = default_table_format_options()
f24fc116
DM
454 .sortby("backup-type", false)
455 .sortby("backup-id", false)
456 .sortby("backup-time", false)
457 .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot"))
458 .column(ColumnConfig::new("size"))
459 .column(ColumnConfig::new("files").renderer(render_files))
460 ;
461
462 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOTS;
463
464 format_and_print_result_full(&mut data, info, &output_format, &options);
184f17af
DM
465
466 Ok(Value::Null)
467}
468
a47a02ae
DM
469#[api(
470 input: {
471 properties: {
472 repository: {
473 schema: REPO_URL_SCHEMA,
474 optional: true,
475 },
476 snapshot: {
477 type: String,
478 description: "Snapshot path.",
479 },
480 }
481 }
482)]
483/// Forget (remove) backup snapshots.
484async fn forget_snapshots(param: Value) -> Result<Value, Error> {
6f62c924 485
2665cef7 486 let repo = extract_repository_from_value(&param)?;
6f62c924
DM
487
488 let path = tools::required_string_param(&param, "snapshot")?;
a67f7d0a 489 let snapshot: BackupDir = path.parse()?;
6f62c924 490
d59dbeca 491 let mut client = connect(repo.host(), repo.user())?;
6f62c924 492
9e391bb7 493 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
6f62c924 494
8a8a4703
DM
495 let result = client.delete(&path, Some(json!({
496 "backup-type": snapshot.group().backup_type(),
497 "backup-id": snapshot.group().backup_id(),
498 "backup-time": snapshot.backup_time().timestamp(),
499 }))).await?;
6f62c924 500
d0a03d40
DM
501 record_repository(&repo);
502
6f62c924
DM
503 Ok(result)
504}
505
a47a02ae
DM
506#[api(
507 input: {
508 properties: {
509 repository: {
510 schema: REPO_URL_SCHEMA,
511 optional: true,
512 },
513 }
514 }
515)]
516/// Try to login. If successful, store ticket.
517async fn api_login(param: Value) -> Result<Value, Error> {
e240d8be
DM
518
519 let repo = extract_repository_from_value(&param)?;
520
d59dbeca 521 let client = connect(repo.host(), repo.user())?;
8a8a4703 522 client.login().await?;
e240d8be
DM
523
524 record_repository(&repo);
525
526 Ok(Value::Null)
527}
528
a47a02ae
DM
529#[api(
530 input: {
531 properties: {
532 repository: {
533 schema: REPO_URL_SCHEMA,
534 optional: true,
535 },
536 }
537 }
538)]
539/// Logout (delete stored ticket).
540fn api_logout(param: Value) -> Result<Value, Error> {
e240d8be
DM
541
542 let repo = extract_repository_from_value(&param)?;
543
5030b7ce 544 delete_ticket_info("proxmox-backup", repo.host(), repo.user())?;
e240d8be
DM
545
546 Ok(Value::Null)
547}
548
9049a8cf 549
a47a02ae
DM
550#[api(
551 input: {
552 properties: {
553 repository: {
554 schema: REPO_URL_SCHEMA,
555 optional: true,
556 },
557 snapshot: {
558 type: String,
559 description: "Snapshot path.",
560 },
561 "output-format": {
562 schema: OUTPUT_FORMAT,
563 optional: true,
564 },
565 }
566 }
567)]
568/// List snapshot files.
569async fn list_snapshot_files(param: Value) -> Result<Value, Error> {
52c171e4
DM
570
571 let repo = extract_repository_from_value(&param)?;
572
573 let path = tools::required_string_param(&param, "snapshot")?;
a67f7d0a 574 let snapshot: BackupDir = path.parse()?;
52c171e4 575
c2043614 576 let output_format = get_output_format(&param);
52c171e4 577
d59dbeca 578 let client = connect(repo.host(), repo.user())?;
52c171e4
DM
579
580 let path = format!("api2/json/admin/datastore/{}/files", repo.store());
581
8a8a4703
DM
582 let mut result = client.get(&path, Some(json!({
583 "backup-type": snapshot.group().backup_type(),
584 "backup-id": snapshot.group().backup_id(),
585 "backup-time": snapshot.backup_time().timestamp(),
586 }))).await?;
52c171e4
DM
587
588 record_repository(&repo);
589
ea5f547f 590 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOT_FILES;
52c171e4 591
ea5f547f
DM
592 let mut data: Value = result["data"].take();
593
c2043614 594 let options = default_table_format_options();
ea5f547f
DM
595
596 format_and_print_result_full(&mut data, info, &output_format, &options);
52c171e4
DM
597
598 Ok(Value::Null)
599}
600
a47a02ae 601#[api(
94913f35 602 input: {
a47a02ae
DM
603 properties: {
604 repository: {
605 schema: REPO_URL_SCHEMA,
606 optional: true,
607 },
94913f35
DM
608 "output-format": {
609 schema: OUTPUT_FORMAT,
610 optional: true,
611 },
612 },
613 },
a47a02ae
DM
614)]
615/// Start garbage collection for a specific repository.
616async fn start_garbage_collection(param: Value) -> Result<Value, Error> {
8cc0d6af 617
2665cef7 618 let repo = extract_repository_from_value(&param)?;
c2043614
DM
619
620 let output_format = get_output_format(&param);
8cc0d6af 621
d59dbeca 622 let mut client = connect(repo.host(), repo.user())?;
8cc0d6af 623
d0a03d40 624 let path = format!("api2/json/admin/datastore/{}/gc", repo.store());
8cc0d6af 625
8a8a4703 626 let result = client.post(&path, None).await?;
8cc0d6af 627
8a8a4703 628 record_repository(&repo);
d0a03d40 629
8a8a4703 630 view_task_result(client, result, &output_format).await?;
e5f7def4 631
e5f7def4 632 Ok(Value::Null)
8cc0d6af 633}
33d64b81 634
bf6e3217 635fn spawn_catalog_upload(
b957aa81 636 client: Arc<BackupWriter>
bf6e3217
DM
637) -> Result<
638 (
f1d99e3f 639 Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>,
bf6e3217
DM
640 tokio::sync::oneshot::Receiver<Result<BackupStats, Error>>
641 ), Error>
642{
f1d99e3f
DM
643 let (catalog_tx, catalog_rx) = std::sync::mpsc::sync_channel(10); // allow to buffer 10 writes
644 let catalog_stream = crate::tools::StdChannelStream(catalog_rx);
bf6e3217
DM
645 let catalog_chunk_size = 512*1024;
646 let catalog_chunk_stream = ChunkStream::new(catalog_stream, Some(catalog_chunk_size));
647
f1d99e3f 648 let catalog = Arc::new(Mutex::new(CatalogWriter::new(crate::tools::StdChannelWriter::new(catalog_tx))?));
bf6e3217
DM
649
650 let (catalog_result_tx, catalog_result_rx) = tokio::sync::oneshot::channel();
651
652 tokio::spawn(async move {
653 let catalog_upload_result = client
b957aa81 654 .upload_stream(None, CATALOG_NAME, catalog_chunk_stream, "dynamic", None)
bf6e3217
DM
655 .await;
656
657 if let Err(ref err) = catalog_upload_result {
658 eprintln!("catalog upload error - {}", err);
659 client.cancel();
660 }
661
662 let _ = catalog_result_tx.send(catalog_upload_result);
663 });
664
665 Ok((catalog, catalog_result_rx))
666}
667
f28d9088
WB
668fn keyfile_parameters(param: &Value) -> Result<(Option<PathBuf>, CryptMode), Error> {
669 let keyfile = match param.get("keyfile") {
670 Some(Value::String(keyfile)) => Some(keyfile),
671 Some(_) => bail!("bad --keyfile parameter type"),
672 None => None,
673 };
674
675 let crypt_mode: Option<CryptMode> = match param.get("crypt-mode") {
676 Some(mode) => Some(serde_json::from_value(mode.clone())?),
677 None => None,
678 };
679
680 Ok(match (keyfile, crypt_mode) {
96ee8577 681 // no parameters:
f28d9088 682 (None, None) => (key::optional_default_key_path()?, CryptMode::Encrypt),
96ee8577 683
f28d9088
WB
684 // just --crypt-mode=none
685 (None, Some(CryptMode::None)) => (None, CryptMode::None),
96ee8577 686
f28d9088
WB
687 // just --crypt-mode other than none
688 (None, Some(crypt_mode)) => match key::optional_default_key_path()? {
689 None => bail!("--crypt-mode without --keyfile and no default key file available"),
690 Some(path) => (Some(path), crypt_mode),
96ee8577
WB
691 }
692
693 // just --keyfile
f28d9088 694 (Some(keyfile), None) => (Some(PathBuf::from(keyfile)), CryptMode::Encrypt),
96ee8577 695
f28d9088
WB
696 // --keyfile and --crypt-mode=none
697 (Some(_), Some(CryptMode::None)) => {
698 bail!("--keyfile and --crypt-mode=none are mutually exclusive");
96ee8577
WB
699 }
700
f28d9088
WB
701 // --keyfile and --crypt-mode other than none
702 (Some(keyfile), Some(crypt_mode)) => (Some(PathBuf::from(keyfile)), crypt_mode),
96ee8577
WB
703 })
704}
705
a47a02ae
DM
706#[api(
707 input: {
708 properties: {
709 backupspec: {
710 type: Array,
711 description: "List of backup source specifications ([<label.ext>:<path>] ...)",
712 items: {
713 schema: BACKUP_SOURCE_SCHEMA,
714 }
715 },
716 repository: {
717 schema: REPO_URL_SCHEMA,
718 optional: true,
719 },
720 "include-dev": {
721 description: "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.",
722 optional: true,
723 items: {
724 type: String,
725 description: "Path to file.",
726 }
727 },
728 keyfile: {
729 schema: KEYFILE_SCHEMA,
730 optional: true,
731 },
96ee8577
WB
732 encryption: {
733 schema: ENCRYPTION_SCHEMA,
734 optional: true,
735 },
a47a02ae
DM
736 "skip-lost-and-found": {
737 type: Boolean,
738 description: "Skip lost+found directory.",
739 optional: true,
740 },
741 "backup-type": {
742 schema: BACKUP_TYPE_SCHEMA,
743 optional: true,
744 },
745 "backup-id": {
746 schema: BACKUP_ID_SCHEMA,
747 optional: true,
748 },
749 "backup-time": {
750 schema: BACKUP_TIME_SCHEMA,
751 optional: true,
752 },
753 "chunk-size": {
754 schema: CHUNK_SIZE_SCHEMA,
755 optional: true,
756 },
189996cf
CE
757 "exclude": {
758 type: Array,
759 description: "List of paths or patterns for matching files to exclude.",
760 optional: true,
761 items: {
762 type: String,
763 description: "Path or match pattern.",
764 }
765 },
6fc053ed
CE
766 "entries-max": {
767 type: Integer,
768 description: "Max number of entries to hold in memory.",
769 optional: true,
c443f58b 770 default: proxmox_backup::pxar::ENCODER_MAX_ENTRIES as isize,
6fc053ed 771 },
e02c3d46
DM
772 "verbose": {
773 type: Boolean,
774 description: "Verbose output.",
775 optional: true,
776 },
a47a02ae
DM
777 }
778 }
779)]
780/// Create (host) backup.
781async fn create_backup(
6049b71f
DM
782 param: Value,
783 _info: &ApiMethod,
dd5495d6 784 _rpcenv: &mut dyn RpcEnvironment,
6049b71f 785) -> Result<Value, Error> {
ff5d3707 786
2665cef7 787 let repo = extract_repository_from_value(&param)?;
ae0be2dd
DM
788
789 let backupspec_list = tools::required_array_param(&param, "backupspec")?;
a914a774 790
eed6db39
DM
791 let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false);
792
5b72c9b4
DM
793 let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false);
794
219ef0e6
DM
795 let verbose = param["verbose"].as_bool().unwrap_or(false);
796
ca5d0b61
DM
797 let backup_time_opt = param["backup-time"].as_i64();
798
36898ffc 799 let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize);
2d9d143a 800
247cdbce
DM
801 if let Some(size) = chunk_size_opt {
802 verify_chunk_size(size)?;
2d9d143a
DM
803 }
804
f28d9088 805 let (keyfile, crypt_mode) = keyfile_parameters(&param)?;
6d0983db 806
f69adc81 807 let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename());
fba30411 808
bbf9e7e9 809 let backup_type = param["backup-type"].as_str().unwrap_or("host");
ca5d0b61 810
2eeaacb9
DM
811 let include_dev = param["include-dev"].as_array();
812
c443f58b
WB
813 let entries_max = param["entries-max"].as_u64()
814 .unwrap_or(proxmox_backup::pxar::ENCODER_MAX_ENTRIES as u64);
6fc053ed 815
189996cf 816 let empty = Vec::new();
c443f58b
WB
817 let exclude_args = param["exclude"].as_array().unwrap_or(&empty);
818
239e49f9 819 let mut pattern_list = Vec::with_capacity(exclude_args.len());
c443f58b
WB
820 for entry in exclude_args {
821 let entry = entry.as_str().ok_or_else(|| format_err!("Invalid pattern string slice"))?;
239e49f9 822 pattern_list.push(
c443f58b
WB
823 MatchEntry::parse_pattern(entry, PatternFlag::PATH_NAME, MatchType::Exclude)
824 .map_err(|err| format_err!("invalid exclude pattern entry: {}", err))?
825 );
189996cf
CE
826 }
827
2eeaacb9
DM
828 let mut devices = if all_file_systems { None } else { Some(HashSet::new()) };
829
830 if let Some(include_dev) = include_dev {
831 if all_file_systems {
832 bail!("option 'all-file-systems' conflicts with option 'include-dev'");
833 }
834
835 let mut set = HashSet::new();
836 for path in include_dev {
837 let path = path.as_str().unwrap();
838 let stat = nix::sys::stat::stat(path)
839 .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?;
840 set.insert(stat.st_dev);
841 }
842 devices = Some(set);
843 }
844
ae0be2dd 845 let mut upload_list = vec![];
a914a774 846
ae0be2dd 847 for backupspec in backupspec_list {
7cc3473a
DM
848 let spec = parse_backup_specification(backupspec.as_str().unwrap())?;
849 let filename = &spec.config_string;
850 let target = &spec.archive_name;
bcd879cf 851
eb1804c5
DM
852 use std::os::unix::fs::FileTypeExt;
853
3fa71727
CE
854 let metadata = std::fs::metadata(filename)
855 .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?;
eb1804c5 856 let file_type = metadata.file_type();
23bb8780 857
7cc3473a
DM
858 match spec.spec_type {
859 BackupSpecificationType::PXAR => {
ec8a9bb9
DM
860 if !file_type.is_dir() {
861 bail!("got unexpected file type (expected directory)");
862 }
7cc3473a 863 upload_list.push((BackupSpecificationType::PXAR, filename.to_owned(), format!("{}.didx", target), 0));
ec8a9bb9 864 }
7cc3473a 865 BackupSpecificationType::IMAGE => {
ec8a9bb9
DM
866 if !(file_type.is_file() || file_type.is_block_device()) {
867 bail!("got unexpected file type (expected file or block device)");
868 }
eb1804c5 869
e18a6c9e 870 let size = image_size(&PathBuf::from(filename))?;
23bb8780 871
ec8a9bb9 872 if size == 0 { bail!("got zero-sized file '{}'", filename); }
ae0be2dd 873
7cc3473a 874 upload_list.push((BackupSpecificationType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size));
ec8a9bb9 875 }
7cc3473a 876 BackupSpecificationType::CONFIG => {
ec8a9bb9
DM
877 if !file_type.is_file() {
878 bail!("got unexpected file type (expected regular file)");
879 }
7cc3473a 880 upload_list.push((BackupSpecificationType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len()));
ec8a9bb9 881 }
7cc3473a 882 BackupSpecificationType::LOGFILE => {
79679c2d
DM
883 if !file_type.is_file() {
884 bail!("got unexpected file type (expected regular file)");
885 }
7cc3473a 886 upload_list.push((BackupSpecificationType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len()));
ec8a9bb9 887 }
ae0be2dd
DM
888 }
889 }
890
11377a47 891 let backup_time = Utc.timestamp(backup_time_opt.unwrap_or_else(|| Utc::now().timestamp()), 0);
ae0be2dd 892
d59dbeca 893 let client = connect(repo.host(), repo.user())?;
d0a03d40
DM
894 record_repository(&repo);
895
ca5d0b61
DM
896 println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time));
897
f69adc81 898 println!("Client name: {}", proxmox::tools::nodename());
ca5d0b61
DM
899
900 let start_time = Local::now();
901
7a6cfbd9 902 println!("Starting protocol: {}", start_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
51144821 903
bb823140
DM
904 let (crypt_config, rsa_encrypted_key) = match keyfile {
905 None => (None, None),
6d0983db 906 Some(path) => {
9696f519 907 let (key, created) = load_and_decrypt_key(&path, &key::get_encryption_key_password)?;
bb823140
DM
908
909 let crypt_config = CryptConfig::new(key)?;
910
911 let path = master_pubkey_path()?;
912 if path.exists() {
e18a6c9e 913 let pem_data = file_get_contents(&path)?;
bb823140
DM
914 let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
915 let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?;
916 (Some(Arc::new(crypt_config)), Some(enc_key))
917 } else {
918 (Some(Arc::new(crypt_config)), None)
919 }
6d0983db
DM
920 }
921 };
f98ac774 922
8a8a4703
DM
923 let client = BackupWriter::start(
924 client,
b957aa81 925 crypt_config.clone(),
8a8a4703
DM
926 repo.store(),
927 backup_type,
928 &backup_id,
929 backup_time,
930 verbose,
931 ).await?;
932
b957aa81
DM
933 let previous_manifest = if let Ok(previous_manifest) = client.download_previous_manifest().await {
934 Some(Arc::new(previous_manifest))
935 } else {
936 None
937 };
938
8a8a4703
DM
939 let snapshot = BackupDir::new(backup_type, backup_id, backup_time.timestamp());
940 let mut manifest = BackupManifest::new(snapshot);
941
5d85847f
DC
942 let mut catalog = None;
943 let mut catalog_result_tx = None;
8a8a4703
DM
944
945 for (backup_type, filename, target, size) in upload_list {
946 match backup_type {
7cc3473a 947 BackupSpecificationType::CONFIG => {
8a8a4703
DM
948 println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target);
949 let stats = client
f28d9088 950 .upload_blob_from_file(&filename, &target, true, crypt_mode)
8a8a4703 951 .await?;
f28d9088 952 manifest.add_file(target, stats.size, stats.csum, crypt_mode)?;
8a8a4703 953 }
7cc3473a 954 BackupSpecificationType::LOGFILE => { // fixme: remove - not needed anymore ?
8a8a4703
DM
955 println!("Upload log file '{}' to '{:?}' as {}", filename, repo, target);
956 let stats = client
f28d9088 957 .upload_blob_from_file(&filename, &target, true, crypt_mode)
8a8a4703 958 .await?;
f28d9088 959 manifest.add_file(target, stats.size, stats.csum, crypt_mode)?;
8a8a4703 960 }
7cc3473a 961 BackupSpecificationType::PXAR => {
5d85847f
DC
962 // start catalog upload on first use
963 if catalog.is_none() {
b957aa81 964 let (cat, res) = spawn_catalog_upload(client.clone())?;
5d85847f
DC
965 catalog = Some(cat);
966 catalog_result_tx = Some(res);
967 }
968 let catalog = catalog.as_ref().unwrap();
969
8a8a4703
DM
970 println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target);
971 catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?;
972 let stats = backup_directory(
973 &client,
b957aa81 974 previous_manifest.clone(),
8a8a4703
DM
975 &filename,
976 &target,
977 chunk_size_opt,
978 devices.clone(),
979 verbose,
980 skip_lost_and_found,
8a8a4703 981 catalog.clone(),
239e49f9 982 pattern_list.clone(),
6fc053ed 983 entries_max as usize,
8a8a4703 984 ).await?;
f28d9088 985 manifest.add_file(target, stats.size, stats.csum, crypt_mode)?;
8a8a4703
DM
986 catalog.lock().unwrap().end_directory()?;
987 }
7cc3473a 988 BackupSpecificationType::IMAGE => {
8a8a4703
DM
989 println!("Upload image '{}' to '{:?}' as {}", filename, repo, target);
990 let stats = backup_image(
991 &client,
b957aa81
DM
992 previous_manifest.clone(),
993 &filename,
8a8a4703
DM
994 &target,
995 size,
996 chunk_size_opt,
997 verbose,
8a8a4703 998 ).await?;
f28d9088 999 manifest.add_file(target, stats.size, stats.csum, crypt_mode)?;
6af905c1
DM
1000 }
1001 }
8a8a4703 1002 }
4818c8b6 1003
8a8a4703 1004 // finalize and upload catalog
5d85847f 1005 if let Some(catalog) = catalog {
8a8a4703
DM
1006 let mutex = Arc::try_unwrap(catalog)
1007 .map_err(|_| format_err!("unable to get catalog (still used)"))?;
1008 let mut catalog = mutex.into_inner().unwrap();
bf6e3217 1009
8a8a4703 1010 catalog.finish()?;
2761d6a4 1011
8a8a4703 1012 drop(catalog); // close upload stream
2761d6a4 1013
5d85847f
DC
1014 if let Some(catalog_result_rx) = catalog_result_tx {
1015 let stats = catalog_result_rx.await??;
f28d9088 1016 manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum, crypt_mode)?;
5d85847f 1017 }
8a8a4703 1018 }
2761d6a4 1019
8a8a4703
DM
1020 if let Some(rsa_encrypted_key) = rsa_encrypted_key {
1021 let target = "rsa-encrypted.key";
1022 println!("Upload RSA encoded key to '{:?}' as {}", repo, target);
1023 let stats = client
f28d9088 1024 .upload_blob_from_data(rsa_encrypted_key, target, false, CryptMode::None)
8a8a4703 1025 .await?;
f28d9088 1026 manifest.add_file(format!("{}.blob", target), stats.size, stats.csum, crypt_mode)?;
8a8a4703
DM
1027
1028 // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t
1029 /*
1030 let mut buffer2 = vec![0u8; rsa.size() as usize];
1031 let pem_data = file_get_contents("master-private.pem")?;
1032 let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?;
1033 let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?;
1034 println!("TEST {} {:?}", len, buffer2);
1035 */
1036 }
9f46c7de 1037
8a8a4703
DM
1038 // create manifest (index.json)
1039 let manifest = manifest.into_json();
2c3891d1 1040
8a8a4703
DM
1041 println!("Upload index.json to '{:?}'", repo);
1042 let manifest = serde_json::to_string_pretty(&manifest)?.into();
af3a0ae7
WB
1043 // manifests are never encrypted
1044 let manifest_crypt_mode = match crypt_mode {
1045 CryptMode::None => CryptMode::None,
1046 _ => CryptMode::SignOnly,
1047 };
8a8a4703 1048 client
af3a0ae7 1049 .upload_blob_from_data(manifest, MANIFEST_BLOB_NAME, true, manifest_crypt_mode)
8a8a4703 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
8e6e18b7 1084async fn dump_image<W: Write>(
88892ea8
DM
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
e9764238 1094 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
88892ea8
DM
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();
8e6e18b7 1104 let raw_data = chunk_reader.read_chunk(&digest).await?;
88892ea8 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
dc155e9b 1129fn parse_archive_type(name: &str) -> (String, ArchiveType) {
2d32fe2c
TL
1130 if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") {
1131 (name.into(), archive_type(name).unwrap())
1132 } else if name.ends_with(".pxar") {
dc155e9b
TL
1133 (format!("{}.didx", name), ArchiveType::DynamicIndex)
1134 } else if name.ends_with(".img") {
1135 (format!("{}.fidx", name), ArchiveType::FixedIndex)
1136 } else {
1137 (format!("{}.blob", name), ArchiveType::Blob)
1138 }
1139}
1140
a47a02ae
DM
1141#[api(
1142 input: {
1143 properties: {
1144 repository: {
1145 schema: REPO_URL_SCHEMA,
1146 optional: true,
1147 },
1148 snapshot: {
1149 type: String,
1150 description: "Group/Snapshot path.",
1151 },
1152 "archive-name": {
1153 description: "Backup archive name.",
1154 type: String,
1155 },
1156 target: {
1157 type: String,
90c815bf 1158 description: r###"Target directory path. Use '-' to write to standard output.
8a8a4703 1159
5eee6d89 1160We do not extraxt '.pxar' archives when writing to standard output.
8a8a4703 1161
a47a02ae
DM
1162"###
1163 },
1164 "allow-existing-dirs": {
1165 type: Boolean,
1166 description: "Do not fail if directories already exists.",
1167 optional: true,
1168 },
1169 keyfile: {
1170 schema: KEYFILE_SCHEMA,
1171 optional: true,
1172 },
96ee8577
WB
1173 encryption: {
1174 schema: ENCRYPTION_SCHEMA,
1175 optional: true,
1176 },
a47a02ae
DM
1177 }
1178 }
1179)]
1180/// Restore backup repository.
1181async fn restore(param: Value) -> Result<Value, Error> {
2665cef7 1182 let repo = extract_repository_from_value(&param)?;
9f912493 1183
86eda3eb
DM
1184 let verbose = param["verbose"].as_bool().unwrap_or(false);
1185
46d5aa0a
DM
1186 let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false);
1187
d5c34d98
DM
1188 let archive_name = tools::required_string_param(&param, "archive-name")?;
1189
d59dbeca 1190 let client = connect(repo.host(), repo.user())?;
d0a03d40 1191
d0a03d40 1192 record_repository(&repo);
d5c34d98 1193
9f912493 1194 let path = tools::required_string_param(&param, "snapshot")?;
9f912493 1195
86eda3eb 1196 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
d6d3b353 1197 let group: BackupGroup = path.parse()?;
27c9affb 1198 api_datastore_latest_snapshot(&client, repo.store(), group).await?
d5c34d98 1199 } else {
a67f7d0a 1200 let snapshot: BackupDir = path.parse()?;
86eda3eb
DM
1201 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
1202 };
9f912493 1203
d5c34d98 1204 let target = tools::required_string_param(&param, "target")?;
bf125261 1205 let target = if target == "-" { None } else { Some(target) };
2ae7d196 1206
f28d9088 1207 let (keyfile, _crypt_mode) = keyfile_parameters(&param)?;
2ae7d196 1208
86eda3eb
DM
1209 let crypt_config = match keyfile {
1210 None => None,
1211 Some(path) => {
9696f519 1212 let (key, _) = load_and_decrypt_key(&path, &key::get_encryption_key_password)?;
86eda3eb
DM
1213 Some(Arc::new(CryptConfig::new(key)?))
1214 }
1215 };
d5c34d98 1216
296c50ba
DM
1217 let client = BackupReader::start(
1218 client,
1219 crypt_config.clone(),
1220 repo.store(),
1221 &backup_type,
1222 &backup_id,
1223 backup_time,
1224 true,
1225 ).await?;
86eda3eb 1226
f06b820a 1227 let manifest = client.download_manifest().await?;
02fcf372 1228
dc155e9b
TL
1229 let (archive_name, archive_type) = parse_archive_type(archive_name);
1230
1231 if archive_name == MANIFEST_BLOB_NAME {
f06b820a 1232 let backup_index_data = manifest.into_json().to_string();
02fcf372 1233 if let Some(target) = target {
feaa1ad3 1234 replace_file(target, backup_index_data.as_bytes(), CreateOptions::new())?;
02fcf372
DM
1235 } else {
1236 let stdout = std::io::stdout();
1237 let mut writer = stdout.lock();
296c50ba 1238 writer.write_all(backup_index_data.as_bytes())
02fcf372
DM
1239 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1240 }
1241
dc155e9b 1242 } else if archive_type == ArchiveType::Blob {
d2267b11 1243
dc155e9b 1244 let mut reader = client.download_blob(&manifest, &archive_name).await?;
f8100e96 1245
bf125261 1246 if let Some(target) = target {
0d986280
DM
1247 let mut writer = std::fs::OpenOptions::new()
1248 .write(true)
1249 .create(true)
1250 .create_new(true)
1251 .open(target)
1252 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
1253 std::io::copy(&mut reader, &mut writer)?;
bf125261
DM
1254 } else {
1255 let stdout = std::io::stdout();
1256 let mut writer = stdout.lock();
0d986280 1257 std::io::copy(&mut reader, &mut writer)
bf125261
DM
1258 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1259 }
f8100e96 1260
dc155e9b 1261 } else if archive_type == ArchiveType::DynamicIndex {
86eda3eb 1262
dc155e9b 1263 let index = client.download_dynamic_index(&manifest, &archive_name).await?;
df65bd3d 1264
f4bf7dfc
DM
1265 let most_used = index.find_most_used_chunks(8);
1266
1267 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1268
afb4cd28 1269 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
86eda3eb 1270
bf125261 1271 if let Some(target) = target {
c443f58b
WB
1272 proxmox_backup::pxar::extract_archive(
1273 pxar::decoder::Decoder::from_std(reader)?,
1274 Path::new(target),
1275 &[],
5444fa94 1276 proxmox_backup::pxar::Flags::DEFAULT,
c443f58b
WB
1277 allow_existing_dirs,
1278 |path| {
1279 if verbose {
1280 println!("{:?}", path);
1281 }
1282 },
1283 )
1284 .map_err(|err| format_err!("error extracting archive - {}", err))?;
bf125261 1285 } else {
88892ea8
DM
1286 let mut writer = std::fs::OpenOptions::new()
1287 .write(true)
1288 .open("/dev/stdout")
1289 .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?;
afb4cd28 1290
bf125261
DM
1291 std::io::copy(&mut reader, &mut writer)
1292 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1293 }
dc155e9b 1294 } else if archive_type == ArchiveType::FixedIndex {
afb4cd28 1295
dc155e9b 1296 let index = client.download_fixed_index(&manifest, &archive_name).await?;
df65bd3d 1297
88892ea8
DM
1298 let mut writer = if let Some(target) = target {
1299 std::fs::OpenOptions::new()
bf125261
DM
1300 .write(true)
1301 .create(true)
1302 .create_new(true)
1303 .open(target)
88892ea8 1304 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?
bf125261 1305 } else {
88892ea8
DM
1306 std::fs::OpenOptions::new()
1307 .write(true)
1308 .open("/dev/stdout")
1309 .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?
1310 };
afb4cd28 1311
8e6e18b7 1312 dump_image(client.clone(), crypt_config.clone(), index, &mut writer, verbose).await?;
3031e44c 1313 }
fef44d4f
DM
1314
1315 Ok(Value::Null)
45db6f89
DM
1316}
1317
a47a02ae
DM
1318#[api(
1319 input: {
1320 properties: {
1321 repository: {
1322 schema: REPO_URL_SCHEMA,
1323 optional: true,
1324 },
1325 snapshot: {
1326 type: String,
1327 description: "Group/Snapshot path.",
1328 },
1329 logfile: {
1330 type: String,
1331 description: "The path to the log file you want to upload.",
1332 },
1333 keyfile: {
1334 schema: KEYFILE_SCHEMA,
1335 optional: true,
1336 },
96ee8577
WB
1337 encryption: {
1338 schema: ENCRYPTION_SCHEMA,
1339 optional: true,
1340 },
a47a02ae
DM
1341 }
1342 }
1343)]
1344/// Upload backup log file.
1345async fn upload_log(param: Value) -> Result<Value, Error> {
ec34f7eb
DM
1346
1347 let logfile = tools::required_string_param(&param, "logfile")?;
1348 let repo = extract_repository_from_value(&param)?;
1349
1350 let snapshot = tools::required_string_param(&param, "snapshot")?;
a67f7d0a 1351 let snapshot: BackupDir = snapshot.parse()?;
ec34f7eb 1352
d59dbeca 1353 let mut client = connect(repo.host(), repo.user())?;
ec34f7eb 1354
f28d9088 1355 let (keyfile, crypt_mode) = keyfile_parameters(&param)?;
ec34f7eb
DM
1356
1357 let crypt_config = match keyfile {
1358 None => None,
1359 Some(path) => {
9696f519 1360 let (key, _created) = load_and_decrypt_key(&path, &key::get_encryption_key_password)?;
ec34f7eb 1361 let crypt_config = CryptConfig::new(key)?;
9025312a 1362 Some(Arc::new(crypt_config))
ec34f7eb
DM
1363 }
1364 };
1365
e18a6c9e 1366 let data = file_get_contents(logfile)?;
ec34f7eb 1367
f28d9088
WB
1368 let blob = match crypt_mode {
1369 CryptMode::None => DataBlob::encode(&data, None, true)?,
1370 CryptMode::Encrypt => {
1371 DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?
1372 }
1373 CryptMode::SignOnly => DataBlob::create_signed(
1374 &data,
1375 crypt_config
1376 .ok_or_else(|| format_err!("cannot sign without crypt config"))?
1377 .as_ref(),
1378 true,
1379 )?,
1380 };
ec34f7eb
DM
1381
1382 let raw_data = blob.into_inner();
1383
1384 let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store());
1385
1386 let args = json!({
1387 "backup-type": snapshot.group().backup_type(),
1388 "backup-id": snapshot.group().backup_id(),
1389 "backup-time": snapshot.backup_time().timestamp(),
1390 });
1391
1392 let body = hyper::Body::from(raw_data);
1393
8a8a4703 1394 client.upload("application/octet-stream", body, &path, Some(args)).await
ec34f7eb
DM
1395}
1396
032d3ad8
DM
1397const API_METHOD_PRUNE: ApiMethod = ApiMethod::new(
1398 &ApiHandler::Async(&prune),
1399 &ObjectSchema::new(
1400 "Prune a backup repository.",
1401 &proxmox_backup::add_common_prune_prameters!([
1402 ("dry-run", true, &BooleanSchema::new(
1403 "Just show what prune would do, but do not delete anything.")
1404 .schema()),
1405 ("group", false, &StringSchema::new("Backup group.").schema()),
1406 ], [
1407 ("output-format", true, &OUTPUT_FORMAT),
c48aa39f
DM
1408 (
1409 "quiet",
1410 true,
1411 &BooleanSchema::new("Minimal output - only show removals.")
1412 .schema()
1413 ),
032d3ad8
DM
1414 ("repository", true, &REPO_URL_SCHEMA),
1415 ])
1416 )
1417);
1418
1419fn prune<'a>(
1420 param: Value,
1421 _info: &ApiMethod,
1422 _rpcenv: &'a mut dyn RpcEnvironment,
1423) -> proxmox::api::ApiFuture<'a> {
1424 async move {
1425 prune_async(param).await
1426 }.boxed()
1427}
83b7db02 1428
032d3ad8 1429async fn prune_async(mut param: Value) -> Result<Value, Error> {
2665cef7 1430 let repo = extract_repository_from_value(&param)?;
83b7db02 1431
d59dbeca 1432 let mut client = connect(repo.host(), repo.user())?;
83b7db02 1433
d0a03d40 1434 let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
83b7db02 1435
9fdc3ef4 1436 let group = tools::required_string_param(&param, "group")?;
d6d3b353 1437 let group: BackupGroup = group.parse()?;
c2043614
DM
1438
1439 let output_format = get_output_format(&param);
9fdc3ef4 1440
c48aa39f
DM
1441 let quiet = param["quiet"].as_bool().unwrap_or(false);
1442
ea7a7ef2
DM
1443 param.as_object_mut().unwrap().remove("repository");
1444 param.as_object_mut().unwrap().remove("group");
163e9bbe 1445 param.as_object_mut().unwrap().remove("output-format");
c48aa39f 1446 param.as_object_mut().unwrap().remove("quiet");
ea7a7ef2
DM
1447
1448 param["backup-type"] = group.backup_type().into();
1449 param["backup-id"] = group.backup_id().into();
83b7db02 1450
db1e061d 1451 let mut result = client.post(&path, Some(param)).await?;
74fa81b8 1452
87c42375 1453 record_repository(&repo);
3b03abfe 1454
db1e061d
DM
1455 let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> {
1456 let item: PruneListItem = serde_json::from_value(record.to_owned())?;
1457 let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time);
1458 Ok(snapshot.relative_path().to_str().unwrap().to_owned())
1459 };
1460
c48aa39f
DM
1461 let render_prune_action = |v: &Value, _record: &Value| -> Result<String, Error> {
1462 Ok(match v.as_bool() {
1463 Some(true) => "keep",
1464 Some(false) => "remove",
1465 None => "unknown",
1466 }.to_string())
1467 };
1468
db1e061d
DM
1469 let options = default_table_format_options()
1470 .sortby("backup-type", false)
1471 .sortby("backup-id", false)
1472 .sortby("backup-time", false)
1473 .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot"))
74f7240b 1474 .column(ColumnConfig::new("backup-time").renderer(tools::format::render_epoch).header("date"))
c48aa39f 1475 .column(ColumnConfig::new("keep").renderer(render_prune_action).header("action"))
db1e061d
DM
1476 ;
1477
1478 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_PRUNE;
1479
1480 let mut data = result["data"].take();
1481
c48aa39f
DM
1482 if quiet {
1483 let list: Vec<Value> = data.as_array().unwrap().iter().filter(|item| {
1484 item["keep"].as_bool() == Some(false)
1485 }).map(|v| v.clone()).collect();
1486 data = list.into();
1487 }
1488
db1e061d 1489 format_and_print_result_full(&mut data, info, &output_format, &options);
d0a03d40 1490
43a406fd 1491 Ok(Value::Null)
83b7db02
DM
1492}
1493
a47a02ae
DM
1494#[api(
1495 input: {
1496 properties: {
1497 repository: {
1498 schema: REPO_URL_SCHEMA,
1499 optional: true,
1500 },
1501 "output-format": {
1502 schema: OUTPUT_FORMAT,
1503 optional: true,
1504 },
1505 }
1506 }
1507)]
1508/// Get repository status.
1509async fn status(param: Value) -> Result<Value, Error> {
34a816cc
DM
1510
1511 let repo = extract_repository_from_value(&param)?;
1512
c2043614 1513 let output_format = get_output_format(&param);
34a816cc 1514
d59dbeca 1515 let client = connect(repo.host(), repo.user())?;
34a816cc
DM
1516
1517 let path = format!("api2/json/admin/datastore/{}/status", repo.store());
1518
1dc117bb 1519 let mut result = client.get(&path, None).await?;
390c5bdd 1520 let mut data = result["data"].take();
34a816cc
DM
1521
1522 record_repository(&repo);
1523
390c5bdd
DM
1524 let render_total_percentage = |v: &Value, record: &Value| -> Result<String, Error> {
1525 let v = v.as_u64().unwrap();
1526 let total = record["total"].as_u64().unwrap();
1527 let roundup = total/200;
1528 let per = ((v+roundup)*100)/total;
e23f5863
DM
1529 let info = format!(" ({} %)", per);
1530 Ok(format!("{} {:>8}", v, info))
390c5bdd 1531 };
1dc117bb 1532
c2043614 1533 let options = default_table_format_options()
be2425ff 1534 .noheader(true)
e23f5863 1535 .column(ColumnConfig::new("total").renderer(render_total_percentage))
390c5bdd
DM
1536 .column(ColumnConfig::new("used").renderer(render_total_percentage))
1537 .column(ColumnConfig::new("avail").renderer(render_total_percentage));
34a816cc 1538
ea5f547f 1539 let schema = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_STATUS;
390c5bdd
DM
1540
1541 format_and_print_result_full(&mut data, schema, &output_format, &options);
34a816cc
DM
1542
1543 Ok(Value::Null)
1544}
1545
5a2df000 1546// like get, but simply ignore errors and return Null instead
e9722f8b 1547async fn try_get(repo: &BackupRepository, url: &str) -> Value {
024f11bb 1548
a05c0c6f 1549 let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
d1c65727 1550 let password = std::env::var(ENV_VAR_PBS_PASSWORD).ok();
a05c0c6f 1551
d59dbeca 1552 let options = HttpClientOptions::new()
5030b7ce 1553 .prefix(Some("proxmox-backup".to_string()))
d1c65727 1554 .password(password)
d59dbeca 1555 .interactive(false)
a05c0c6f 1556 .fingerprint(fingerprint)
5a74756c 1557 .fingerprint_cache(true)
d59dbeca
DM
1558 .ticket_cache(true);
1559
1560 let client = match HttpClient::new(repo.host(), repo.user(), options) {
45cdce06
DM
1561 Ok(v) => v,
1562 _ => return Value::Null,
1563 };
b2388518 1564
e9722f8b 1565 let mut resp = match client.get(url, None).await {
b2388518
DM
1566 Ok(v) => v,
1567 _ => return Value::Null,
1568 };
1569
1570 if let Some(map) = resp.as_object_mut() {
1571 if let Some(data) = map.remove("data") {
1572 return data;
1573 }
1574 }
1575 Value::Null
1576}
1577
b2388518 1578fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
3f06d6fb 1579 proxmox_backup::tools::runtime::main(async { complete_backup_group_do(param).await })
e9722f8b
WB
1580}
1581
1582async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> {
024f11bb 1583
b2388518
DM
1584 let mut result = vec![];
1585
2665cef7 1586 let repo = match extract_repository_from_map(param) {
b2388518 1587 Some(v) => v,
024f11bb
DM
1588 _ => return result,
1589 };
1590
b2388518
DM
1591 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
1592
e9722f8b 1593 let data = try_get(&repo, &path).await;
b2388518
DM
1594
1595 if let Some(list) = data.as_array() {
024f11bb 1596 for item in list {
98f0b972
DM
1597 if let (Some(backup_id), Some(backup_type)) =
1598 (item["backup-id"].as_str(), item["backup-type"].as_str())
1599 {
1600 result.push(format!("{}/{}", backup_type, backup_id));
024f11bb
DM
1601 }
1602 }
1603 }
1604
1605 result
1606}
1607
43abba4b 1608pub fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
3f06d6fb 1609 proxmox_backup::tools::runtime::main(async { complete_group_or_snapshot_do(arg, param).await })
e9722f8b
WB
1610}
1611
1612async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
b2388518 1613
b2388518 1614 if arg.matches('/').count() < 2 {
e9722f8b 1615 let groups = complete_backup_group_do(param).await;
543a260f 1616 let mut result = vec![];
b2388518
DM
1617 for group in groups {
1618 result.push(group.to_string());
1619 result.push(format!("{}/", group));
1620 }
1621 return result;
1622 }
1623
e9722f8b 1624 complete_backup_snapshot_do(param).await
543a260f 1625}
b2388518 1626
3fb53e07 1627fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
3f06d6fb 1628 proxmox_backup::tools::runtime::main(async { complete_backup_snapshot_do(param).await })
e9722f8b
WB
1629}
1630
1631async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> {
543a260f
DM
1632
1633 let mut result = vec![];
1634
1635 let repo = match extract_repository_from_map(param) {
1636 Some(v) => v,
1637 _ => return result,
1638 };
1639
1640 let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
b2388518 1641
e9722f8b 1642 let data = try_get(&repo, &path).await;
b2388518
DM
1643
1644 if let Some(list) = data.as_array() {
1645 for item in list {
1646 if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
1647 (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64())
1648 {
1649 let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
1650 result.push(snapshot.relative_path().to_str().unwrap().to_owned());
1651 }
1652 }
1653 }
1654
1655 result
1656}
1657
45db6f89 1658fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
3f06d6fb 1659 proxmox_backup::tools::runtime::main(async { complete_server_file_name_do(param).await })
e9722f8b
WB
1660}
1661
1662async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> {
08dc340a
DM
1663
1664 let mut result = vec![];
1665
2665cef7 1666 let repo = match extract_repository_from_map(param) {
08dc340a
DM
1667 Some(v) => v,
1668 _ => return result,
1669 };
1670
a67f7d0a 1671 let snapshot: BackupDir = match param.get("snapshot") {
08dc340a 1672 Some(path) => {
a67f7d0a 1673 match path.parse() {
08dc340a
DM
1674 Ok(v) => v,
1675 _ => return result,
1676 }
1677 }
1678 _ => return result,
1679 };
1680
1681 let query = tools::json_object_to_query(json!({
1682 "backup-type": snapshot.group().backup_type(),
1683 "backup-id": snapshot.group().backup_id(),
1684 "backup-time": snapshot.backup_time().timestamp(),
1685 })).unwrap();
1686
1687 let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query);
1688
e9722f8b 1689 let data = try_get(&repo, &path).await;
08dc340a
DM
1690
1691 if let Some(list) = data.as_array() {
1692 for item in list {
c4f025eb 1693 if let Some(filename) = item["filename"].as_str() {
08dc340a
DM
1694 result.push(filename.to_owned());
1695 }
1696 }
1697 }
1698
45db6f89
DM
1699 result
1700}
1701
1702fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
52c171e4 1703 complete_server_file_name(arg, param)
e9722f8b 1704 .iter()
4939255f 1705 .map(|v| tools::format::strip_server_file_expenstion(&v))
e9722f8b 1706 .collect()
08dc340a
DM
1707}
1708
43abba4b 1709pub fn complete_pxar_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
0ec9e1b0
DM
1710 complete_server_file_name(arg, param)
1711 .iter()
1712 .filter_map(|v| {
4939255f 1713 let name = tools::format::strip_server_file_expenstion(&v);
0ec9e1b0
DM
1714 if name.ends_with(".pxar") {
1715 Some(name)
1716 } else {
1717 None
1718 }
1719 })
1720 .collect()
1721}
1722
49811347
DM
1723fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
1724
1725 let mut result = vec![];
1726
1727 let mut size = 64;
1728 loop {
1729 result.push(size.to_string());
11377a47 1730 size *= 2;
49811347
DM
1731 if size > 4096 { break; }
1732 }
1733
1734 result
1735}
1736
9f46c7de
DM
1737fn master_pubkey_path() -> Result<PathBuf, Error> {
1738 let base = BaseDirectories::with_prefix("proxmox-backup")?;
1739
1740 // usually $HOME/.config/proxmox-backup/master-public.pem
1741 let path = base.place_config_file("master-public.pem")?;
1742
1743 Ok(path)
1744}
1745
c443f58b
WB
1746use proxmox_backup::client::RemoteChunkReader;
1747/// This is a workaround until we have cleaned up the chunk/reader/... infrastructure for better
1748/// async use!
1749///
1750/// Ideally BufferedDynamicReader gets replaced so the LruCache maps to `BroadcastFuture<Chunk>`,
1751/// so that we can properly access it from multiple threads simultaneously while not issuing
1752/// duplicate simultaneous reads over http.
43abba4b 1753pub struct BufferedDynamicReadAt {
c443f58b
WB
1754 inner: Mutex<BufferedDynamicReader<RemoteChunkReader>>,
1755}
1756
1757impl BufferedDynamicReadAt {
1758 fn new(inner: BufferedDynamicReader<RemoteChunkReader>) -> Self {
1759 Self {
1760 inner: Mutex::new(inner),
1761 }
1762 }
1763}
1764
a6f87283
WB
1765impl ReadAt for BufferedDynamicReadAt {
1766 fn start_read_at<'a>(
1767 self: Pin<&'a Self>,
c443f58b 1768 _cx: &mut Context,
a6f87283 1769 buf: &'a mut [u8],
c443f58b 1770 offset: u64,
a6f87283 1771 ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> {
c443f58b 1772 use std::io::Read;
a6f87283 1773 MaybeReady::Ready(tokio::task::block_in_place(move || {
c443f58b
WB
1774 let mut reader = self.inner.lock().unwrap();
1775 reader.seek(SeekFrom::Start(offset))?;
a6f87283
WB
1776 Ok(reader.read(buf)?)
1777 }))
1778 }
1779
1780 fn poll_complete<'a>(
1781 self: Pin<&'a Self>,
1782 _op: ReadAtOperation<'a>,
1783 ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> {
1784 panic!("LocalDynamicReadAt::start_read_at returned Pending");
c443f58b
WB
1785 }
1786}
1787
f2401311 1788fn main() {
33d64b81 1789
255f378a 1790 let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP)
49fddd98 1791 .arg_param(&["backupspec"])
d0a03d40 1792 .completion_cb("repository", complete_repository)
49811347 1793 .completion_cb("backupspec", complete_backup_source)
6d0983db 1794 .completion_cb("keyfile", tools::complete_file_name)
49811347 1795 .completion_cb("chunk-size", complete_chunk_size);
f8838fe9 1796
caea8d61
DM
1797 let benchmark_cmd_def = CliCommand::new(&API_METHOD_BENCHMARK)
1798 .completion_cb("repository", complete_repository)
1799 .completion_cb("keyfile", tools::complete_file_name);
1800
255f378a 1801 let upload_log_cmd_def = CliCommand::new(&API_METHOD_UPLOAD_LOG)
49fddd98 1802 .arg_param(&["snapshot", "logfile"])
543a260f 1803 .completion_cb("snapshot", complete_backup_snapshot)
ec34f7eb
DM
1804 .completion_cb("logfile", tools::complete_file_name)
1805 .completion_cb("keyfile", tools::complete_file_name)
1806 .completion_cb("repository", complete_repository);
1807
255f378a 1808 let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS)
d0a03d40 1809 .completion_cb("repository", complete_repository);
41c039e1 1810
255f378a 1811 let snapshots_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOTS)
49fddd98 1812 .arg_param(&["group"])
024f11bb 1813 .completion_cb("group", complete_backup_group)
d0a03d40 1814 .completion_cb("repository", complete_repository);
184f17af 1815
255f378a 1816 let forget_cmd_def = CliCommand::new(&API_METHOD_FORGET_SNAPSHOTS)
49fddd98 1817 .arg_param(&["snapshot"])
b2388518 1818 .completion_cb("repository", complete_repository)
543a260f 1819 .completion_cb("snapshot", complete_backup_snapshot);
6f62c924 1820
255f378a 1821 let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
d0a03d40 1822 .completion_cb("repository", complete_repository);
8cc0d6af 1823
255f378a 1824 let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE)
49fddd98 1825 .arg_param(&["snapshot", "archive-name", "target"])
b2388518 1826 .completion_cb("repository", complete_repository)
08dc340a
DM
1827 .completion_cb("snapshot", complete_group_or_snapshot)
1828 .completion_cb("archive-name", complete_archive_name)
1829 .completion_cb("target", tools::complete_file_name);
9f912493 1830
255f378a 1831 let files_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOT_FILES)
49fddd98 1832 .arg_param(&["snapshot"])
52c171e4 1833 .completion_cb("repository", complete_repository)
543a260f 1834 .completion_cb("snapshot", complete_backup_snapshot);
52c171e4 1835
255f378a 1836 let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE)
49fddd98 1837 .arg_param(&["group"])
9fdc3ef4 1838 .completion_cb("group", complete_backup_group)
d0a03d40 1839 .completion_cb("repository", complete_repository);
9f912493 1840
255f378a 1841 let status_cmd_def = CliCommand::new(&API_METHOD_STATUS)
34a816cc
DM
1842 .completion_cb("repository", complete_repository);
1843
255f378a 1844 let login_cmd_def = CliCommand::new(&API_METHOD_API_LOGIN)
e240d8be
DM
1845 .completion_cb("repository", complete_repository);
1846
255f378a 1847 let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT)
e240d8be 1848 .completion_cb("repository", complete_repository);
32efac1c 1849
41c039e1 1850 let cmd_def = CliCommandMap::new()
48ef3c33
DM
1851 .insert("backup", backup_cmd_def)
1852 .insert("upload-log", upload_log_cmd_def)
1853 .insert("forget", forget_cmd_def)
1854 .insert("garbage-collect", garbage_collect_cmd_def)
1855 .insert("list", list_cmd_def)
1856 .insert("login", login_cmd_def)
1857 .insert("logout", logout_cmd_def)
1858 .insert("prune", prune_cmd_def)
1859 .insert("restore", restore_cmd_def)
1860 .insert("snapshots", snapshots_cmd_def)
1861 .insert("files", files_cmd_def)
1862 .insert("status", status_cmd_def)
9696f519 1863 .insert("key", key::cli())
43abba4b 1864 .insert("mount", mount_cmd_def())
5830c205 1865 .insert("catalog", catalog_mgmt_cli())
caea8d61
DM
1866 .insert("task", task_mgmt_cli())
1867 .insert("benchmark", benchmark_cmd_def);
48ef3c33 1868
7b22acd0
DM
1869 let rpcenv = CliEnvironment::new();
1870 run_cli_command(cmd_def, rpcenv, Some(|future| {
d08bc483
DM
1871 proxmox_backup::tools::runtime::main(future)
1872 }));
ff5d3707 1873}