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