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