]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-client.rs
pbs-datastore/prune: make PruneOptions an api type
[proxmox-backup.git] / src / bin / proxmox-backup-client.rs
CommitLineData
f1a83e97 1use std::collections::HashSet;
0351f23b 2use std::io::{self, Read, 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};
c443f58b 9use futures::future::FutureExt;
c443f58b 10use futures::stream::{StreamExt, TryStreamExt};
c443f58b 11use serde_json::{json, Value};
c443f58b 12use tokio::sync::mpsc;
7c667013 13use tokio_stream::wrappers::ReceiverStream;
c443f58b 14use xdg::BaseDirectories;
2761d6a4 15
c443f58b 16use pathpatterns::{MatchEntry, MatchType, PatternFlag};
6a7be83e
DM
17use proxmox::{
18 tools::{
19 time::{strftime_local, epoch_i64},
ff8945fd 20 fs::{file_get_json, replace_file, CreateOptions, image_size},
6a7be83e
DM
21 },
22 api::{
23 api,
24 ApiHandler,
25 ApiMethod,
26 RpcEnvironment,
27 schema::*,
28 cli::*,
29 },
30};
a6f87283 31use pxar::accessor::{MaybeReady, ReadAt, ReadAtOperation};
ff5d3707 32
f323e906
WB
33use pbs_datastore::catalog::BackupCatalogWriter;
34
f1d76ecf
DC
35use proxmox_backup::tools::{
36 self,
37 StdChannelWriter,
38 TokioWriterAdapter,
39};
bbf9e7e9 40use proxmox_backup::api2::types::*;
e39974af 41use proxmox_backup::api2::version;
151c6ce2 42use proxmox_backup::client::*;
4d16badf
WB
43use proxmox_backup::backup::{
44 archive_type,
0351f23b 45 decrypt_key,
8acfd15d 46 rsa_encrypt_key_config,
4d16badf
WB
47 verify_chunk_size,
48 ArchiveType,
8e6e18b7 49 AsyncReadChunk,
4d16badf
WB
50 BackupDir,
51 BackupGroup,
52 BackupManifest,
53 BufferedDynamicReader,
f28d9088 54 CATALOG_NAME,
4d16badf
WB
55 CatalogReader,
56 CatalogWriter,
4d16badf
WB
57 ChunkStream,
58 CryptConfig,
f28d9088 59 CryptMode,
4d16badf 60 DynamicIndexReader,
9990af30 61 ENCRYPTED_KEY_BLOB_NAME,
4d16badf
WB
62 FixedChunkStream,
63 FixedIndexReader,
8acfd15d 64 KeyConfig,
4d16badf 65 IndexFile,
4d16badf 66 MANIFEST_BLOB_NAME,
4d16badf
WB
67 Shell,
68};
ae0be2dd 69
caea8d61
DM
70mod proxmox_backup_client;
71use proxmox_backup_client::*;
72
ff8945fd
SR
73pub mod proxmox_client_tools;
74use proxmox_client_tools::{
75 complete_archive_name, complete_auth_id, complete_backup_group, complete_backup_snapshot,
76 complete_backup_source, complete_chunk_size, complete_group_or_snapshot,
77 complete_img_archive_name, complete_pxar_archive_name, complete_repository, connect,
78 extract_repository_from_value,
79 key_source::{
80 crypto_parameters, format_key_source, get_encryption_key_password, KEYFD_SCHEMA,
81 KEYFILE_SCHEMA, MASTER_PUBKEY_FD_SCHEMA, MASTER_PUBKEY_FILE_SCHEMA,
82 },
83 CHUNK_SIZE_SCHEMA, REPO_URL_SCHEMA,
84};
2665cef7 85
d0a03d40
DM
86fn record_repository(repo: &BackupRepository) {
87
88 let base = match BaseDirectories::with_prefix("proxmox-backup") {
89 Ok(v) => v,
90 _ => return,
91 };
92
93 // usually $HOME/.cache/proxmox-backup/repo-list
94 let path = match base.place_cache_file("repo-list") {
95 Ok(v) => v,
96 _ => return,
97 };
98
11377a47 99 let mut data = file_get_json(&path, None).unwrap_or_else(|_| json!({}));
d0a03d40
DM
100
101 let repo = repo.to_string();
102
103 data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 };
104
105 let mut map = serde_json::map::Map::new();
106
107 loop {
108 let mut max_used = 0;
109 let mut max_repo = None;
110 for (repo, count) in data.as_object().unwrap() {
111 if map.contains_key(repo) { continue; }
112 if let Some(count) = count.as_i64() {
113 if count > max_used {
114 max_used = count;
115 max_repo = Some(repo);
116 }
117 }
118 }
119 if let Some(repo) = max_repo {
120 map.insert(repo.to_owned(), json!(max_used));
121 } else {
122 break;
123 }
124 if map.len() > 10 { // store max. 10 repos
125 break;
126 }
127 }
128
129 let new_data = json!(map);
130
feaa1ad3 131 let _ = replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new());
d0a03d40
DM
132}
133
42af4b8f
DM
134async fn api_datastore_list_snapshots(
135 client: &HttpClient,
136 store: &str,
137 group: Option<BackupGroup>,
f24fc116 138) -> Result<Value, Error> {
42af4b8f
DM
139
140 let path = format!("api2/json/admin/datastore/{}/snapshots", store);
141
142 let mut args = json!({});
143 if let Some(group) = group {
144 args["backup-type"] = group.backup_type().into();
145 args["backup-id"] = group.backup_id().into();
146 }
147
148 let mut result = client.get(&path, Some(args)).await?;
149
f24fc116 150 Ok(result["data"].take())
42af4b8f
DM
151}
152
43abba4b 153pub async fn api_datastore_latest_snapshot(
27c9affb
DM
154 client: &HttpClient,
155 store: &str,
156 group: BackupGroup,
6a7be83e 157) -> Result<(String, String, i64), Error> {
27c9affb 158
f24fc116
DM
159 let list = api_datastore_list_snapshots(client, store, Some(group.clone())).await?;
160 let mut list: Vec<SnapshotListItem> = serde_json::from_value(list)?;
27c9affb
DM
161
162 if list.is_empty() {
163 bail!("backup group {:?} does not contain any snapshots.", group.group_path());
164 }
165
166 list.sort_unstable_by(|a, b| b.backup_time.cmp(&a.backup_time));
167
6a7be83e 168 let backup_time = list[0].backup_time;
27c9affb
DM
169
170 Ok((group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time))
171}
172
e9722f8b 173async fn backup_directory<P: AsRef<Path>>(
cf9271e2 174 client: &BackupWriter,
17d6979a 175 dir_path: P,
247cdbce 176 archive_name: &str,
36898ffc 177 chunk_size: Option<usize>,
f1d76ecf 178 catalog: Arc<Mutex<CatalogWriter<TokioWriterAdapter<StdChannelWriter>>>>,
77486a60 179 pxar_create_options: proxmox_backup::pxar::PxarCreateOptions,
e43b9175 180 upload_options: UploadOptions,
2c3891d1 181) -> Result<BackupStats, Error> {
33d64b81 182
6fc053ed
CE
183 let pxar_stream = PxarBackupStream::open(
184 dir_path.as_ref(),
6fc053ed 185 catalog,
77486a60 186 pxar_create_options,
6fc053ed 187 )?;
e9722f8b 188 let mut chunk_stream = ChunkStream::new(pxar_stream, chunk_size);
ff3d3100 189
0bfcea6a 190 let (tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks
5e7a09be 191
7c667013 192 let stream = ReceiverStream::new(rx)
e9722f8b 193 .map_err(Error::from);
17d6979a 194
c4ff3dce 195 // spawn chunker inside a separate task so that it can run parallel
e9722f8b 196 tokio::spawn(async move {
db0cb9ce
WB
197 while let Some(v) = chunk_stream.next().await {
198 let _ = tx.send(v).await;
199 }
e9722f8b 200 });
17d6979a 201
e43b9175
FG
202 if upload_options.fixed_size.is_some() {
203 bail!("cannot backup directory with fixed chunk size!");
204 }
205
e9722f8b 206 let stats = client
e43b9175 207 .upload_stream(archive_name, stream, upload_options)
e9722f8b 208 .await?;
bcd879cf 209
2c3891d1 210 Ok(stats)
bcd879cf
DM
211}
212
e9722f8b 213async fn backup_image<P: AsRef<Path>>(
cf9271e2 214 client: &BackupWriter,
6af905c1
DM
215 image_path: P,
216 archive_name: &str,
36898ffc 217 chunk_size: Option<usize>,
e43b9175 218 upload_options: UploadOptions,
2c3891d1 219) -> Result<BackupStats, Error> {
6af905c1 220
6af905c1
DM
221 let path = image_path.as_ref().to_owned();
222
e9722f8b 223 let file = tokio::fs::File::open(path).await?;
6af905c1 224
db0cb9ce 225 let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new())
6af905c1
DM
226 .map_err(Error::from);
227
36898ffc 228 let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024));
6af905c1 229
e43b9175
FG
230 if upload_options.fixed_size.is_none() {
231 bail!("cannot backup image with dynamic chunk size!");
232 }
233
e9722f8b 234 let stats = client
e43b9175 235 .upload_stream(archive_name, stream, upload_options)
e9722f8b 236 .await?;
6af905c1 237
2c3891d1 238 Ok(stats)
6af905c1
DM
239}
240
a47a02ae
DM
241#[api(
242 input: {
243 properties: {
244 repository: {
245 schema: REPO_URL_SCHEMA,
246 optional: true,
247 },
248 "output-format": {
249 schema: OUTPUT_FORMAT,
250 optional: true,
251 },
252 }
253 }
254)]
255/// List backup groups.
256async fn list_backup_groups(param: Value) -> Result<Value, Error> {
812c6f87 257
c81b2b7c
DM
258 let output_format = get_output_format(&param);
259
2665cef7 260 let repo = extract_repository_from_value(&param)?;
812c6f87 261
f3fde36b 262 let client = connect(&repo)?;
812c6f87 263
d0a03d40 264 let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
812c6f87 265
8a8a4703 266 let mut result = client.get(&path, None).await?;
812c6f87 267
d0a03d40
DM
268 record_repository(&repo);
269
c81b2b7c
DM
270 let render_group_path = |_v: &Value, record: &Value| -> Result<String, Error> {
271 let item: GroupListItem = serde_json::from_value(record.to_owned())?;
272 let group = BackupGroup::new(item.backup_type, item.backup_id);
273 Ok(group.group_path().to_str().unwrap().to_owned())
274 };
812c6f87 275
18deda40
DM
276 let render_last_backup = |_v: &Value, record: &Value| -> Result<String, Error> {
277 let item: GroupListItem = serde_json::from_value(record.to_owned())?;
e0e5b442 278 let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.last_backup)?;
18deda40 279 Ok(snapshot.relative_path().to_str().unwrap().to_owned())
c81b2b7c 280 };
812c6f87 281
c81b2b7c
DM
282 let render_files = |_v: &Value, record: &Value| -> Result<String, Error> {
283 let item: GroupListItem = serde_json::from_value(record.to_owned())?;
770a36e5 284 Ok(pbs_tools::format::render_backup_file_list(&item.files))
c81b2b7c 285 };
812c6f87 286
c81b2b7c
DM
287 let options = default_table_format_options()
288 .sortby("backup-type", false)
289 .sortby("backup-id", false)
290 .column(ColumnConfig::new("backup-id").renderer(render_group_path).header("group"))
18deda40
DM
291 .column(
292 ColumnConfig::new("last-backup")
293 .renderer(render_last_backup)
294 .header("last snapshot")
295 .right_align(false)
296 )
c81b2b7c
DM
297 .column(ColumnConfig::new("backup-count"))
298 .column(ColumnConfig::new("files").renderer(render_files));
ad20d198 299
c81b2b7c 300 let mut data: Value = result["data"].take();
ad20d198 301
b2362a12 302 let return_type = &proxmox_backup::api2::admin::datastore::API_METHOD_LIST_GROUPS.returns;
812c6f87 303
b2362a12 304 format_and_print_result_full(&mut data, return_type, &output_format, &options);
34a816cc 305
812c6f87
DM
306 Ok(Value::Null)
307}
308
344add38
DW
309#[api(
310 input: {
311 properties: {
312 repository: {
313 schema: REPO_URL_SCHEMA,
314 optional: true,
315 },
316 group: {
317 type: String,
318 description: "Backup group.",
319 },
320 "new-owner": {
e6dc35ac 321 type: Authid,
344add38
DW
322 },
323 }
324 }
325)]
326/// Change owner of a backup group
327async fn change_backup_owner(group: String, mut param: Value) -> Result<(), Error> {
328
329 let repo = extract_repository_from_value(&param)?;
330
f3fde36b 331 let mut client = connect(&repo)?;
344add38
DW
332
333 param.as_object_mut().unwrap().remove("repository");
334
335 let group: BackupGroup = group.parse()?;
336
337 param["backup-type"] = group.backup_type().into();
338 param["backup-id"] = group.backup_id().into();
339
340 let path = format!("api2/json/admin/datastore/{}/change-owner", repo.store());
341 client.post(&path, Some(param)).await?;
342
343 record_repository(&repo);
344
345 Ok(())
346}
347
a47a02ae
DM
348#[api(
349 input: {
350 properties: {
351 repository: {
352 schema: REPO_URL_SCHEMA,
353 optional: true,
354 },
355 }
356 }
357)]
358/// Try to login. If successful, store ticket.
359async fn api_login(param: Value) -> Result<Value, Error> {
e240d8be
DM
360
361 let repo = extract_repository_from_value(&param)?;
362
f3fde36b 363 let client = connect(&repo)?;
8a8a4703 364 client.login().await?;
e240d8be
DM
365
366 record_repository(&repo);
367
368 Ok(Value::Null)
369}
370
a47a02ae
DM
371#[api(
372 input: {
373 properties: {
374 repository: {
375 schema: REPO_URL_SCHEMA,
376 optional: true,
377 },
378 }
379 }
380)]
381/// Logout (delete stored ticket).
382fn api_logout(param: Value) -> Result<Value, Error> {
e240d8be
DM
383
384 let repo = extract_repository_from_value(&param)?;
385
5030b7ce 386 delete_ticket_info("proxmox-backup", repo.host(), repo.user())?;
e240d8be
DM
387
388 Ok(Value::Null)
389}
390
e39974af
TL
391#[api(
392 input: {
393 properties: {
394 repository: {
395 schema: REPO_URL_SCHEMA,
396 optional: true,
397 },
398 "output-format": {
399 schema: OUTPUT_FORMAT,
400 optional: true,
401 },
402 }
403 }
404)]
405/// Show client and optional server version
406async fn api_version(param: Value) -> Result<(), Error> {
407
408 let output_format = get_output_format(&param);
409
410 let mut version_info = json!({
411 "client": {
412 "version": version::PROXMOX_PKG_VERSION,
413 "release": version::PROXMOX_PKG_RELEASE,
414 "repoid": version::PROXMOX_PKG_REPOID,
415 }
416 });
417
418 let repo = extract_repository_from_value(&param);
419 if let Ok(repo) = repo {
f3fde36b 420 let client = connect(&repo)?;
e39974af
TL
421
422 match client.get("api2/json/version", None).await {
423 Ok(mut result) => version_info["server"] = result["data"].take(),
424 Err(e) => eprintln!("could not connect to server - {}", e),
425 }
426 }
427 if output_format == "text" {
428 println!("client version: {}.{}", version::PROXMOX_PKG_VERSION, version::PROXMOX_PKG_RELEASE);
429 if let Some(server) = version_info["server"].as_object() {
430 let server_version = server["version"].as_str().unwrap();
431 let server_release = server["release"].as_str().unwrap();
432 println!("server version: {}.{}", server_version, server_release);
433 }
434 } else {
435 format_and_print_result(&version_info, &output_format);
436 }
437
438 Ok(())
439}
440
a47a02ae 441#[api(
94913f35 442 input: {
a47a02ae
DM
443 properties: {
444 repository: {
445 schema: REPO_URL_SCHEMA,
446 optional: true,
447 },
94913f35
DM
448 "output-format": {
449 schema: OUTPUT_FORMAT,
450 optional: true,
451 },
452 },
453 },
a47a02ae
DM
454)]
455/// Start garbage collection for a specific repository.
456async fn start_garbage_collection(param: Value) -> Result<Value, Error> {
8cc0d6af 457
2665cef7 458 let repo = extract_repository_from_value(&param)?;
c2043614
DM
459
460 let output_format = get_output_format(&param);
8cc0d6af 461
f3fde36b 462 let mut client = connect(&repo)?;
8cc0d6af 463
d0a03d40 464 let path = format!("api2/json/admin/datastore/{}/gc", repo.store());
8cc0d6af 465
8a8a4703 466 let result = client.post(&path, None).await?;
8cc0d6af 467
8a8a4703 468 record_repository(&repo);
d0a03d40 469
e68269fc 470 view_task_result(&mut client, result, &output_format).await?;
e5f7def4 471
e5f7def4 472 Ok(Value::Null)
8cc0d6af 473}
33d64b81 474
6d233161 475struct CatalogUploadResult {
f1d76ecf 476 catalog_writer: Arc<Mutex<CatalogWriter<TokioWriterAdapter<StdChannelWriter>>>>,
6d233161
FG
477 result: tokio::sync::oneshot::Receiver<Result<BackupStats, Error>>,
478}
479
bf6e3217 480fn spawn_catalog_upload(
3bad3e6e 481 client: Arc<BackupWriter>,
3638341a 482 encrypt: bool,
6d233161 483) -> Result<CatalogUploadResult, Error> {
f1d99e3f
DM
484 let (catalog_tx, catalog_rx) = std::sync::mpsc::sync_channel(10); // allow to buffer 10 writes
485 let catalog_stream = crate::tools::StdChannelStream(catalog_rx);
bf6e3217
DM
486 let catalog_chunk_size = 512*1024;
487 let catalog_chunk_stream = ChunkStream::new(catalog_stream, Some(catalog_chunk_size));
488
f1d76ecf 489 let catalog_writer = Arc::new(Mutex::new(CatalogWriter::new(TokioWriterAdapter::new(StdChannelWriter::new(catalog_tx)))?));
bf6e3217
DM
490
491 let (catalog_result_tx, catalog_result_rx) = tokio::sync::oneshot::channel();
492
e43b9175
FG
493 let upload_options = UploadOptions {
494 encrypt,
495 compress: true,
496 ..UploadOptions::default()
497 };
498
bf6e3217
DM
499 tokio::spawn(async move {
500 let catalog_upload_result = client
e43b9175 501 .upload_stream(CATALOG_NAME, catalog_chunk_stream, upload_options)
bf6e3217
DM
502 .await;
503
504 if let Err(ref err) = catalog_upload_result {
505 eprintln!("catalog upload error - {}", err);
506 client.cancel();
507 }
508
509 let _ = catalog_result_tx.send(catalog_upload_result);
510 });
511
6d233161 512 Ok(CatalogUploadResult { catalog_writer, result: catalog_result_rx })
bf6e3217
DM
513}
514
a47a02ae
DM
515#[api(
516 input: {
517 properties: {
518 backupspec: {
519 type: Array,
520 description: "List of backup source specifications ([<label.ext>:<path>] ...)",
521 items: {
522 schema: BACKUP_SOURCE_SCHEMA,
523 }
524 },
525 repository: {
526 schema: REPO_URL_SCHEMA,
527 optional: true,
528 },
529 "include-dev": {
530 description: "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.",
531 optional: true,
532 items: {
533 type: String,
534 description: "Path to file.",
535 }
536 },
58fcbf5a
FE
537 "all-file-systems": {
538 type: Boolean,
539 description: "Include all mounted subdirectories.",
540 optional: true,
541 },
a47a02ae
DM
542 keyfile: {
543 schema: KEYFILE_SCHEMA,
544 optional: true,
545 },
0351f23b
WB
546 "keyfd": {
547 schema: KEYFD_SCHEMA,
548 optional: true,
549 },
c0a87c12
FG
550 "master-pubkey-file": {
551 schema: MASTER_PUBKEY_FILE_SCHEMA,
552 optional: true,
553 },
554 "master-pubkey-fd": {
555 schema: MASTER_PUBKEY_FD_SCHEMA,
556 optional: true,
557 },
24be37e3
WB
558 "crypt-mode": {
559 type: CryptMode,
96ee8577
WB
560 optional: true,
561 },
a47a02ae
DM
562 "skip-lost-and-found": {
563 type: Boolean,
564 description: "Skip lost+found directory.",
565 optional: true,
566 },
567 "backup-type": {
568 schema: BACKUP_TYPE_SCHEMA,
569 optional: true,
570 },
571 "backup-id": {
572 schema: BACKUP_ID_SCHEMA,
573 optional: true,
574 },
575 "backup-time": {
576 schema: BACKUP_TIME_SCHEMA,
577 optional: true,
578 },
579 "chunk-size": {
580 schema: CHUNK_SIZE_SCHEMA,
581 optional: true,
582 },
189996cf
CE
583 "exclude": {
584 type: Array,
585 description: "List of paths or patterns for matching files to exclude.",
586 optional: true,
587 items: {
588 type: String,
589 description: "Path or match pattern.",
590 }
591 },
6fc053ed
CE
592 "entries-max": {
593 type: Integer,
594 description: "Max number of entries to hold in memory.",
595 optional: true,
c443f58b 596 default: proxmox_backup::pxar::ENCODER_MAX_ENTRIES as isize,
6fc053ed 597 },
e02c3d46
DM
598 "verbose": {
599 type: Boolean,
600 description: "Verbose output.",
601 optional: true,
602 },
a47a02ae
DM
603 }
604 }
605)]
606/// Create (host) backup.
607async fn create_backup(
6049b71f
DM
608 param: Value,
609 _info: &ApiMethod,
dd5495d6 610 _rpcenv: &mut dyn RpcEnvironment,
6049b71f 611) -> Result<Value, Error> {
ff5d3707 612
2665cef7 613 let repo = extract_repository_from_value(&param)?;
ae0be2dd
DM
614
615 let backupspec_list = tools::required_array_param(&param, "backupspec")?;
a914a774 616
eed6db39
DM
617 let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false);
618
5b72c9b4
DM
619 let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false);
620
219ef0e6
DM
621 let verbose = param["verbose"].as_bool().unwrap_or(false);
622
ca5d0b61
DM
623 let backup_time_opt = param["backup-time"].as_i64();
624
36898ffc 625 let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize);
2d9d143a 626
247cdbce
DM
627 if let Some(size) = chunk_size_opt {
628 verify_chunk_size(size)?;
2d9d143a
DM
629 }
630
c6a7ea0a 631 let crypto = crypto_parameters(&param)?;
6d0983db 632
f69adc81 633 let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename());
fba30411 634
bbf9e7e9 635 let backup_type = param["backup-type"].as_str().unwrap_or("host");
ca5d0b61 636
2eeaacb9
DM
637 let include_dev = param["include-dev"].as_array();
638
c443f58b
WB
639 let entries_max = param["entries-max"].as_u64()
640 .unwrap_or(proxmox_backup::pxar::ENCODER_MAX_ENTRIES as u64);
6fc053ed 641
189996cf 642 let empty = Vec::new();
c443f58b
WB
643 let exclude_args = param["exclude"].as_array().unwrap_or(&empty);
644
239e49f9 645 let mut pattern_list = Vec::with_capacity(exclude_args.len());
c443f58b
WB
646 for entry in exclude_args {
647 let entry = entry.as_str().ok_or_else(|| format_err!("Invalid pattern string slice"))?;
239e49f9 648 pattern_list.push(
c443f58b
WB
649 MatchEntry::parse_pattern(entry, PatternFlag::PATH_NAME, MatchType::Exclude)
650 .map_err(|err| format_err!("invalid exclude pattern entry: {}", err))?
651 );
189996cf
CE
652 }
653
2eeaacb9
DM
654 let mut devices = if all_file_systems { None } else { Some(HashSet::new()) };
655
656 if let Some(include_dev) = include_dev {
657 if all_file_systems {
658 bail!("option 'all-file-systems' conflicts with option 'include-dev'");
659 }
660
661 let mut set = HashSet::new();
662 for path in include_dev {
663 let path = path.as_str().unwrap();
664 let stat = nix::sys::stat::stat(path)
665 .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?;
666 set.insert(stat.st_dev);
667 }
668 devices = Some(set);
669 }
670
ae0be2dd 671 let mut upload_list = vec![];
f2b4b4b9 672 let mut target_set = HashSet::new();
a914a774 673
ae0be2dd 674 for backupspec in backupspec_list {
7cc3473a
DM
675 let spec = parse_backup_specification(backupspec.as_str().unwrap())?;
676 let filename = &spec.config_string;
677 let target = &spec.archive_name;
bcd879cf 678
f2b4b4b9
SI
679 if target_set.contains(target) {
680 bail!("got target twice: '{}'", target);
681 }
682 target_set.insert(target.to_string());
683
eb1804c5
DM
684 use std::os::unix::fs::FileTypeExt;
685
3fa71727
CE
686 let metadata = std::fs::metadata(filename)
687 .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?;
eb1804c5 688 let file_type = metadata.file_type();
23bb8780 689
7cc3473a
DM
690 match spec.spec_type {
691 BackupSpecificationType::PXAR => {
ec8a9bb9
DM
692 if !file_type.is_dir() {
693 bail!("got unexpected file type (expected directory)");
694 }
7cc3473a 695 upload_list.push((BackupSpecificationType::PXAR, filename.to_owned(), format!("{}.didx", target), 0));
ec8a9bb9 696 }
7cc3473a 697 BackupSpecificationType::IMAGE => {
ec8a9bb9
DM
698 if !(file_type.is_file() || file_type.is_block_device()) {
699 bail!("got unexpected file type (expected file or block device)");
700 }
eb1804c5 701
e18a6c9e 702 let size = image_size(&PathBuf::from(filename))?;
23bb8780 703
ec8a9bb9 704 if size == 0 { bail!("got zero-sized file '{}'", filename); }
ae0be2dd 705
7cc3473a 706 upload_list.push((BackupSpecificationType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size));
ec8a9bb9 707 }
7cc3473a 708 BackupSpecificationType::CONFIG => {
ec8a9bb9
DM
709 if !file_type.is_file() {
710 bail!("got unexpected file type (expected regular file)");
711 }
7cc3473a 712 upload_list.push((BackupSpecificationType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len()));
ec8a9bb9 713 }
7cc3473a 714 BackupSpecificationType::LOGFILE => {
79679c2d
DM
715 if !file_type.is_file() {
716 bail!("got unexpected file type (expected regular file)");
717 }
7cc3473a 718 upload_list.push((BackupSpecificationType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len()));
ec8a9bb9 719 }
ae0be2dd
DM
720 }
721 }
722
22a9189e 723 let backup_time = backup_time_opt.unwrap_or_else(epoch_i64);
ae0be2dd 724
f3fde36b 725 let client = connect(&repo)?;
d0a03d40
DM
726 record_repository(&repo);
727
6a7be83e 728 println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time)?);
ca5d0b61 729
f69adc81 730 println!("Client name: {}", proxmox::tools::nodename());
ca5d0b61 731
6a7be83e 732 let start_time = std::time::Instant::now();
ca5d0b61 733
6a7be83e 734 println!("Starting backup protocol: {}", strftime_local("%c", epoch_i64())?);
51144821 735
c6a7ea0a 736 let (crypt_config, rsa_encrypted_key) = match crypto.enc_key {
bb823140 737 None => (None, None),
2f26b866
FG
738 Some(key_with_source) => {
739 println!(
740 "{}",
741 format_key_source(&key_with_source.source, "encryption")
742 );
743
744 let (key, created, fingerprint) =
ff8945fd 745 decrypt_key(&key_with_source.key, &get_encryption_key_password)?;
6f2626ae 746 println!("Encryption key fingerprint: {}", fingerprint);
bb823140 747
44288184 748 let crypt_config = CryptConfig::new(key)?;
bb823140 749
c0a87c12 750 match crypto.master_pubkey {
2f26b866
FG
751 Some(pem_with_source) => {
752 println!("{}", format_key_source(&pem_with_source.source, "master"));
753
754 let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_with_source.key)?;
82a103c8 755
1c86893d 756 let mut key_config = KeyConfig::without_password(key)?;
82a103c8 757 key_config.created = created; // keep original value
82a103c8 758
8acfd15d 759 let enc_key = rsa_encrypt_key_config(rsa, &key_config)?;
6f2626ae 760
05389a01 761 (Some(Arc::new(crypt_config)), Some(enc_key))
2f26b866 762 },
05389a01 763 _ => (Some(Arc::new(crypt_config)), None),
bb823140 764 }
6d0983db
DM
765 }
766 };
f98ac774 767
8a8a4703
DM
768 let client = BackupWriter::start(
769 client,
b957aa81 770 crypt_config.clone(),
8a8a4703
DM
771 repo.store(),
772 backup_type,
773 &backup_id,
774 backup_time,
775 verbose,
61d7b501 776 false
8a8a4703
DM
777 ).await?;
778
8b7f8d3f
FG
779 let download_previous_manifest = match client.previous_backup_time().await {
780 Ok(Some(backup_time)) => {
781 println!(
782 "Downloading previous manifest ({})",
783 strftime_local("%c", backup_time)?
784 );
785 true
786 }
787 Ok(None) => {
788 println!("No previous manifest available.");
789 false
790 }
791 Err(_) => {
792 // Fallback for outdated server, TODO remove/bubble up with 2.0
793 true
794 }
795 };
796
797 let previous_manifest = if download_previous_manifest {
798 match client.download_previous_manifest().await {
799 Ok(previous_manifest) => {
800 match previous_manifest.check_fingerprint(crypt_config.as_ref().map(Arc::as_ref)) {
801 Ok(()) => Some(Arc::new(previous_manifest)),
802 Err(err) => {
803 println!("Couldn't re-use previous manifest - {}", err);
804 None
805 }
806 }
23f9503a 807 }
8b7f8d3f
FG
808 Err(err) => {
809 println!("Couldn't download previous manifest - {}", err);
810 None
811 }
812 }
813 } else {
814 None
b957aa81
DM
815 };
816
6a7be83e 817 let snapshot = BackupDir::new(backup_type, backup_id, backup_time)?;
8a8a4703
DM
818 let mut manifest = BackupManifest::new(snapshot);
819
5d85847f 820 let mut catalog = None;
6d233161 821 let mut catalog_result_rx = None;
8a8a4703
DM
822
823 for (backup_type, filename, target, size) in upload_list {
824 match backup_type {
7cc3473a 825 BackupSpecificationType::CONFIG => {
e43b9175
FG
826 let upload_options = UploadOptions {
827 compress: true,
c6a7ea0a 828 encrypt: crypto.mode == CryptMode::Encrypt,
e43b9175
FG
829 ..UploadOptions::default()
830 };
831
5b32820e 832 println!("Upload config file '{}' to '{}' as {}", filename, repo, target);
8a8a4703 833 let stats = client
e43b9175 834 .upload_blob_from_file(&filename, &target, upload_options)
8a8a4703 835 .await?;
c6a7ea0a 836 manifest.add_file(target, stats.size, stats.csum, crypto.mode)?;
8a8a4703 837 }
7cc3473a 838 BackupSpecificationType::LOGFILE => { // fixme: remove - not needed anymore ?
e43b9175
FG
839 let upload_options = UploadOptions {
840 compress: true,
c6a7ea0a 841 encrypt: crypto.mode == CryptMode::Encrypt,
e43b9175
FG
842 ..UploadOptions::default()
843 };
844
5b32820e 845 println!("Upload log file '{}' to '{}' as {}", filename, repo, target);
8a8a4703 846 let stats = client
e43b9175 847 .upload_blob_from_file(&filename, &target, upload_options)
8a8a4703 848 .await?;
c6a7ea0a 849 manifest.add_file(target, stats.size, stats.csum, crypto.mode)?;
8a8a4703 850 }
7cc3473a 851 BackupSpecificationType::PXAR => {
5d85847f
DC
852 // start catalog upload on first use
853 if catalog.is_none() {
c6a7ea0a 854 let catalog_upload_res = spawn_catalog_upload(client.clone(), crypto.mode == CryptMode::Encrypt)?;
6d233161
FG
855 catalog = Some(catalog_upload_res.catalog_writer);
856 catalog_result_rx = Some(catalog_upload_res.result);
5d85847f
DC
857 }
858 let catalog = catalog.as_ref().unwrap();
859
5b32820e 860 println!("Upload directory '{}' to '{}' as {}", filename, repo, target);
8a8a4703 861 catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?;
77486a60
FG
862
863 let pxar_options = proxmox_backup::pxar::PxarCreateOptions {
864 device_set: devices.clone(),
865 patterns: pattern_list.clone(),
866 entries_max: entries_max as usize,
867 skip_lost_and_found,
868 verbose,
869 };
870
e43b9175
FG
871 let upload_options = UploadOptions {
872 previous_manifest: previous_manifest.clone(),
873 compress: true,
c6a7ea0a 874 encrypt: crypto.mode == CryptMode::Encrypt,
e43b9175
FG
875 ..UploadOptions::default()
876 };
877
8a8a4703
DM
878 let stats = backup_directory(
879 &client,
880 &filename,
881 &target,
882 chunk_size_opt,
8a8a4703 883 catalog.clone(),
77486a60 884 pxar_options,
e43b9175 885 upload_options,
8a8a4703 886 ).await?;
c6a7ea0a 887 manifest.add_file(target, stats.size, stats.csum, crypto.mode)?;
8a8a4703
DM
888 catalog.lock().unwrap().end_directory()?;
889 }
7cc3473a 890 BackupSpecificationType::IMAGE => {
8a8a4703 891 println!("Upload image '{}' to '{:?}' as {}", filename, repo, target);
e43b9175
FG
892
893 let upload_options = UploadOptions {
894 previous_manifest: previous_manifest.clone(),
895 fixed_size: Some(size),
896 compress: true,
c6a7ea0a 897 encrypt: crypto.mode == CryptMode::Encrypt,
e43b9175
FG
898 };
899
8a8a4703
DM
900 let stats = backup_image(
901 &client,
e43b9175 902 &filename,
8a8a4703 903 &target,
8a8a4703 904 chunk_size_opt,
e43b9175 905 upload_options,
8a8a4703 906 ).await?;
c6a7ea0a 907 manifest.add_file(target, stats.size, stats.csum, crypto.mode)?;
6af905c1
DM
908 }
909 }
8a8a4703 910 }
4818c8b6 911
8a8a4703 912 // finalize and upload catalog
5d85847f 913 if let Some(catalog) = catalog {
8a8a4703
DM
914 let mutex = Arc::try_unwrap(catalog)
915 .map_err(|_| format_err!("unable to get catalog (still used)"))?;
916 let mut catalog = mutex.into_inner().unwrap();
bf6e3217 917
8a8a4703 918 catalog.finish()?;
2761d6a4 919
8a8a4703 920 drop(catalog); // close upload stream
2761d6a4 921
6d233161 922 if let Some(catalog_result_rx) = catalog_result_rx {
5d85847f 923 let stats = catalog_result_rx.await??;
c6a7ea0a 924 manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum, crypto.mode)?;
5d85847f 925 }
8a8a4703 926 }
2761d6a4 927
8a8a4703 928 if let Some(rsa_encrypted_key) = rsa_encrypted_key {
9990af30 929 let target = ENCRYPTED_KEY_BLOB_NAME;
8a8a4703 930 println!("Upload RSA encoded key to '{:?}' as {}", repo, target);
e43b9175 931 let options = UploadOptions { compress: false, encrypt: false, ..UploadOptions::default() };
8a8a4703 932 let stats = client
e43b9175 933 .upload_blob_from_data(rsa_encrypted_key, target, options)
8a8a4703 934 .await?;
c6a7ea0a 935 manifest.add_file(target.to_string(), stats.size, stats.csum, crypto.mode)?;
8a8a4703 936
8a8a4703 937 }
8a8a4703 938 // create manifest (index.json)
3638341a 939 // manifests are never encrypted, but include a signature
dfa517ad 940 let manifest = manifest.to_string(crypt_config.as_ref().map(Arc::as_ref))
b53f6379 941 .map_err(|err| format_err!("unable to format manifest - {}", err))?;
3638341a 942
b53f6379 943
9688f6de 944 if verbose { println!("Upload index.json to '{}'", repo) };
e43b9175 945 let options = UploadOptions { compress: true, encrypt: false, ..UploadOptions::default() };
8a8a4703 946 client
e43b9175 947 .upload_blob_from_data(manifest.into_bytes(), MANIFEST_BLOB_NAME, options)
8a8a4703 948 .await?;
2c3891d1 949
8a8a4703 950 client.finish().await?;
c4ff3dce 951
6a7be83e
DM
952 let end_time = std::time::Instant::now();
953 let elapsed = end_time.duration_since(start_time);
954 println!("Duration: {:.2}s", elapsed.as_secs_f64());
3ec3ec3f 955
6a7be83e 956 println!("End Time: {}", strftime_local("%c", epoch_i64())?);
3d5c11e5 957
8a8a4703 958 Ok(Value::Null)
f98ea63d
DM
959}
960
8e6e18b7 961async fn dump_image<W: Write>(
88892ea8
DM
962 client: Arc<BackupReader>,
963 crypt_config: Option<Arc<CryptConfig>>,
14f6c9cb 964 crypt_mode: CryptMode,
88892ea8
DM
965 index: FixedIndexReader,
966 mut writer: W,
fd04ca7a 967 verbose: bool,
88892ea8
DM
968) -> Result<(), Error> {
969
970 let most_used = index.find_most_used_chunks(8);
971
14f6c9cb 972 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, crypt_mode, most_used);
88892ea8
DM
973
974 // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy
975 // and thus slows down reading. Instead, directly use RemoteChunkReader
fd04ca7a
DM
976 let mut per = 0;
977 let mut bytes = 0;
978 let start_time = std::time::Instant::now();
979
88892ea8
DM
980 for pos in 0..index.index_count() {
981 let digest = index.index_digest(pos).unwrap();
8e6e18b7 982 let raw_data = chunk_reader.read_chunk(&digest).await?;
88892ea8 983 writer.write_all(&raw_data)?;
fd04ca7a
DM
984 bytes += raw_data.len();
985 if verbose {
986 let next_per = ((pos+1)*100)/index.index_count();
987 if per != next_per {
988 eprintln!("progress {}% (read {} bytes, duration {} sec)",
989 next_per, bytes, start_time.elapsed().as_secs());
990 per = next_per;
991 }
992 }
88892ea8
DM
993 }
994
fd04ca7a
DM
995 let end_time = std::time::Instant::now();
996 let elapsed = end_time.duration_since(start_time);
997 eprintln!("restore image complete (bytes={}, duration={:.2}s, speed={:.2}MB/s)",
998 bytes,
999 elapsed.as_secs_f64(),
1000 bytes as f64/(1024.0*1024.0*elapsed.as_secs_f64())
1001 );
1002
1003
88892ea8
DM
1004 Ok(())
1005}
1006
dc155e9b 1007fn parse_archive_type(name: &str) -> (String, ArchiveType) {
2d32fe2c
TL
1008 if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") {
1009 (name.into(), archive_type(name).unwrap())
1010 } else if name.ends_with(".pxar") {
dc155e9b
TL
1011 (format!("{}.didx", name), ArchiveType::DynamicIndex)
1012 } else if name.ends_with(".img") {
1013 (format!("{}.fidx", name), ArchiveType::FixedIndex)
1014 } else {
1015 (format!("{}.blob", name), ArchiveType::Blob)
1016 }
1017}
1018
a47a02ae
DM
1019#[api(
1020 input: {
1021 properties: {
1022 repository: {
1023 schema: REPO_URL_SCHEMA,
1024 optional: true,
1025 },
1026 snapshot: {
1027 type: String,
1028 description: "Group/Snapshot path.",
1029 },
1030 "archive-name": {
1031 description: "Backup archive name.",
1032 type: String,
1033 },
1034 target: {
1035 type: String,
90c815bf 1036 description: r###"Target directory path. Use '-' to write to standard output.
8a8a4703 1037
d1d74c43 1038We do not extract '.pxar' archives when writing to standard output.
8a8a4703 1039
a47a02ae
DM
1040"###
1041 },
1042 "allow-existing-dirs": {
1043 type: Boolean,
1044 description: "Do not fail if directories already exists.",
1045 optional: true,
1046 },
1047 keyfile: {
1048 schema: KEYFILE_SCHEMA,
1049 optional: true,
1050 },
0351f23b
WB
1051 "keyfd": {
1052 schema: KEYFD_SCHEMA,
1053 optional: true,
1054 },
24be37e3
WB
1055 "crypt-mode": {
1056 type: CryptMode,
96ee8577
WB
1057 optional: true,
1058 },
a47a02ae
DM
1059 }
1060 }
1061)]
1062/// Restore backup repository.
1063async fn restore(param: Value) -> Result<Value, Error> {
2665cef7 1064 let repo = extract_repository_from_value(&param)?;
9f912493 1065
86eda3eb
DM
1066 let verbose = param["verbose"].as_bool().unwrap_or(false);
1067
46d5aa0a
DM
1068 let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false);
1069
d5c34d98
DM
1070 let archive_name = tools::required_string_param(&param, "archive-name")?;
1071
f3fde36b 1072 let client = connect(&repo)?;
d0a03d40 1073
d0a03d40 1074 record_repository(&repo);
d5c34d98 1075
9f912493 1076 let path = tools::required_string_param(&param, "snapshot")?;
9f912493 1077
86eda3eb 1078 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
d6d3b353 1079 let group: BackupGroup = path.parse()?;
27c9affb 1080 api_datastore_latest_snapshot(&client, repo.store(), group).await?
d5c34d98 1081 } else {
a67f7d0a 1082 let snapshot: BackupDir = path.parse()?;
86eda3eb
DM
1083 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
1084 };
9f912493 1085
d5c34d98 1086 let target = tools::required_string_param(&param, "target")?;
bf125261 1087 let target = if target == "-" { None } else { Some(target) };
2ae7d196 1088
c6a7ea0a 1089 let crypto = crypto_parameters(&param)?;
2ae7d196 1090
c6a7ea0a 1091 let crypt_config = match crypto.enc_key {
86eda3eb 1092 None => None,
2f26b866
FG
1093 Some(ref key) => {
1094 let (key, _, _) =
ff8945fd 1095 decrypt_key(&key.key, &get_encryption_key_password).map_err(|err| {
2f26b866
FG
1096 eprintln!("{}", format_key_source(&key.source, "encryption"));
1097 err
1098 })?;
86eda3eb
DM
1099 Some(Arc::new(CryptConfig::new(key)?))
1100 }
1101 };
d5c34d98 1102
296c50ba
DM
1103 let client = BackupReader::start(
1104 client,
1105 crypt_config.clone(),
1106 repo.store(),
1107 &backup_type,
1108 &backup_id,
1109 backup_time,
1110 true,
1111 ).await?;
86eda3eb 1112
48fbbfeb
FG
1113 let (archive_name, archive_type) = parse_archive_type(archive_name);
1114
2107a5ae 1115 let (manifest, backup_index_data) = client.download_manifest().await?;
02fcf372 1116
48fbbfeb
FG
1117 if archive_name == ENCRYPTED_KEY_BLOB_NAME && crypt_config.is_none() {
1118 eprintln!("Restoring encrypted key blob without original key - skipping manifest fingerprint check!")
1119 } else {
2f26b866
FG
1120 if manifest.signature.is_some() {
1121 if let Some(key) = &crypto.enc_key {
1122 eprintln!("{}", format_key_source(&key.source, "encryption"));
1123 }
1124 if let Some(config) = &crypt_config {
1125 eprintln!("Fingerprint: {}", config.fingerprint());
1126 }
1127 }
48fbbfeb
FG
1128 manifest.check_fingerprint(crypt_config.as_ref().map(Arc::as_ref))?;
1129 }
dc155e9b
TL
1130
1131 if archive_name == MANIFEST_BLOB_NAME {
02fcf372 1132 if let Some(target) = target {
2107a5ae 1133 replace_file(target, &backup_index_data, CreateOptions::new())?;
02fcf372
DM
1134 } else {
1135 let stdout = std::io::stdout();
1136 let mut writer = stdout.lock();
2107a5ae 1137 writer.write_all(&backup_index_data)
02fcf372
DM
1138 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1139 }
1140
14f6c9cb
FG
1141 return Ok(Value::Null);
1142 }
1143
1144 let file_info = manifest.lookup_file_info(&archive_name)?;
1145
1146 if archive_type == ArchiveType::Blob {
d2267b11 1147
dc155e9b 1148 let mut reader = client.download_blob(&manifest, &archive_name).await?;
f8100e96 1149
bf125261 1150 if let Some(target) = target {
0d986280
DM
1151 let mut writer = std::fs::OpenOptions::new()
1152 .write(true)
1153 .create(true)
1154 .create_new(true)
1155 .open(target)
1156 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?;
1157 std::io::copy(&mut reader, &mut writer)?;
bf125261
DM
1158 } else {
1159 let stdout = std::io::stdout();
1160 let mut writer = stdout.lock();
0d986280 1161 std::io::copy(&mut reader, &mut writer)
bf125261
DM
1162 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1163 }
f8100e96 1164
dc155e9b 1165 } else if archive_type == ArchiveType::DynamicIndex {
86eda3eb 1166
dc155e9b 1167 let index = client.download_dynamic_index(&manifest, &archive_name).await?;
df65bd3d 1168
f4bf7dfc
DM
1169 let most_used = index.find_most_used_chunks(8);
1170
14f6c9cb 1171 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, file_info.chunk_crypt_mode(), most_used);
f4bf7dfc 1172
afb4cd28 1173 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
86eda3eb 1174
72064fd0
FG
1175 let options = proxmox_backup::pxar::PxarExtractOptions {
1176 match_list: &[],
1177 extract_match_default: true,
1178 allow_existing_dirs,
1179 on_error: None,
1180 };
1181
bf125261 1182 if let Some(target) = target {
c443f58b
WB
1183 proxmox_backup::pxar::extract_archive(
1184 pxar::decoder::Decoder::from_std(reader)?,
1185 Path::new(target),
5444fa94 1186 proxmox_backup::pxar::Flags::DEFAULT,
c443f58b
WB
1187 |path| {
1188 if verbose {
1189 println!("{:?}", path);
1190 }
1191 },
72064fd0 1192 options,
c443f58b
WB
1193 )
1194 .map_err(|err| format_err!("error extracting archive - {}", err))?;
bf125261 1195 } else {
88892ea8
DM
1196 let mut writer = std::fs::OpenOptions::new()
1197 .write(true)
1198 .open("/dev/stdout")
1199 .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?;
afb4cd28 1200
bf125261
DM
1201 std::io::copy(&mut reader, &mut writer)
1202 .map_err(|err| format_err!("unable to pipe data - {}", err))?;
1203 }
dc155e9b 1204 } else if archive_type == ArchiveType::FixedIndex {
afb4cd28 1205
dc155e9b 1206 let index = client.download_fixed_index(&manifest, &archive_name).await?;
df65bd3d 1207
88892ea8
DM
1208 let mut writer = if let Some(target) = target {
1209 std::fs::OpenOptions::new()
bf125261
DM
1210 .write(true)
1211 .create(true)
1212 .create_new(true)
1213 .open(target)
88892ea8 1214 .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?
bf125261 1215 } else {
88892ea8
DM
1216 std::fs::OpenOptions::new()
1217 .write(true)
1218 .open("/dev/stdout")
1219 .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?
1220 };
afb4cd28 1221
14f6c9cb 1222 dump_image(client.clone(), crypt_config.clone(), file_info.chunk_crypt_mode(), index, &mut writer, verbose).await?;
3031e44c 1223 }
fef44d4f
DM
1224
1225 Ok(Value::Null)
45db6f89
DM
1226}
1227
032d3ad8
DM
1228const API_METHOD_PRUNE: ApiMethod = ApiMethod::new(
1229 &ApiHandler::Async(&prune),
1230 &ObjectSchema::new(
1231 "Prune a backup repository.",
1232 &proxmox_backup::add_common_prune_prameters!([
1233 ("dry-run", true, &BooleanSchema::new(
1234 "Just show what prune would do, but do not delete anything.")
1235 .schema()),
1236 ("group", false, &StringSchema::new("Backup group.").schema()),
1237 ], [
1238 ("output-format", true, &OUTPUT_FORMAT),
c48aa39f
DM
1239 (
1240 "quiet",
1241 true,
1242 &BooleanSchema::new("Minimal output - only show removals.")
1243 .schema()
1244 ),
032d3ad8
DM
1245 ("repository", true, &REPO_URL_SCHEMA),
1246 ])
1247 )
1248);
1249
1250fn prune<'a>(
1251 param: Value,
1252 _info: &ApiMethod,
1253 _rpcenv: &'a mut dyn RpcEnvironment,
1254) -> proxmox::api::ApiFuture<'a> {
1255 async move {
1256 prune_async(param).await
1257 }.boxed()
1258}
83b7db02 1259
032d3ad8 1260async fn prune_async(mut param: Value) -> Result<Value, Error> {
2665cef7 1261 let repo = extract_repository_from_value(&param)?;
83b7db02 1262
f3fde36b 1263 let mut client = connect(&repo)?;
83b7db02 1264
d0a03d40 1265 let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
83b7db02 1266
9fdc3ef4 1267 let group = tools::required_string_param(&param, "group")?;
d6d3b353 1268 let group: BackupGroup = group.parse()?;
c2043614 1269
671c6a96 1270 let output_format = extract_output_format(&mut param);
9fdc3ef4 1271
c48aa39f
DM
1272 let quiet = param["quiet"].as_bool().unwrap_or(false);
1273
ea7a7ef2
DM
1274 param.as_object_mut().unwrap().remove("repository");
1275 param.as_object_mut().unwrap().remove("group");
c48aa39f 1276 param.as_object_mut().unwrap().remove("quiet");
ea7a7ef2
DM
1277
1278 param["backup-type"] = group.backup_type().into();
1279 param["backup-id"] = group.backup_id().into();
83b7db02 1280
db1e061d 1281 let mut result = client.post(&path, Some(param)).await?;
74fa81b8 1282
87c42375 1283 record_repository(&repo);
3b03abfe 1284
db1e061d
DM
1285 let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> {
1286 let item: PruneListItem = serde_json::from_value(record.to_owned())?;
e0e5b442 1287 let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time)?;
db1e061d
DM
1288 Ok(snapshot.relative_path().to_str().unwrap().to_owned())
1289 };
1290
c48aa39f
DM
1291 let render_prune_action = |v: &Value, _record: &Value| -> Result<String, Error> {
1292 Ok(match v.as_bool() {
1293 Some(true) => "keep",
1294 Some(false) => "remove",
1295 None => "unknown",
1296 }.to_string())
1297 };
1298
db1e061d
DM
1299 let options = default_table_format_options()
1300 .sortby("backup-type", false)
1301 .sortby("backup-id", false)
1302 .sortby("backup-time", false)
1303 .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot"))
770a36e5 1304 .column(ColumnConfig::new("backup-time").renderer(pbs_tools::format::render_epoch).header("date"))
c48aa39f 1305 .column(ColumnConfig::new("keep").renderer(render_prune_action).header("action"))
db1e061d
DM
1306 ;
1307
b2362a12 1308 let return_type = &proxmox_backup::api2::admin::datastore::API_METHOD_PRUNE.returns;
db1e061d
DM
1309
1310 let mut data = result["data"].take();
1311
c48aa39f
DM
1312 if quiet {
1313 let list: Vec<Value> = data.as_array().unwrap().iter().filter(|item| {
1314 item["keep"].as_bool() == Some(false)
a375df6f 1315 }).cloned().collect();
c48aa39f
DM
1316 data = list.into();
1317 }
1318
b2362a12 1319 format_and_print_result_full(&mut data, return_type, &output_format, &options);
d0a03d40 1320
43a406fd 1321 Ok(Value::Null)
83b7db02
DM
1322}
1323
a47a02ae
DM
1324#[api(
1325 input: {
1326 properties: {
1327 repository: {
1328 schema: REPO_URL_SCHEMA,
1329 optional: true,
1330 },
1331 "output-format": {
1332 schema: OUTPUT_FORMAT,
1333 optional: true,
1334 },
1335 }
f9beae9c
TL
1336 },
1337 returns: {
1338 type: StorageStatus,
1339 },
a47a02ae
DM
1340)]
1341/// Get repository status.
1342async fn status(param: Value) -> Result<Value, Error> {
34a816cc
DM
1343
1344 let repo = extract_repository_from_value(&param)?;
1345
c2043614 1346 let output_format = get_output_format(&param);
34a816cc 1347
f3fde36b 1348 let client = connect(&repo)?;
34a816cc
DM
1349
1350 let path = format!("api2/json/admin/datastore/{}/status", repo.store());
1351
1dc117bb 1352 let mut result = client.get(&path, None).await?;
14e08625 1353 let mut data = result["data"].take();
34a816cc
DM
1354
1355 record_repository(&repo);
1356
390c5bdd
DM
1357 let render_total_percentage = |v: &Value, record: &Value| -> Result<String, Error> {
1358 let v = v.as_u64().unwrap();
1359 let total = record["total"].as_u64().unwrap();
1360 let roundup = total/200;
1361 let per = ((v+roundup)*100)/total;
e23f5863
DM
1362 let info = format!(" ({} %)", per);
1363 Ok(format!("{} {:>8}", v, info))
390c5bdd 1364 };
1dc117bb 1365
c2043614 1366 let options = default_table_format_options()
be2425ff 1367 .noheader(true)
e23f5863 1368 .column(ColumnConfig::new("total").renderer(render_total_percentage))
390c5bdd
DM
1369 .column(ColumnConfig::new("used").renderer(render_total_percentage))
1370 .column(ColumnConfig::new("avail").renderer(render_total_percentage));
34a816cc 1371
b2362a12 1372 let return_type = &API_METHOD_STATUS.returns;
390c5bdd 1373
b2362a12 1374 format_and_print_result_full(&mut data, return_type, &output_format, &options);
34a816cc
DM
1375
1376 Ok(Value::Null)
1377}
1378
c443f58b
WB
1379use proxmox_backup::client::RemoteChunkReader;
1380/// This is a workaround until we have cleaned up the chunk/reader/... infrastructure for better
1381/// async use!
1382///
1383/// Ideally BufferedDynamicReader gets replaced so the LruCache maps to `BroadcastFuture<Chunk>`,
1384/// so that we can properly access it from multiple threads simultaneously while not issuing
1385/// duplicate simultaneous reads over http.
43abba4b 1386pub struct BufferedDynamicReadAt {
c443f58b
WB
1387 inner: Mutex<BufferedDynamicReader<RemoteChunkReader>>,
1388}
1389
1390impl BufferedDynamicReadAt {
1391 fn new(inner: BufferedDynamicReader<RemoteChunkReader>) -> Self {
1392 Self {
1393 inner: Mutex::new(inner),
1394 }
1395 }
1396}
1397
a6f87283
WB
1398impl ReadAt for BufferedDynamicReadAt {
1399 fn start_read_at<'a>(
1400 self: Pin<&'a Self>,
c443f58b 1401 _cx: &mut Context,
a6f87283 1402 buf: &'a mut [u8],
c443f58b 1403 offset: u64,
a6f87283 1404 ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> {
a6f87283 1405 MaybeReady::Ready(tokio::task::block_in_place(move || {
c443f58b
WB
1406 let mut reader = self.inner.lock().unwrap();
1407 reader.seek(SeekFrom::Start(offset))?;
a6f87283
WB
1408 Ok(reader.read(buf)?)
1409 }))
1410 }
1411
1412 fn poll_complete<'a>(
1413 self: Pin<&'a Self>,
1414 _op: ReadAtOperation<'a>,
1415 ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> {
1416 panic!("LocalDynamicReadAt::start_read_at returned Pending");
c443f58b
WB
1417 }
1418}
1419
f2401311 1420fn main() {
33d64b81 1421
255f378a 1422 let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP)
49fddd98 1423 .arg_param(&["backupspec"])
d0a03d40 1424 .completion_cb("repository", complete_repository)
49811347 1425 .completion_cb("backupspec", complete_backup_source)
6d0983db 1426 .completion_cb("keyfile", tools::complete_file_name)
c0a87c12 1427 .completion_cb("master-pubkey-file", tools::complete_file_name)
49811347 1428 .completion_cb("chunk-size", complete_chunk_size);
f8838fe9 1429
caea8d61
DM
1430 let benchmark_cmd_def = CliCommand::new(&API_METHOD_BENCHMARK)
1431 .completion_cb("repository", complete_repository)
1432 .completion_cb("keyfile", tools::complete_file_name);
1433
255f378a 1434 let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS)
d0a03d40 1435 .completion_cb("repository", complete_repository);
41c039e1 1436
255f378a 1437 let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
d0a03d40 1438 .completion_cb("repository", complete_repository);
8cc0d6af 1439
255f378a 1440 let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE)
49fddd98 1441 .arg_param(&["snapshot", "archive-name", "target"])
b2388518 1442 .completion_cb("repository", complete_repository)
08dc340a
DM
1443 .completion_cb("snapshot", complete_group_or_snapshot)
1444 .completion_cb("archive-name", complete_archive_name)
1445 .completion_cb("target", tools::complete_file_name);
9f912493 1446
255f378a 1447 let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE)
49fddd98 1448 .arg_param(&["group"])
9fdc3ef4 1449 .completion_cb("group", complete_backup_group)
d0a03d40 1450 .completion_cb("repository", complete_repository);
9f912493 1451
255f378a 1452 let status_cmd_def = CliCommand::new(&API_METHOD_STATUS)
34a816cc
DM
1453 .completion_cb("repository", complete_repository);
1454
255f378a 1455 let login_cmd_def = CliCommand::new(&API_METHOD_API_LOGIN)
e240d8be
DM
1456 .completion_cb("repository", complete_repository);
1457
255f378a 1458 let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT)
e240d8be 1459 .completion_cb("repository", complete_repository);
32efac1c 1460
e39974af
TL
1461 let version_cmd_def = CliCommand::new(&API_METHOD_API_VERSION)
1462 .completion_cb("repository", complete_repository);
1463
344add38
DW
1464 let change_owner_cmd_def = CliCommand::new(&API_METHOD_CHANGE_BACKUP_OWNER)
1465 .arg_param(&["group", "new-owner"])
1466 .completion_cb("group", complete_backup_group)
0224c3c2 1467 .completion_cb("new-owner", complete_auth_id)
344add38
DW
1468 .completion_cb("repository", complete_repository);
1469
41c039e1 1470 let cmd_def = CliCommandMap::new()
48ef3c33 1471 .insert("backup", backup_cmd_def)
48ef3c33
DM
1472 .insert("garbage-collect", garbage_collect_cmd_def)
1473 .insert("list", list_cmd_def)
1474 .insert("login", login_cmd_def)
1475 .insert("logout", logout_cmd_def)
1476 .insert("prune", prune_cmd_def)
1477 .insert("restore", restore_cmd_def)
a65e3e4b 1478 .insert("snapshot", snapshot_mgtm_cli())
48ef3c33 1479 .insert("status", status_cmd_def)
9696f519 1480 .insert("key", key::cli())
43abba4b 1481 .insert("mount", mount_cmd_def())
45f9b32e
SR
1482 .insert("map", map_cmd_def())
1483 .insert("unmap", unmap_cmd_def())
5830c205 1484 .insert("catalog", catalog_mgmt_cli())
caea8d61 1485 .insert("task", task_mgmt_cli())
e39974af 1486 .insert("version", version_cmd_def)
344add38 1487 .insert("benchmark", benchmark_cmd_def)
731eeef2
DM
1488 .insert("change-owner", change_owner_cmd_def)
1489
61205f00 1490 .alias(&["files"], &["snapshot", "files"])
edebd523 1491 .alias(&["forget"], &["snapshot", "forget"])
0c9209b0 1492 .alias(&["upload-log"], &["snapshot", "upload-log"])
731eeef2
DM
1493 .alias(&["snapshots"], &["snapshot", "list"])
1494 ;
48ef3c33 1495
7b22acd0
DM
1496 let rpcenv = CliEnvironment::new();
1497 run_cli_command(cmd_def, rpcenv, Some(|future| {
d420962f 1498 pbs_runtime::main(future)
d08bc483 1499 }));
ff5d3707 1500}