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