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