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