]>
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 | keyfile: { | |
879 | schema: KEYFILE_SCHEMA, | |
880 | optional: true, | |
881 | }, | |
882 | "keyfd": { | |
883 | schema: KEYFD_SCHEMA, | |
884 | optional: true, | |
885 | }, | |
886 | "crypt-mode": { | |
887 | type: CryptMode, | |
888 | optional: true, | |
889 | }, | |
890 | "skip-lost-and-found": { | |
891 | type: Boolean, | |
892 | description: "Skip lost+found directory.", | |
893 | optional: true, | |
894 | }, | |
895 | "backup-type": { | |
896 | schema: BACKUP_TYPE_SCHEMA, | |
897 | optional: true, | |
898 | }, | |
899 | "backup-id": { | |
900 | schema: BACKUP_ID_SCHEMA, | |
901 | optional: true, | |
902 | }, | |
903 | "backup-time": { | |
904 | schema: BACKUP_TIME_SCHEMA, | |
905 | optional: true, | |
906 | }, | |
907 | "chunk-size": { | |
908 | schema: CHUNK_SIZE_SCHEMA, | |
909 | optional: true, | |
910 | }, | |
911 | "exclude": { | |
912 | type: Array, | |
913 | description: "List of paths or patterns for matching files to exclude.", | |
914 | optional: true, | |
915 | items: { | |
916 | type: String, | |
917 | description: "Path or match pattern.", | |
918 | } | |
919 | }, | |
920 | "entries-max": { | |
921 | type: Integer, | |
922 | description: "Max number of entries to hold in memory.", | |
923 | optional: true, | |
924 | default: proxmox_backup::pxar::ENCODER_MAX_ENTRIES as isize, | |
925 | }, | |
926 | "verbose": { | |
927 | type: Boolean, | |
928 | description: "Verbose output.", | |
929 | optional: true, | |
930 | }, | |
931 | } | |
932 | } | |
933 | )] | |
934 | /// Create (host) backup. | |
935 | async fn create_backup( | |
936 | param: Value, | |
937 | _info: &ApiMethod, | |
938 | _rpcenv: &mut dyn RpcEnvironment, | |
939 | ) -> Result<Value, Error> { | |
940 | ||
941 | let repo = extract_repository_from_value(¶m)?; | |
942 | ||
943 | let backupspec_list = tools::required_array_param(¶m, "backupspec")?; | |
944 | ||
945 | let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false); | |
946 | ||
947 | let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false); | |
948 | ||
949 | let verbose = param["verbose"].as_bool().unwrap_or(false); | |
950 | ||
951 | let backup_time_opt = param["backup-time"].as_i64(); | |
952 | ||
953 | let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize); | |
954 | ||
955 | if let Some(size) = chunk_size_opt { | |
956 | verify_chunk_size(size)?; | |
957 | } | |
958 | ||
959 | let (keydata, crypt_mode) = keyfile_parameters(¶m)?; | |
960 | ||
961 | let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename()); | |
962 | ||
963 | let backup_type = param["backup-type"].as_str().unwrap_or("host"); | |
964 | ||
965 | let include_dev = param["include-dev"].as_array(); | |
966 | ||
967 | let entries_max = param["entries-max"].as_u64() | |
968 | .unwrap_or(proxmox_backup::pxar::ENCODER_MAX_ENTRIES as u64); | |
969 | ||
970 | let empty = Vec::new(); | |
971 | let exclude_args = param["exclude"].as_array().unwrap_or(&empty); | |
972 | ||
973 | let mut pattern_list = Vec::with_capacity(exclude_args.len()); | |
974 | for entry in exclude_args { | |
975 | let entry = entry.as_str().ok_or_else(|| format_err!("Invalid pattern string slice"))?; | |
976 | pattern_list.push( | |
977 | MatchEntry::parse_pattern(entry, PatternFlag::PATH_NAME, MatchType::Exclude) | |
978 | .map_err(|err| format_err!("invalid exclude pattern entry: {}", err))? | |
979 | ); | |
980 | } | |
981 | ||
982 | let mut devices = if all_file_systems { None } else { Some(HashSet::new()) }; | |
983 | ||
984 | if let Some(include_dev) = include_dev { | |
985 | if all_file_systems { | |
986 | bail!("option 'all-file-systems' conflicts with option 'include-dev'"); | |
987 | } | |
988 | ||
989 | let mut set = HashSet::new(); | |
990 | for path in include_dev { | |
991 | let path = path.as_str().unwrap(); | |
992 | let stat = nix::sys::stat::stat(path) | |
993 | .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?; | |
994 | set.insert(stat.st_dev); | |
995 | } | |
996 | devices = Some(set); | |
997 | } | |
998 | ||
999 | let mut upload_list = vec![]; | |
1000 | let mut target_set = HashSet::new(); | |
1001 | ||
1002 | for backupspec in backupspec_list { | |
1003 | let spec = parse_backup_specification(backupspec.as_str().unwrap())?; | |
1004 | let filename = &spec.config_string; | |
1005 | let target = &spec.archive_name; | |
1006 | ||
1007 | if target_set.contains(target) { | |
1008 | bail!("got target twice: '{}'", target); | |
1009 | } | |
1010 | target_set.insert(target.to_string()); | |
1011 | ||
1012 | use std::os::unix::fs::FileTypeExt; | |
1013 | ||
1014 | let metadata = std::fs::metadata(filename) | |
1015 | .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?; | |
1016 | let file_type = metadata.file_type(); | |
1017 | ||
1018 | match spec.spec_type { | |
1019 | BackupSpecificationType::PXAR => { | |
1020 | if !file_type.is_dir() { | |
1021 | bail!("got unexpected file type (expected directory)"); | |
1022 | } | |
1023 | upload_list.push((BackupSpecificationType::PXAR, filename.to_owned(), format!("{}.didx", target), 0)); | |
1024 | } | |
1025 | BackupSpecificationType::IMAGE => { | |
1026 | if !(file_type.is_file() || file_type.is_block_device()) { | |
1027 | bail!("got unexpected file type (expected file or block device)"); | |
1028 | } | |
1029 | ||
1030 | let size = image_size(&PathBuf::from(filename))?; | |
1031 | ||
1032 | if size == 0 { bail!("got zero-sized file '{}'", filename); } | |
1033 | ||
1034 | upload_list.push((BackupSpecificationType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size)); | |
1035 | } | |
1036 | BackupSpecificationType::CONFIG => { | |
1037 | if !file_type.is_file() { | |
1038 | bail!("got unexpected file type (expected regular file)"); | |
1039 | } | |
1040 | upload_list.push((BackupSpecificationType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len())); | |
1041 | } | |
1042 | BackupSpecificationType::LOGFILE => { | |
1043 | if !file_type.is_file() { | |
1044 | bail!("got unexpected file type (expected regular file)"); | |
1045 | } | |
1046 | upload_list.push((BackupSpecificationType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len())); | |
1047 | } | |
1048 | } | |
1049 | } | |
1050 | ||
1051 | let backup_time = backup_time_opt.unwrap_or_else(|| epoch_i64()); | |
1052 | ||
1053 | let client = connect(&repo)?; | |
1054 | record_repository(&repo); | |
1055 | ||
1056 | println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time)?); | |
1057 | ||
1058 | println!("Client name: {}", proxmox::tools::nodename()); | |
1059 | ||
1060 | let start_time = std::time::Instant::now(); | |
1061 | ||
1062 | println!("Starting backup protocol: {}", strftime_local("%c", epoch_i64())?); | |
1063 | ||
1064 | let (crypt_config, rsa_encrypted_key) = match keydata { | |
1065 | None => (None, None), | |
1066 | Some(key) => { | |
1067 | let (key, created) = decrypt_key(&key, &key::get_encryption_key_password)?; | |
1068 | ||
1069 | let crypt_config = CryptConfig::new(key)?; | |
1070 | ||
1071 | match key::find_master_pubkey()? { | |
1072 | Some(ref path) if path.exists() => { | |
1073 | let pem_data = file_get_contents(path)?; | |
1074 | let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?; | |
1075 | let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?; | |
1076 | (Some(Arc::new(crypt_config)), Some(enc_key)) | |
1077 | } | |
1078 | _ => (Some(Arc::new(crypt_config)), None), | |
1079 | } | |
1080 | } | |
1081 | }; | |
1082 | ||
1083 | let client = BackupWriter::start( | |
1084 | client, | |
1085 | crypt_config.clone(), | |
1086 | repo.store(), | |
1087 | backup_type, | |
1088 | &backup_id, | |
1089 | backup_time, | |
1090 | verbose, | |
1091 | false | |
1092 | ).await?; | |
1093 | ||
1094 | let previous_manifest = if let Ok(previous_manifest) = client.download_previous_manifest().await { | |
1095 | Some(Arc::new(previous_manifest)) | |
1096 | } else { | |
1097 | None | |
1098 | }; | |
1099 | ||
1100 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time)?; | |
1101 | let mut manifest = BackupManifest::new(snapshot); | |
1102 | ||
1103 | let mut catalog = None; | |
1104 | let mut catalog_result_tx = None; | |
1105 | ||
1106 | for (backup_type, filename, target, size) in upload_list { | |
1107 | match backup_type { | |
1108 | BackupSpecificationType::CONFIG => { | |
1109 | println!("Upload config file '{}' to '{}' as {}", filename, repo, target); | |
1110 | let stats = client | |
1111 | .upload_blob_from_file(&filename, &target, true, crypt_mode == CryptMode::Encrypt) | |
1112 | .await?; | |
1113 | manifest.add_file(target, stats.size, stats.csum, crypt_mode)?; | |
1114 | } | |
1115 | BackupSpecificationType::LOGFILE => { // fixme: remove - not needed anymore ? | |
1116 | println!("Upload log file '{}' to '{}' as {}", filename, repo, target); | |
1117 | let stats = client | |
1118 | .upload_blob_from_file(&filename, &target, true, crypt_mode == CryptMode::Encrypt) | |
1119 | .await?; | |
1120 | manifest.add_file(target, stats.size, stats.csum, crypt_mode)?; | |
1121 | } | |
1122 | BackupSpecificationType::PXAR => { | |
1123 | // start catalog upload on first use | |
1124 | if catalog.is_none() { | |
1125 | let (cat, res) = spawn_catalog_upload(client.clone(), crypt_mode == CryptMode::Encrypt)?; | |
1126 | catalog = Some(cat); | |
1127 | catalog_result_tx = Some(res); | |
1128 | } | |
1129 | let catalog = catalog.as_ref().unwrap(); | |
1130 | ||
1131 | println!("Upload directory '{}' to '{}' as {}", filename, repo, target); | |
1132 | catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?; | |
1133 | let stats = backup_directory( | |
1134 | &client, | |
1135 | previous_manifest.clone(), | |
1136 | &filename, | |
1137 | &target, | |
1138 | chunk_size_opt, | |
1139 | devices.clone(), | |
1140 | verbose, | |
1141 | skip_lost_and_found, | |
1142 | catalog.clone(), | |
1143 | pattern_list.clone(), | |
1144 | entries_max as usize, | |
1145 | true, | |
1146 | crypt_mode == CryptMode::Encrypt, | |
1147 | ).await?; | |
1148 | manifest.add_file(target, stats.size, stats.csum, crypt_mode)?; | |
1149 | catalog.lock().unwrap().end_directory()?; | |
1150 | } | |
1151 | BackupSpecificationType::IMAGE => { | |
1152 | println!("Upload image '{}' to '{:?}' as {}", filename, repo, target); | |
1153 | let stats = backup_image( | |
1154 | &client, | |
1155 | previous_manifest.clone(), | |
1156 | &filename, | |
1157 | &target, | |
1158 | size, | |
1159 | chunk_size_opt, | |
1160 | true, | |
1161 | crypt_mode == CryptMode::Encrypt, | |
1162 | verbose, | |
1163 | ).await?; | |
1164 | manifest.add_file(target, stats.size, stats.csum, crypt_mode)?; | |
1165 | } | |
1166 | } | |
1167 | } | |
1168 | ||
1169 | // finalize and upload catalog | |
1170 | if let Some(catalog) = catalog { | |
1171 | let mutex = Arc::try_unwrap(catalog) | |
1172 | .map_err(|_| format_err!("unable to get catalog (still used)"))?; | |
1173 | let mut catalog = mutex.into_inner().unwrap(); | |
1174 | ||
1175 | catalog.finish()?; | |
1176 | ||
1177 | drop(catalog); // close upload stream | |
1178 | ||
1179 | if let Some(catalog_result_rx) = catalog_result_tx { | |
1180 | let stats = catalog_result_rx.await??; | |
1181 | manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum, crypt_mode)?; | |
1182 | } | |
1183 | } | |
1184 | ||
1185 | if let Some(rsa_encrypted_key) = rsa_encrypted_key { | |
1186 | let target = "rsa-encrypted.key.blob"; | |
1187 | println!("Upload RSA encoded key to '{:?}' as {}", repo, target); | |
1188 | let stats = client | |
1189 | .upload_blob_from_data(rsa_encrypted_key, target, false, false) | |
1190 | .await?; | |
1191 | manifest.add_file(target.to_string(), stats.size, stats.csum, crypt_mode)?; | |
1192 | ||
1193 | // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t | |
1194 | /* | |
1195 | let mut buffer2 = vec![0u8; rsa.size() as usize]; | |
1196 | let pem_data = file_get_contents("master-private.pem")?; | |
1197 | let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?; | |
1198 | let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?; | |
1199 | println!("TEST {} {:?}", len, buffer2); | |
1200 | */ | |
1201 | } | |
1202 | // create manifest (index.json) | |
1203 | // manifests are never encrypted, but include a signature | |
1204 | let manifest = manifest.to_string(crypt_config.as_ref().map(Arc::as_ref)) | |
1205 | .map_err(|err| format_err!("unable to format manifest - {}", err))?; | |
1206 | ||
1207 | ||
1208 | if verbose { println!("Upload index.json to '{}'", repo) }; | |
1209 | client | |
1210 | .upload_blob_from_data(manifest.into_bytes(), MANIFEST_BLOB_NAME, true, false) | |
1211 | .await?; | |
1212 | ||
1213 | client.finish().await?; | |
1214 | ||
1215 | let end_time = std::time::Instant::now(); | |
1216 | let elapsed = end_time.duration_since(start_time); | |
1217 | println!("Duration: {:.2}s", elapsed.as_secs_f64()); | |
1218 | ||
1219 | println!("End Time: {}", strftime_local("%c", epoch_i64())?); | |
1220 | ||
1221 | Ok(Value::Null) | |
1222 | } | |
1223 | ||
1224 | fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
1225 | ||
1226 | let mut result = vec![]; | |
1227 | ||
1228 | let data: Vec<&str> = arg.splitn(2, ':').collect(); | |
1229 | ||
1230 | if data.len() != 2 { | |
1231 | result.push(String::from("root.pxar:/")); | |
1232 | result.push(String::from("etc.pxar:/etc")); | |
1233 | return result; | |
1234 | } | |
1235 | ||
1236 | let files = tools::complete_file_name(data[1], param); | |
1237 | ||
1238 | for file in files { | |
1239 | result.push(format!("{}:{}", data[0], file)); | |
1240 | } | |
1241 | ||
1242 | result | |
1243 | } | |
1244 | ||
1245 | async fn dump_image<W: Write>( | |
1246 | client: Arc<BackupReader>, | |
1247 | crypt_config: Option<Arc<CryptConfig>>, | |
1248 | crypt_mode: CryptMode, | |
1249 | index: FixedIndexReader, | |
1250 | mut writer: W, | |
1251 | verbose: bool, | |
1252 | ) -> Result<(), Error> { | |
1253 | ||
1254 | let most_used = index.find_most_used_chunks(8); | |
1255 | ||
1256 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, crypt_mode, most_used); | |
1257 | ||
1258 | // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy | |
1259 | // and thus slows down reading. Instead, directly use RemoteChunkReader | |
1260 | let mut per = 0; | |
1261 | let mut bytes = 0; | |
1262 | let start_time = std::time::Instant::now(); | |
1263 | ||
1264 | for pos in 0..index.index_count() { | |
1265 | let digest = index.index_digest(pos).unwrap(); | |
1266 | let raw_data = chunk_reader.read_chunk(&digest).await?; | |
1267 | writer.write_all(&raw_data)?; | |
1268 | bytes += raw_data.len(); | |
1269 | if verbose { | |
1270 | let next_per = ((pos+1)*100)/index.index_count(); | |
1271 | if per != next_per { | |
1272 | eprintln!("progress {}% (read {} bytes, duration {} sec)", | |
1273 | next_per, bytes, start_time.elapsed().as_secs()); | |
1274 | per = next_per; | |
1275 | } | |
1276 | } | |
1277 | } | |
1278 | ||
1279 | let end_time = std::time::Instant::now(); | |
1280 | let elapsed = end_time.duration_since(start_time); | |
1281 | eprintln!("restore image complete (bytes={}, duration={:.2}s, speed={:.2}MB/s)", | |
1282 | bytes, | |
1283 | elapsed.as_secs_f64(), | |
1284 | bytes as f64/(1024.0*1024.0*elapsed.as_secs_f64()) | |
1285 | ); | |
1286 | ||
1287 | ||
1288 | Ok(()) | |
1289 | } | |
1290 | ||
1291 | fn parse_archive_type(name: &str) -> (String, ArchiveType) { | |
1292 | if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") { | |
1293 | (name.into(), archive_type(name).unwrap()) | |
1294 | } else if name.ends_with(".pxar") { | |
1295 | (format!("{}.didx", name), ArchiveType::DynamicIndex) | |
1296 | } else if name.ends_with(".img") { | |
1297 | (format!("{}.fidx", name), ArchiveType::FixedIndex) | |
1298 | } else { | |
1299 | (format!("{}.blob", name), ArchiveType::Blob) | |
1300 | } | |
1301 | } | |
1302 | ||
1303 | #[api( | |
1304 | input: { | |
1305 | properties: { | |
1306 | repository: { | |
1307 | schema: REPO_URL_SCHEMA, | |
1308 | optional: true, | |
1309 | }, | |
1310 | snapshot: { | |
1311 | type: String, | |
1312 | description: "Group/Snapshot path.", | |
1313 | }, | |
1314 | "archive-name": { | |
1315 | description: "Backup archive name.", | |
1316 | type: String, | |
1317 | }, | |
1318 | target: { | |
1319 | type: String, | |
1320 | description: r###"Target directory path. Use '-' to write to standard output. | |
1321 | ||
1322 | We do not extraxt '.pxar' archives when writing to standard output. | |
1323 | ||
1324 | "### | |
1325 | }, | |
1326 | "allow-existing-dirs": { | |
1327 | type: Boolean, | |
1328 | description: "Do not fail if directories already exists.", | |
1329 | optional: true, | |
1330 | }, | |
1331 | keyfile: { | |
1332 | schema: KEYFILE_SCHEMA, | |
1333 | optional: true, | |
1334 | }, | |
1335 | "keyfd": { | |
1336 | schema: KEYFD_SCHEMA, | |
1337 | optional: true, | |
1338 | }, | |
1339 | "crypt-mode": { | |
1340 | type: CryptMode, | |
1341 | optional: true, | |
1342 | }, | |
1343 | } | |
1344 | } | |
1345 | )] | |
1346 | /// Restore backup repository. | |
1347 | async fn restore(param: Value) -> Result<Value, Error> { | |
1348 | let repo = extract_repository_from_value(¶m)?; | |
1349 | ||
1350 | let verbose = param["verbose"].as_bool().unwrap_or(false); | |
1351 | ||
1352 | let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false); | |
1353 | ||
1354 | let archive_name = tools::required_string_param(¶m, "archive-name")?; | |
1355 | ||
1356 | let client = connect(&repo)?; | |
1357 | ||
1358 | record_repository(&repo); | |
1359 | ||
1360 | let path = tools::required_string_param(¶m, "snapshot")?; | |
1361 | ||
1362 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { | |
1363 | let group: BackupGroup = path.parse()?; | |
1364 | api_datastore_latest_snapshot(&client, repo.store(), group).await? | |
1365 | } else { | |
1366 | let snapshot: BackupDir = path.parse()?; | |
1367 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) | |
1368 | }; | |
1369 | ||
1370 | let target = tools::required_string_param(¶m, "target")?; | |
1371 | let target = if target == "-" { None } else { Some(target) }; | |
1372 | ||
1373 | let (keydata, _crypt_mode) = keyfile_parameters(¶m)?; | |
1374 | ||
1375 | let crypt_config = match keydata { | |
1376 | None => None, | |
1377 | Some(key) => { | |
1378 | let (key, _) = decrypt_key(&key, &key::get_encryption_key_password)?; | |
1379 | Some(Arc::new(CryptConfig::new(key)?)) | |
1380 | } | |
1381 | }; | |
1382 | ||
1383 | let client = BackupReader::start( | |
1384 | client, | |
1385 | crypt_config.clone(), | |
1386 | repo.store(), | |
1387 | &backup_type, | |
1388 | &backup_id, | |
1389 | backup_time, | |
1390 | true, | |
1391 | ).await?; | |
1392 | ||
1393 | let (manifest, backup_index_data) = client.download_manifest().await?; | |
1394 | ||
1395 | let (archive_name, archive_type) = parse_archive_type(archive_name); | |
1396 | ||
1397 | if archive_name == MANIFEST_BLOB_NAME { | |
1398 | if let Some(target) = target { | |
1399 | replace_file(target, &backup_index_data, CreateOptions::new())?; | |
1400 | } else { | |
1401 | let stdout = std::io::stdout(); | |
1402 | let mut writer = stdout.lock(); | |
1403 | writer.write_all(&backup_index_data) | |
1404 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
1405 | } | |
1406 | ||
1407 | return Ok(Value::Null); | |
1408 | } | |
1409 | ||
1410 | let file_info = manifest.lookup_file_info(&archive_name)?; | |
1411 | ||
1412 | if archive_type == ArchiveType::Blob { | |
1413 | ||
1414 | let mut reader = client.download_blob(&manifest, &archive_name).await?; | |
1415 | ||
1416 | if let Some(target) = target { | |
1417 | let mut writer = 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 | std::io::copy(&mut reader, &mut writer)?; | |
1424 | } else { | |
1425 | let stdout = std::io::stdout(); | |
1426 | let mut writer = stdout.lock(); | |
1427 | std::io::copy(&mut reader, &mut writer) | |
1428 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
1429 | } | |
1430 | ||
1431 | } else if archive_type == ArchiveType::DynamicIndex { | |
1432 | ||
1433 | let index = client.download_dynamic_index(&manifest, &archive_name).await?; | |
1434 | ||
1435 | let most_used = index.find_most_used_chunks(8); | |
1436 | ||
1437 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, file_info.chunk_crypt_mode(), most_used); | |
1438 | ||
1439 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); | |
1440 | ||
1441 | if let Some(target) = target { | |
1442 | proxmox_backup::pxar::extract_archive( | |
1443 | pxar::decoder::Decoder::from_std(reader)?, | |
1444 | Path::new(target), | |
1445 | &[], | |
1446 | true, | |
1447 | proxmox_backup::pxar::Flags::DEFAULT, | |
1448 | allow_existing_dirs, | |
1449 | |path| { | |
1450 | if verbose { | |
1451 | println!("{:?}", path); | |
1452 | } | |
1453 | }, | |
1454 | None, | |
1455 | ) | |
1456 | .map_err(|err| format_err!("error extracting archive - {}", err))?; | |
1457 | } else { | |
1458 | let mut writer = std::fs::OpenOptions::new() | |
1459 | .write(true) | |
1460 | .open("/dev/stdout") | |
1461 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?; | |
1462 | ||
1463 | std::io::copy(&mut reader, &mut writer) | |
1464 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
1465 | } | |
1466 | } else if archive_type == ArchiveType::FixedIndex { | |
1467 | ||
1468 | let index = client.download_fixed_index(&manifest, &archive_name).await?; | |
1469 | ||
1470 | let mut writer = if let Some(target) = target { | |
1471 | std::fs::OpenOptions::new() | |
1472 | .write(true) | |
1473 | .create(true) | |
1474 | .create_new(true) | |
1475 | .open(target) | |
1476 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))? | |
1477 | } else { | |
1478 | std::fs::OpenOptions::new() | |
1479 | .write(true) | |
1480 | .open("/dev/stdout") | |
1481 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))? | |
1482 | }; | |
1483 | ||
1484 | dump_image(client.clone(), crypt_config.clone(), file_info.chunk_crypt_mode(), index, &mut writer, verbose).await?; | |
1485 | } | |
1486 | ||
1487 | Ok(Value::Null) | |
1488 | } | |
1489 | ||
1490 | #[api( | |
1491 | input: { | |
1492 | properties: { | |
1493 | repository: { | |
1494 | schema: REPO_URL_SCHEMA, | |
1495 | optional: true, | |
1496 | }, | |
1497 | snapshot: { | |
1498 | type: String, | |
1499 | description: "Group/Snapshot path.", | |
1500 | }, | |
1501 | logfile: { | |
1502 | type: String, | |
1503 | description: "The path to the log file you want to upload.", | |
1504 | }, | |
1505 | keyfile: { | |
1506 | schema: KEYFILE_SCHEMA, | |
1507 | optional: true, | |
1508 | }, | |
1509 | "keyfd": { | |
1510 | schema: KEYFD_SCHEMA, | |
1511 | optional: true, | |
1512 | }, | |
1513 | "crypt-mode": { | |
1514 | type: CryptMode, | |
1515 | optional: true, | |
1516 | }, | |
1517 | } | |
1518 | } | |
1519 | )] | |
1520 | /// Upload backup log file. | |
1521 | async fn upload_log(param: Value) -> Result<Value, Error> { | |
1522 | ||
1523 | let logfile = tools::required_string_param(¶m, "logfile")?; | |
1524 | let repo = extract_repository_from_value(¶m)?; | |
1525 | ||
1526 | let snapshot = tools::required_string_param(¶m, "snapshot")?; | |
1527 | let snapshot: BackupDir = snapshot.parse()?; | |
1528 | ||
1529 | let mut client = connect(&repo)?; | |
1530 | ||
1531 | let (keydata, crypt_mode) = keyfile_parameters(¶m)?; | |
1532 | ||
1533 | let crypt_config = match keydata { | |
1534 | None => None, | |
1535 | Some(key) => { | |
1536 | let (key, _created) = decrypt_key(&key, &key::get_encryption_key_password)?; | |
1537 | let crypt_config = CryptConfig::new(key)?; | |
1538 | Some(Arc::new(crypt_config)) | |
1539 | } | |
1540 | }; | |
1541 | ||
1542 | let data = file_get_contents(logfile)?; | |
1543 | ||
1544 | // fixme: howto sign log? | |
1545 | let blob = match crypt_mode { | |
1546 | CryptMode::None | CryptMode::SignOnly => DataBlob::encode(&data, None, true)?, | |
1547 | CryptMode::Encrypt => DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?, | |
1548 | }; | |
1549 | ||
1550 | let raw_data = blob.into_inner(); | |
1551 | ||
1552 | let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store()); | |
1553 | ||
1554 | let args = json!({ | |
1555 | "backup-type": snapshot.group().backup_type(), | |
1556 | "backup-id": snapshot.group().backup_id(), | |
1557 | "backup-time": snapshot.backup_time(), | |
1558 | }); | |
1559 | ||
1560 | let body = hyper::Body::from(raw_data); | |
1561 | ||
1562 | client.upload("application/octet-stream", body, &path, Some(args)).await | |
1563 | } | |
1564 | ||
1565 | const API_METHOD_PRUNE: ApiMethod = ApiMethod::new( | |
1566 | &ApiHandler::Async(&prune), | |
1567 | &ObjectSchema::new( | |
1568 | "Prune a backup repository.", | |
1569 | &proxmox_backup::add_common_prune_prameters!([ | |
1570 | ("dry-run", true, &BooleanSchema::new( | |
1571 | "Just show what prune would do, but do not delete anything.") | |
1572 | .schema()), | |
1573 | ("group", false, &StringSchema::new("Backup group.").schema()), | |
1574 | ], [ | |
1575 | ("output-format", true, &OUTPUT_FORMAT), | |
1576 | ( | |
1577 | "quiet", | |
1578 | true, | |
1579 | &BooleanSchema::new("Minimal output - only show removals.") | |
1580 | .schema() | |
1581 | ), | |
1582 | ("repository", true, &REPO_URL_SCHEMA), | |
1583 | ]) | |
1584 | ) | |
1585 | ); | |
1586 | ||
1587 | fn prune<'a>( | |
1588 | param: Value, | |
1589 | _info: &ApiMethod, | |
1590 | _rpcenv: &'a mut dyn RpcEnvironment, | |
1591 | ) -> proxmox::api::ApiFuture<'a> { | |
1592 | async move { | |
1593 | prune_async(param).await | |
1594 | }.boxed() | |
1595 | } | |
1596 | ||
1597 | async fn prune_async(mut param: Value) -> Result<Value, Error> { | |
1598 | let repo = extract_repository_from_value(¶m)?; | |
1599 | ||
1600 | let mut client = connect(&repo)?; | |
1601 | ||
1602 | let path = format!("api2/json/admin/datastore/{}/prune", repo.store()); | |
1603 | ||
1604 | let group = tools::required_string_param(¶m, "group")?; | |
1605 | let group: BackupGroup = group.parse()?; | |
1606 | ||
1607 | let output_format = get_output_format(¶m); | |
1608 | ||
1609 | let quiet = param["quiet"].as_bool().unwrap_or(false); | |
1610 | ||
1611 | param.as_object_mut().unwrap().remove("repository"); | |
1612 | param.as_object_mut().unwrap().remove("group"); | |
1613 | param.as_object_mut().unwrap().remove("output-format"); | |
1614 | param.as_object_mut().unwrap().remove("quiet"); | |
1615 | ||
1616 | param["backup-type"] = group.backup_type().into(); | |
1617 | param["backup-id"] = group.backup_id().into(); | |
1618 | ||
1619 | let mut result = client.post(&path, Some(param)).await?; | |
1620 | ||
1621 | record_repository(&repo); | |
1622 | ||
1623 | let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> { | |
1624 | let item: PruneListItem = serde_json::from_value(record.to_owned())?; | |
1625 | let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time)?; | |
1626 | Ok(snapshot.relative_path().to_str().unwrap().to_owned()) | |
1627 | }; | |
1628 | ||
1629 | let render_prune_action = |v: &Value, _record: &Value| -> Result<String, Error> { | |
1630 | Ok(match v.as_bool() { | |
1631 | Some(true) => "keep", | |
1632 | Some(false) => "remove", | |
1633 | None => "unknown", | |
1634 | }.to_string()) | |
1635 | }; | |
1636 | ||
1637 | let options = default_table_format_options() | |
1638 | .sortby("backup-type", false) | |
1639 | .sortby("backup-id", false) | |
1640 | .sortby("backup-time", false) | |
1641 | .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot")) | |
1642 | .column(ColumnConfig::new("backup-time").renderer(tools::format::render_epoch).header("date")) | |
1643 | .column(ColumnConfig::new("keep").renderer(render_prune_action).header("action")) | |
1644 | ; | |
1645 | ||
1646 | let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_PRUNE; | |
1647 | ||
1648 | let mut data = result["data"].take(); | |
1649 | ||
1650 | if quiet { | |
1651 | let list: Vec<Value> = data.as_array().unwrap().iter().filter(|item| { | |
1652 | item["keep"].as_bool() == Some(false) | |
1653 | }).map(|v| v.clone()).collect(); | |
1654 | data = list.into(); | |
1655 | } | |
1656 | ||
1657 | format_and_print_result_full(&mut data, info, &output_format, &options); | |
1658 | ||
1659 | Ok(Value::Null) | |
1660 | } | |
1661 | ||
1662 | #[api( | |
1663 | input: { | |
1664 | properties: { | |
1665 | repository: { | |
1666 | schema: REPO_URL_SCHEMA, | |
1667 | optional: true, | |
1668 | }, | |
1669 | "output-format": { | |
1670 | schema: OUTPUT_FORMAT, | |
1671 | optional: true, | |
1672 | }, | |
1673 | } | |
1674 | }, | |
1675 | returns: { | |
1676 | type: StorageStatus, | |
1677 | }, | |
1678 | )] | |
1679 | /// Get repository status. | |
1680 | async fn status(param: Value) -> Result<Value, Error> { | |
1681 | ||
1682 | let repo = extract_repository_from_value(¶m)?; | |
1683 | ||
1684 | let output_format = get_output_format(¶m); | |
1685 | ||
1686 | let client = connect(&repo)?; | |
1687 | ||
1688 | let path = format!("api2/json/admin/datastore/{}/status", repo.store()); | |
1689 | ||
1690 | let mut result = client.get(&path, None).await?; | |
1691 | let mut data = result["data"].take(); | |
1692 | ||
1693 | record_repository(&repo); | |
1694 | ||
1695 | let render_total_percentage = |v: &Value, record: &Value| -> Result<String, Error> { | |
1696 | let v = v.as_u64().unwrap(); | |
1697 | let total = record["total"].as_u64().unwrap(); | |
1698 | let roundup = total/200; | |
1699 | let per = ((v+roundup)*100)/total; | |
1700 | let info = format!(" ({} %)", per); | |
1701 | Ok(format!("{} {:>8}", v, info)) | |
1702 | }; | |
1703 | ||
1704 | let options = default_table_format_options() | |
1705 | .noheader(true) | |
1706 | .column(ColumnConfig::new("total").renderer(render_total_percentage)) | |
1707 | .column(ColumnConfig::new("used").renderer(render_total_percentage)) | |
1708 | .column(ColumnConfig::new("avail").renderer(render_total_percentage)); | |
1709 | ||
1710 | let schema = &API_RETURN_SCHEMA_STATUS; | |
1711 | ||
1712 | format_and_print_result_full(&mut data, schema, &output_format, &options); | |
1713 | ||
1714 | Ok(Value::Null) | |
1715 | } | |
1716 | ||
1717 | // like get, but simply ignore errors and return Null instead | |
1718 | async fn try_get(repo: &BackupRepository, url: &str) -> Value { | |
1719 | ||
1720 | let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok(); | |
1721 | let password = std::env::var(ENV_VAR_PBS_PASSWORD).ok(); | |
1722 | ||
1723 | let options = HttpClientOptions::new() | |
1724 | .prefix(Some("proxmox-backup".to_string())) | |
1725 | .password(password) | |
1726 | .interactive(false) | |
1727 | .fingerprint(fingerprint) | |
1728 | .fingerprint_cache(true) | |
1729 | .ticket_cache(true); | |
1730 | ||
1731 | let client = match HttpClient::new(repo.host(), repo.port(), repo.auth_id(), options) { | |
1732 | Ok(v) => v, | |
1733 | _ => return Value::Null, | |
1734 | }; | |
1735 | ||
1736 | let mut resp = match client.get(url, None).await { | |
1737 | Ok(v) => v, | |
1738 | _ => return Value::Null, | |
1739 | }; | |
1740 | ||
1741 | if let Some(map) = resp.as_object_mut() { | |
1742 | if let Some(data) = map.remove("data") { | |
1743 | return data; | |
1744 | } | |
1745 | } | |
1746 | Value::Null | |
1747 | } | |
1748 | ||
1749 | fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
1750 | proxmox_backup::tools::runtime::main(async { complete_backup_group_do(param).await }) | |
1751 | } | |
1752 | ||
1753 | async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> { | |
1754 | ||
1755 | let mut result = vec![]; | |
1756 | ||
1757 | let repo = match extract_repository_from_map(param) { | |
1758 | Some(v) => v, | |
1759 | _ => return result, | |
1760 | }; | |
1761 | ||
1762 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); | |
1763 | ||
1764 | let data = try_get(&repo, &path).await; | |
1765 | ||
1766 | if let Some(list) = data.as_array() { | |
1767 | for item in list { | |
1768 | if let (Some(backup_id), Some(backup_type)) = | |
1769 | (item["backup-id"].as_str(), item["backup-type"].as_str()) | |
1770 | { | |
1771 | result.push(format!("{}/{}", backup_type, backup_id)); | |
1772 | } | |
1773 | } | |
1774 | } | |
1775 | ||
1776 | result | |
1777 | } | |
1778 | ||
1779 | pub fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
1780 | proxmox_backup::tools::runtime::main(async { complete_group_or_snapshot_do(arg, param).await }) | |
1781 | } | |
1782 | ||
1783 | async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
1784 | ||
1785 | if arg.matches('/').count() < 2 { | |
1786 | let groups = complete_backup_group_do(param).await; | |
1787 | let mut result = vec![]; | |
1788 | for group in groups { | |
1789 | result.push(group.to_string()); | |
1790 | result.push(format!("{}/", group)); | |
1791 | } | |
1792 | return result; | |
1793 | } | |
1794 | ||
1795 | complete_backup_snapshot_do(param).await | |
1796 | } | |
1797 | ||
1798 | fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
1799 | proxmox_backup::tools::runtime::main(async { complete_backup_snapshot_do(param).await }) | |
1800 | } | |
1801 | ||
1802 | async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> { | |
1803 | ||
1804 | let mut result = vec![]; | |
1805 | ||
1806 | let repo = match extract_repository_from_map(param) { | |
1807 | Some(v) => v, | |
1808 | _ => return result, | |
1809 | }; | |
1810 | ||
1811 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); | |
1812 | ||
1813 | let data = try_get(&repo, &path).await; | |
1814 | ||
1815 | if let Some(list) = data.as_array() { | |
1816 | for item in list { | |
1817 | if let (Some(backup_id), Some(backup_type), Some(backup_time)) = | |
1818 | (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64()) | |
1819 | { | |
1820 | if let Ok(snapshot) = BackupDir::new(backup_type, backup_id, backup_time) { | |
1821 | result.push(snapshot.relative_path().to_str().unwrap().to_owned()); | |
1822 | } | |
1823 | } | |
1824 | } | |
1825 | } | |
1826 | ||
1827 | result | |
1828 | } | |
1829 | ||
1830 | fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
1831 | proxmox_backup::tools::runtime::main(async { complete_server_file_name_do(param).await }) | |
1832 | } | |
1833 | ||
1834 | async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> { | |
1835 | ||
1836 | let mut result = vec![]; | |
1837 | ||
1838 | let repo = match extract_repository_from_map(param) { | |
1839 | Some(v) => v, | |
1840 | _ => return result, | |
1841 | }; | |
1842 | ||
1843 | let snapshot: BackupDir = match param.get("snapshot") { | |
1844 | Some(path) => { | |
1845 | match path.parse() { | |
1846 | Ok(v) => v, | |
1847 | _ => return result, | |
1848 | } | |
1849 | } | |
1850 | _ => return result, | |
1851 | }; | |
1852 | ||
1853 | let query = tools::json_object_to_query(json!({ | |
1854 | "backup-type": snapshot.group().backup_type(), | |
1855 | "backup-id": snapshot.group().backup_id(), | |
1856 | "backup-time": snapshot.backup_time(), | |
1857 | })).unwrap(); | |
1858 | ||
1859 | let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query); | |
1860 | ||
1861 | let data = try_get(&repo, &path).await; | |
1862 | ||
1863 | if let Some(list) = data.as_array() { | |
1864 | for item in list { | |
1865 | if let Some(filename) = item["filename"].as_str() { | |
1866 | result.push(filename.to_owned()); | |
1867 | } | |
1868 | } | |
1869 | } | |
1870 | ||
1871 | result | |
1872 | } | |
1873 | ||
1874 | fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
1875 | complete_server_file_name(arg, param) | |
1876 | .iter() | |
1877 | .map(|v| tools::format::strip_server_file_extension(&v)) | |
1878 | .collect() | |
1879 | } | |
1880 | ||
1881 | pub fn complete_pxar_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
1882 | complete_server_file_name(arg, param) | |
1883 | .iter() | |
1884 | .filter_map(|name| { | |
1885 | if name.ends_with(".pxar.didx") { | |
1886 | Some(tools::format::strip_server_file_extension(name)) | |
1887 | } else { | |
1888 | None | |
1889 | } | |
1890 | }) | |
1891 | .collect() | |
1892 | } | |
1893 | ||
1894 | pub fn complete_img_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
1895 | complete_server_file_name(arg, param) | |
1896 | .iter() | |
1897 | .filter_map(|name| { | |
1898 | if name.ends_with(".img.fidx") { | |
1899 | Some(tools::format::strip_server_file_extension(name)) | |
1900 | } else { | |
1901 | None | |
1902 | } | |
1903 | }) | |
1904 | .collect() | |
1905 | } | |
1906 | ||
1907 | fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { | |
1908 | ||
1909 | let mut result = vec![]; | |
1910 | ||
1911 | let mut size = 64; | |
1912 | loop { | |
1913 | result.push(size.to_string()); | |
1914 | size *= 2; | |
1915 | if size > 4096 { break; } | |
1916 | } | |
1917 | ||
1918 | result | |
1919 | } | |
1920 | ||
1921 | fn complete_auth_id(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
1922 | proxmox_backup::tools::runtime::main(async { complete_auth_id_do(param).await }) | |
1923 | } | |
1924 | ||
1925 | async fn complete_auth_id_do(param: &HashMap<String, String>) -> Vec<String> { | |
1926 | ||
1927 | let mut result = vec![]; | |
1928 | ||
1929 | let repo = match extract_repository_from_map(param) { | |
1930 | Some(v) => v, | |
1931 | _ => return result, | |
1932 | }; | |
1933 | ||
1934 | let data = try_get(&repo, "api2/json/access/users?include_tokens=true").await; | |
1935 | ||
1936 | if let Ok(parsed) = serde_json::from_value::<Vec<UserWithTokens>>(data) { | |
1937 | for user in parsed { | |
1938 | result.push(user.userid.to_string()); | |
1939 | for token in user.tokens { | |
1940 | result.push(token.tokenid.to_string()); | |
1941 | } | |
1942 | } | |
1943 | }; | |
1944 | ||
1945 | result | |
1946 | } | |
1947 | ||
1948 | use proxmox_backup::client::RemoteChunkReader; | |
1949 | /// This is a workaround until we have cleaned up the chunk/reader/... infrastructure for better | |
1950 | /// async use! | |
1951 | /// | |
1952 | /// Ideally BufferedDynamicReader gets replaced so the LruCache maps to `BroadcastFuture<Chunk>`, | |
1953 | /// so that we can properly access it from multiple threads simultaneously while not issuing | |
1954 | /// duplicate simultaneous reads over http. | |
1955 | pub struct BufferedDynamicReadAt { | |
1956 | inner: Mutex<BufferedDynamicReader<RemoteChunkReader>>, | |
1957 | } | |
1958 | ||
1959 | impl BufferedDynamicReadAt { | |
1960 | fn new(inner: BufferedDynamicReader<RemoteChunkReader>) -> Self { | |
1961 | Self { | |
1962 | inner: Mutex::new(inner), | |
1963 | } | |
1964 | } | |
1965 | } | |
1966 | ||
1967 | impl ReadAt for BufferedDynamicReadAt { | |
1968 | fn start_read_at<'a>( | |
1969 | self: Pin<&'a Self>, | |
1970 | _cx: &mut Context, | |
1971 | buf: &'a mut [u8], | |
1972 | offset: u64, | |
1973 | ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> { | |
1974 | MaybeReady::Ready(tokio::task::block_in_place(move || { | |
1975 | let mut reader = self.inner.lock().unwrap(); | |
1976 | reader.seek(SeekFrom::Start(offset))?; | |
1977 | Ok(reader.read(buf)?) | |
1978 | })) | |
1979 | } | |
1980 | ||
1981 | fn poll_complete<'a>( | |
1982 | self: Pin<&'a Self>, | |
1983 | _op: ReadAtOperation<'a>, | |
1984 | ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> { | |
1985 | panic!("LocalDynamicReadAt::start_read_at returned Pending"); | |
1986 | } | |
1987 | } | |
1988 | ||
1989 | fn main() { | |
1990 | ||
1991 | let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP) | |
1992 | .arg_param(&["backupspec"]) | |
1993 | .completion_cb("repository", complete_repository) | |
1994 | .completion_cb("backupspec", complete_backup_source) | |
1995 | .completion_cb("keyfile", tools::complete_file_name) | |
1996 | .completion_cb("chunk-size", complete_chunk_size); | |
1997 | ||
1998 | let benchmark_cmd_def = CliCommand::new(&API_METHOD_BENCHMARK) | |
1999 | .completion_cb("repository", complete_repository) | |
2000 | .completion_cb("keyfile", tools::complete_file_name); | |
2001 | ||
2002 | let upload_log_cmd_def = CliCommand::new(&API_METHOD_UPLOAD_LOG) | |
2003 | .arg_param(&["snapshot", "logfile"]) | |
2004 | .completion_cb("snapshot", complete_backup_snapshot) | |
2005 | .completion_cb("logfile", tools::complete_file_name) | |
2006 | .completion_cb("keyfile", tools::complete_file_name) | |
2007 | .completion_cb("repository", complete_repository); | |
2008 | ||
2009 | let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS) | |
2010 | .completion_cb("repository", complete_repository); | |
2011 | ||
2012 | let snapshots_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOTS) | |
2013 | .arg_param(&["group"]) | |
2014 | .completion_cb("group", complete_backup_group) | |
2015 | .completion_cb("repository", complete_repository); | |
2016 | ||
2017 | let forget_cmd_def = CliCommand::new(&API_METHOD_FORGET_SNAPSHOTS) | |
2018 | .arg_param(&["snapshot"]) | |
2019 | .completion_cb("repository", complete_repository) | |
2020 | .completion_cb("snapshot", complete_backup_snapshot); | |
2021 | ||
2022 | let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION) | |
2023 | .completion_cb("repository", complete_repository); | |
2024 | ||
2025 | let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE) | |
2026 | .arg_param(&["snapshot", "archive-name", "target"]) | |
2027 | .completion_cb("repository", complete_repository) | |
2028 | .completion_cb("snapshot", complete_group_or_snapshot) | |
2029 | .completion_cb("archive-name", complete_archive_name) | |
2030 | .completion_cb("target", tools::complete_file_name); | |
2031 | ||
2032 | let files_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOT_FILES) | |
2033 | .arg_param(&["snapshot"]) | |
2034 | .completion_cb("repository", complete_repository) | |
2035 | .completion_cb("snapshot", complete_backup_snapshot); | |
2036 | ||
2037 | let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE) | |
2038 | .arg_param(&["group"]) | |
2039 | .completion_cb("group", complete_backup_group) | |
2040 | .completion_cb("repository", complete_repository); | |
2041 | ||
2042 | let status_cmd_def = CliCommand::new(&API_METHOD_STATUS) | |
2043 | .completion_cb("repository", complete_repository); | |
2044 | ||
2045 | let login_cmd_def = CliCommand::new(&API_METHOD_API_LOGIN) | |
2046 | .completion_cb("repository", complete_repository); | |
2047 | ||
2048 | let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT) | |
2049 | .completion_cb("repository", complete_repository); | |
2050 | ||
2051 | let version_cmd_def = CliCommand::new(&API_METHOD_API_VERSION) | |
2052 | .completion_cb("repository", complete_repository); | |
2053 | ||
2054 | let change_owner_cmd_def = CliCommand::new(&API_METHOD_CHANGE_BACKUP_OWNER) | |
2055 | .arg_param(&["group", "new-owner"]) | |
2056 | .completion_cb("group", complete_backup_group) | |
2057 | .completion_cb("new-owner", complete_auth_id) | |
2058 | .completion_cb("repository", complete_repository); | |
2059 | ||
2060 | let cmd_def = CliCommandMap::new() | |
2061 | .insert("backup", backup_cmd_def) | |
2062 | .insert("upload-log", upload_log_cmd_def) | |
2063 | .insert("forget", forget_cmd_def) | |
2064 | .insert("garbage-collect", garbage_collect_cmd_def) | |
2065 | .insert("list", list_cmd_def) | |
2066 | .insert("login", login_cmd_def) | |
2067 | .insert("logout", logout_cmd_def) | |
2068 | .insert("prune", prune_cmd_def) | |
2069 | .insert("restore", restore_cmd_def) | |
2070 | .insert("snapshots", snapshots_cmd_def) | |
2071 | .insert("files", files_cmd_def) | |
2072 | .insert("status", status_cmd_def) | |
2073 | .insert("key", key::cli()) | |
2074 | .insert("mount", mount_cmd_def()) | |
2075 | .insert("map", map_cmd_def()) | |
2076 | .insert("unmap", unmap_cmd_def()) | |
2077 | .insert("catalog", catalog_mgmt_cli()) | |
2078 | .insert("task", task_mgmt_cli()) | |
2079 | .insert("version", version_cmd_def) | |
2080 | .insert("benchmark", benchmark_cmd_def) | |
2081 | .insert("change-owner", change_owner_cmd_def); | |
2082 | ||
2083 | let rpcenv = CliEnvironment::new(); | |
2084 | run_cli_command(cmd_def, rpcenv, Some(|future| { | |
2085 | proxmox_backup::tools::runtime::main(future) | |
2086 | })); | |
2087 | } |