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