]>
Commit | Line | Data |
---|---|---|
f1a83e97 | 1 | use std::collections::HashSet; |
0351f23b | 2 | use std::io::{self, Read, Write, Seek, SeekFrom}; |
c443f58b WB |
3 | use std::path::{Path, PathBuf}; |
4 | use std::pin::Pin; | |
5 | use std::sync::{Arc, Mutex}; | |
a6f87283 | 6 | use std::task::Context; |
c443f58b WB |
7 | |
8 | use anyhow::{bail, format_err, Error}; | |
c443f58b | 9 | use futures::stream::{StreamExt, TryStreamExt}; |
c443f58b | 10 | use serde_json::{json, Value}; |
c443f58b | 11 | use tokio::sync::mpsc; |
7c667013 | 12 | use tokio_stream::wrappers::ReceiverStream; |
c443f58b | 13 | use xdg::BaseDirectories; |
2761d6a4 | 14 | |
c443f58b | 15 | use pathpatterns::{MatchEntry, MatchType, PatternFlag}; |
726b9d44 | 16 | use proxmox_io::StdChannelWriter; |
25877d05 | 17 | use proxmox_sys::fs::{file_get_json, replace_file, CreateOptions, image_size}; |
6ef1b649 WB |
18 | use proxmox_router::{ApiMethod, RpcEnvironment, cli::*}; |
19 | use proxmox_schema::api; | |
20 | use proxmox_time::{strftime_local, epoch_i64}; | |
92a8f0bc | 21 | use proxmox_async::blocking::TokioWriterAdapter; |
a6f87283 | 22 | use pxar::accessor::{MaybeReady, ReadAt, ReadAtOperation}; |
ff5d3707 | 23 | |
51ec8a3c | 24 | use pbs_api_types::{ |
bfd12e87 DM |
25 | BACKUP_ID_SCHEMA, BACKUP_TIME_SCHEMA, BACKUP_TYPE_SCHEMA, |
26 | TRAFFIC_CONTROL_BURST_SCHEMA, TRAFFIC_CONTROL_RATE_SCHEMA, | |
2d5287fb DM |
27 | Authid, CryptMode, Fingerprint, GroupListItem, HumanByte, |
28 | PruneListItem, PruneOptions, RateLimitConfig, SnapshotListItem, | |
29 | StorageStatus, | |
51ec8a3c | 30 | }; |
2b7f8dd5 WB |
31 | use pbs_client::{ |
32 | BACKUP_SOURCE_SCHEMA, | |
33 | BackupReader, | |
34 | BackupRepository, | |
35 | BackupSpecificationType, | |
36 | BackupStats, | |
37 | BackupWriter, | |
38629c39 WB |
38 | ChunkStream, |
39 | FixedChunkStream, | |
2b7f8dd5 WB |
40 | HttpClient, |
41 | PxarBackupStream, | |
42 | RemoteChunkReader, | |
43 | UploadOptions, | |
44 | delete_ticket_info, | |
45 | parse_backup_specification, | |
46 | view_task_result, | |
47 | }; | |
48 | use pbs_client::catalog_shell::Shell; | |
49 | use pbs_client::tools::{ | |
50 | complete_archive_name, complete_auth_id, complete_backup_group, complete_backup_snapshot, | |
51 | complete_backup_source, complete_chunk_size, complete_group_or_snapshot, | |
52 | complete_img_archive_name, complete_pxar_archive_name, complete_repository, connect, | |
e4bc3e0e | 53 | connect_rate_limited, extract_repository_from_value, |
2b7f8dd5 WB |
54 | key_source::{ |
55 | crypto_parameters, format_key_source, get_encryption_key_password, KEYFD_SCHEMA, | |
56 | KEYFILE_SCHEMA, MASTER_PUBKEY_FD_SCHEMA, MASTER_PUBKEY_FILE_SCHEMA, | |
57 | }, | |
58 | CHUNK_SIZE_SCHEMA, REPO_URL_SCHEMA, | |
59 | }; | |
bbdda58b DM |
60 | use pbs_config::key_config::{KeyConfig, decrypt_key, rsa_encrypt_key_config}; |
61 | use pbs_datastore::CATALOG_NAME; | |
2b7f8dd5 | 62 | use pbs_datastore::backup_info::{BackupDir, BackupGroup}; |
51ec8a3c WB |
63 | use pbs_datastore::catalog::{BackupCatalogWriter, CatalogReader, CatalogWriter}; |
64 | use pbs_datastore::chunk_store::verify_chunk_size; | |
eb5e0ae6 | 65 | use pbs_datastore::dynamic_index::{BufferedDynamicReader, DynamicIndexReader}; |
2b7f8dd5 WB |
66 | use pbs_datastore::fixed_index::FixedIndexReader; |
67 | use pbs_datastore::index::IndexFile; | |
51ec8a3c WB |
68 | use pbs_datastore::manifest::{ |
69 | ENCRYPTED_KEY_BLOB_NAME, MANIFEST_BLOB_NAME, ArchiveType, BackupManifest, archive_type, | |
70 | }; | |
2b7f8dd5 | 71 | use pbs_datastore::read_chunk::AsyncReadChunk; |
3c8c2827 | 72 | use pbs_tools::json; |
bbdda58b | 73 | use pbs_tools::crypt_config::CryptConfig; |
f323e906 | 74 | |
e351ac78 WB |
75 | mod benchmark; |
76 | pub use benchmark::*; | |
77 | mod mount; | |
78 | pub use mount::*; | |
79 | mod task; | |
80 | pub use task::*; | |
81 | mod catalog; | |
82 | pub use catalog::*; | |
83 | mod snapshot; | |
84 | pub use snapshot::*; | |
85 | pub mod key; | |
caea8d61 | 86 | |
d0a03d40 DM |
87 | fn record_repository(repo: &BackupRepository) { |
88 | ||
89 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
90 | Ok(v) => v, | |
91 | _ => return, | |
92 | }; | |
93 | ||
94 | // usually $HOME/.cache/proxmox-backup/repo-list | |
95 | let path = match base.place_cache_file("repo-list") { | |
96 | Ok(v) => v, | |
97 | _ => return, | |
98 | }; | |
99 | ||
11377a47 | 100 | let mut data = file_get_json(&path, None).unwrap_or_else(|_| json!({})); |
d0a03d40 DM |
101 | |
102 | let repo = repo.to_string(); | |
103 | ||
104 | data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 }; | |
105 | ||
106 | let mut map = serde_json::map::Map::new(); | |
107 | ||
108 | loop { | |
109 | let mut max_used = 0; | |
110 | let mut max_repo = None; | |
111 | for (repo, count) in data.as_object().unwrap() { | |
112 | if map.contains_key(repo) { continue; } | |
113 | if let Some(count) = count.as_i64() { | |
114 | if count > max_used { | |
115 | max_used = count; | |
116 | max_repo = Some(repo); | |
117 | } | |
118 | } | |
119 | } | |
120 | if let Some(repo) = max_repo { | |
121 | map.insert(repo.to_owned(), json!(max_used)); | |
122 | } else { | |
123 | break; | |
124 | } | |
125 | if map.len() > 10 { // store max. 10 repos | |
126 | break; | |
127 | } | |
128 | } | |
129 | ||
130 | let new_data = json!(map); | |
131 | ||
e0a19d33 | 132 | let _ = replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new(), false); |
d0a03d40 DM |
133 | } |
134 | ||
42af4b8f DM |
135 | async fn api_datastore_list_snapshots( |
136 | client: &HttpClient, | |
137 | store: &str, | |
138 | group: Option<BackupGroup>, | |
f24fc116 | 139 | ) -> Result<Value, Error> { |
42af4b8f DM |
140 | |
141 | let path = format!("api2/json/admin/datastore/{}/snapshots", store); | |
142 | ||
143 | let mut args = json!({}); | |
144 | if let Some(group) = group { | |
145 | args["backup-type"] = group.backup_type().into(); | |
146 | args["backup-id"] = group.backup_id().into(); | |
147 | } | |
148 | ||
149 | let mut result = client.get(&path, Some(args)).await?; | |
150 | ||
f24fc116 | 151 | Ok(result["data"].take()) |
42af4b8f DM |
152 | } |
153 | ||
43abba4b | 154 | pub async fn api_datastore_latest_snapshot( |
27c9affb DM |
155 | client: &HttpClient, |
156 | store: &str, | |
157 | group: BackupGroup, | |
6a7be83e | 158 | ) -> Result<(String, String, i64), Error> { |
27c9affb | 159 | |
f24fc116 DM |
160 | let list = api_datastore_list_snapshots(client, store, Some(group.clone())).await?; |
161 | let mut list: Vec<SnapshotListItem> = serde_json::from_value(list)?; | |
27c9affb DM |
162 | |
163 | if list.is_empty() { | |
164 | bail!("backup group {:?} does not contain any snapshots.", group.group_path()); | |
165 | } | |
166 | ||
167 | list.sort_unstable_by(|a, b| b.backup_time.cmp(&a.backup_time)); | |
168 | ||
6a7be83e | 169 | let backup_time = list[0].backup_time; |
27c9affb DM |
170 | |
171 | Ok((group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time)) | |
172 | } | |
173 | ||
e9722f8b | 174 | async fn backup_directory<P: AsRef<Path>>( |
cf9271e2 | 175 | client: &BackupWriter, |
17d6979a | 176 | dir_path: P, |
247cdbce | 177 | archive_name: &str, |
36898ffc | 178 | chunk_size: Option<usize>, |
f35e187f | 179 | catalog: Arc<Mutex<CatalogWriter<TokioWriterAdapter<StdChannelWriter<Error>>>>>, |
2b7f8dd5 | 180 | pxar_create_options: pbs_client::pxar::PxarCreateOptions, |
e43b9175 | 181 | upload_options: UploadOptions, |
2c3891d1 | 182 | ) -> Result<BackupStats, Error> { |
33d64b81 | 183 | |
6fc053ed CE |
184 | let pxar_stream = PxarBackupStream::open( |
185 | dir_path.as_ref(), | |
6fc053ed | 186 | catalog, |
77486a60 | 187 | pxar_create_options, |
6fc053ed | 188 | )?; |
e9722f8b | 189 | let mut chunk_stream = ChunkStream::new(pxar_stream, chunk_size); |
ff3d3100 | 190 | |
0bfcea6a | 191 | let (tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks |
5e7a09be | 192 | |
7c667013 | 193 | let stream = ReceiverStream::new(rx) |
e9722f8b | 194 | .map_err(Error::from); |
17d6979a | 195 | |
c4ff3dce | 196 | // spawn chunker inside a separate task so that it can run parallel |
e9722f8b | 197 | tokio::spawn(async move { |
db0cb9ce WB |
198 | while let Some(v) = chunk_stream.next().await { |
199 | let _ = tx.send(v).await; | |
200 | } | |
e9722f8b | 201 | }); |
17d6979a | 202 | |
e43b9175 FG |
203 | if upload_options.fixed_size.is_some() { |
204 | bail!("cannot backup directory with fixed chunk size!"); | |
205 | } | |
206 | ||
e9722f8b | 207 | let stats = client |
e43b9175 | 208 | .upload_stream(archive_name, stream, upload_options) |
e9722f8b | 209 | .await?; |
bcd879cf | 210 | |
2c3891d1 | 211 | Ok(stats) |
bcd879cf DM |
212 | } |
213 | ||
e9722f8b | 214 | async fn backup_image<P: AsRef<Path>>( |
cf9271e2 | 215 | client: &BackupWriter, |
6af905c1 DM |
216 | image_path: P, |
217 | archive_name: &str, | |
36898ffc | 218 | chunk_size: Option<usize>, |
e43b9175 | 219 | upload_options: UploadOptions, |
2c3891d1 | 220 | ) -> Result<BackupStats, Error> { |
6af905c1 | 221 | |
6af905c1 DM |
222 | let path = image_path.as_ref().to_owned(); |
223 | ||
e9722f8b | 224 | let file = tokio::fs::File::open(path).await?; |
6af905c1 | 225 | |
db0cb9ce | 226 | let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new()) |
6af905c1 DM |
227 | .map_err(Error::from); |
228 | ||
36898ffc | 229 | let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024)); |
6af905c1 | 230 | |
e43b9175 FG |
231 | if upload_options.fixed_size.is_none() { |
232 | bail!("cannot backup image with dynamic chunk size!"); | |
233 | } | |
234 | ||
e9722f8b | 235 | let stats = client |
e43b9175 | 236 | .upload_stream(archive_name, stream, upload_options) |
e9722f8b | 237 | .await?; |
6af905c1 | 238 | |
2c3891d1 | 239 | Ok(stats) |
6af905c1 DM |
240 | } |
241 | ||
a47a02ae DM |
242 | #[api( |
243 | input: { | |
244 | properties: { | |
245 | repository: { | |
246 | schema: REPO_URL_SCHEMA, | |
247 | optional: true, | |
248 | }, | |
249 | "output-format": { | |
250 | schema: OUTPUT_FORMAT, | |
251 | optional: true, | |
252 | }, | |
253 | } | |
254 | } | |
255 | )] | |
256 | /// List backup groups. | |
257 | async fn list_backup_groups(param: Value) -> Result<Value, Error> { | |
812c6f87 | 258 | |
c81b2b7c DM |
259 | let output_format = get_output_format(¶m); |
260 | ||
2665cef7 | 261 | let repo = extract_repository_from_value(¶m)?; |
812c6f87 | 262 | |
f3fde36b | 263 | let client = connect(&repo)?; |
812c6f87 | 264 | |
d0a03d40 | 265 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
812c6f87 | 266 | |
8a8a4703 | 267 | let mut result = client.get(&path, None).await?; |
812c6f87 | 268 | |
d0a03d40 DM |
269 | record_repository(&repo); |
270 | ||
c81b2b7c DM |
271 | let render_group_path = |_v: &Value, record: &Value| -> Result<String, Error> { |
272 | let item: GroupListItem = serde_json::from_value(record.to_owned())?; | |
273 | let group = BackupGroup::new(item.backup_type, item.backup_id); | |
274 | Ok(group.group_path().to_str().unwrap().to_owned()) | |
275 | }; | |
812c6f87 | 276 | |
18deda40 DM |
277 | let render_last_backup = |_v: &Value, record: &Value| -> Result<String, Error> { |
278 | let item: GroupListItem = serde_json::from_value(record.to_owned())?; | |
e0e5b442 | 279 | let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.last_backup)?; |
18deda40 | 280 | Ok(snapshot.relative_path().to_str().unwrap().to_owned()) |
c81b2b7c | 281 | }; |
812c6f87 | 282 | |
c81b2b7c DM |
283 | let render_files = |_v: &Value, record: &Value| -> Result<String, Error> { |
284 | let item: GroupListItem = serde_json::from_value(record.to_owned())?; | |
770a36e5 | 285 | Ok(pbs_tools::format::render_backup_file_list(&item.files)) |
c81b2b7c | 286 | }; |
812c6f87 | 287 | |
c81b2b7c DM |
288 | let options = default_table_format_options() |
289 | .sortby("backup-type", false) | |
290 | .sortby("backup-id", false) | |
291 | .column(ColumnConfig::new("backup-id").renderer(render_group_path).header("group")) | |
18deda40 DM |
292 | .column( |
293 | ColumnConfig::new("last-backup") | |
294 | .renderer(render_last_backup) | |
295 | .header("last snapshot") | |
296 | .right_align(false) | |
297 | ) | |
c81b2b7c DM |
298 | .column(ColumnConfig::new("backup-count")) |
299 | .column(ColumnConfig::new("files").renderer(render_files)); | |
ad20d198 | 300 | |
c81b2b7c | 301 | let mut data: Value = result["data"].take(); |
ad20d198 | 302 | |
e351ac78 | 303 | let return_type = &pbs_api_types::ADMIN_DATASTORE_LIST_GROUPS_RETURN_TYPE; |
812c6f87 | 304 | |
b2362a12 | 305 | format_and_print_result_full(&mut data, return_type, &output_format, &options); |
34a816cc | 306 | |
812c6f87 DM |
307 | Ok(Value::Null) |
308 | } | |
309 | ||
344add38 DW |
310 | #[api( |
311 | input: { | |
312 | properties: { | |
313 | repository: { | |
314 | schema: REPO_URL_SCHEMA, | |
315 | optional: true, | |
316 | }, | |
317 | group: { | |
318 | type: String, | |
319 | description: "Backup group.", | |
320 | }, | |
321 | "new-owner": { | |
e6dc35ac | 322 | type: Authid, |
344add38 DW |
323 | }, |
324 | } | |
325 | } | |
326 | )] | |
327 | /// Change owner of a backup group | |
328 | async fn change_backup_owner(group: String, mut param: Value) -> Result<(), Error> { | |
329 | ||
330 | let repo = extract_repository_from_value(¶m)?; | |
331 | ||
d4877712 | 332 | let client = connect(&repo)?; |
344add38 DW |
333 | |
334 | param.as_object_mut().unwrap().remove("repository"); | |
335 | ||
336 | let group: BackupGroup = group.parse()?; | |
337 | ||
338 | param["backup-type"] = group.backup_type().into(); | |
339 | param["backup-id"] = group.backup_id().into(); | |
340 | ||
341 | let path = format!("api2/json/admin/datastore/{}/change-owner", repo.store()); | |
342 | client.post(&path, Some(param)).await?; | |
343 | ||
344 | record_repository(&repo); | |
345 | ||
346 | Ok(()) | |
347 | } | |
348 | ||
a47a02ae DM |
349 | #[api( |
350 | input: { | |
351 | properties: { | |
352 | repository: { | |
353 | schema: REPO_URL_SCHEMA, | |
354 | optional: true, | |
355 | }, | |
356 | } | |
357 | } | |
358 | )] | |
359 | /// Try to login. If successful, store ticket. | |
360 | async fn api_login(param: Value) -> Result<Value, Error> { | |
e240d8be DM |
361 | |
362 | let repo = extract_repository_from_value(¶m)?; | |
363 | ||
f3fde36b | 364 | let client = connect(&repo)?; |
8a8a4703 | 365 | client.login().await?; |
e240d8be DM |
366 | |
367 | record_repository(&repo); | |
368 | ||
369 | Ok(Value::Null) | |
370 | } | |
371 | ||
a47a02ae DM |
372 | #[api( |
373 | input: { | |
374 | properties: { | |
375 | repository: { | |
376 | schema: REPO_URL_SCHEMA, | |
377 | optional: true, | |
378 | }, | |
379 | } | |
380 | } | |
381 | )] | |
382 | /// Logout (delete stored ticket). | |
383 | fn api_logout(param: Value) -> Result<Value, Error> { | |
e240d8be DM |
384 | |
385 | let repo = extract_repository_from_value(¶m)?; | |
386 | ||
5030b7ce | 387 | delete_ticket_info("proxmox-backup", repo.host(), repo.user())?; |
e240d8be DM |
388 | |
389 | Ok(Value::Null) | |
390 | } | |
391 | ||
e39974af TL |
392 | #[api( |
393 | input: { | |
394 | properties: { | |
395 | repository: { | |
396 | schema: REPO_URL_SCHEMA, | |
397 | optional: true, | |
398 | }, | |
399 | "output-format": { | |
400 | schema: OUTPUT_FORMAT, | |
401 | optional: true, | |
402 | }, | |
403 | } | |
404 | } | |
405 | )] | |
406 | /// Show client and optional server version | |
407 | async fn api_version(param: Value) -> Result<(), Error> { | |
408 | ||
409 | let output_format = get_output_format(¶m); | |
410 | ||
411 | let mut version_info = json!({ | |
412 | "client": { | |
a12b1be7 WB |
413 | "version": pbs_buildcfg::PROXMOX_PKG_VERSION, |
414 | "release": pbs_buildcfg::PROXMOX_PKG_RELEASE, | |
415 | "repoid": pbs_buildcfg::PROXMOX_PKG_REPOID, | |
e39974af TL |
416 | } |
417 | }); | |
418 | ||
419 | let repo = extract_repository_from_value(¶m); | |
420 | if let Ok(repo) = repo { | |
f3fde36b | 421 | let client = connect(&repo)?; |
e39974af TL |
422 | |
423 | match client.get("api2/json/version", None).await { | |
424 | Ok(mut result) => version_info["server"] = result["data"].take(), | |
425 | Err(e) => eprintln!("could not connect to server - {}", e), | |
426 | } | |
427 | } | |
428 | if output_format == "text" { | |
a12b1be7 WB |
429 | println!( |
430 | "client version: {}.{}", | |
431 | pbs_buildcfg::PROXMOX_PKG_VERSION, | |
432 | pbs_buildcfg::PROXMOX_PKG_RELEASE, | |
433 | ); | |
e39974af TL |
434 | if let Some(server) = version_info["server"].as_object() { |
435 | let server_version = server["version"].as_str().unwrap(); | |
436 | let server_release = server["release"].as_str().unwrap(); | |
437 | println!("server version: {}.{}", server_version, server_release); | |
438 | } | |
439 | } else { | |
440 | format_and_print_result(&version_info, &output_format); | |
441 | } | |
442 | ||
443 | Ok(()) | |
444 | } | |
445 | ||
a47a02ae | 446 | #[api( |
94913f35 | 447 | input: { |
a47a02ae DM |
448 | properties: { |
449 | repository: { | |
450 | schema: REPO_URL_SCHEMA, | |
451 | optional: true, | |
452 | }, | |
94913f35 DM |
453 | "output-format": { |
454 | schema: OUTPUT_FORMAT, | |
455 | optional: true, | |
456 | }, | |
457 | }, | |
458 | }, | |
a47a02ae DM |
459 | )] |
460 | /// Start garbage collection for a specific repository. | |
461 | async fn start_garbage_collection(param: Value) -> Result<Value, Error> { | |
8cc0d6af | 462 | |
2665cef7 | 463 | let repo = extract_repository_from_value(¶m)?; |
c2043614 DM |
464 | |
465 | let output_format = get_output_format(¶m); | |
8cc0d6af | 466 | |
d4877712 | 467 | let client = connect(&repo)?; |
8cc0d6af | 468 | |
d0a03d40 | 469 | let path = format!("api2/json/admin/datastore/{}/gc", repo.store()); |
8cc0d6af | 470 | |
8a8a4703 | 471 | let result = client.post(&path, None).await?; |
8cc0d6af | 472 | |
8a8a4703 | 473 | record_repository(&repo); |
d0a03d40 | 474 | |
d4877712 | 475 | view_task_result(&client, result, &output_format).await?; |
e5f7def4 | 476 | |
e5f7def4 | 477 | Ok(Value::Null) |
8cc0d6af | 478 | } |
33d64b81 | 479 | |
6d233161 | 480 | struct CatalogUploadResult { |
f35e187f | 481 | catalog_writer: Arc<Mutex<CatalogWriter<TokioWriterAdapter<StdChannelWriter<Error>>>>>, |
6d233161 FG |
482 | result: tokio::sync::oneshot::Receiver<Result<BackupStats, Error>>, |
483 | } | |
484 | ||
bf6e3217 | 485 | fn spawn_catalog_upload( |
3bad3e6e | 486 | client: Arc<BackupWriter>, |
3638341a | 487 | encrypt: bool, |
6d233161 | 488 | ) -> Result<CatalogUploadResult, Error> { |
f1d99e3f | 489 | let (catalog_tx, catalog_rx) = std::sync::mpsc::sync_channel(10); // allow to buffer 10 writes |
9a1b24b6 | 490 | let catalog_stream = proxmox_async::blocking::StdChannelStream(catalog_rx); |
bf6e3217 DM |
491 | let catalog_chunk_size = 512*1024; |
492 | let catalog_chunk_stream = ChunkStream::new(catalog_stream, Some(catalog_chunk_size)); | |
493 | ||
f1d76ecf | 494 | let catalog_writer = Arc::new(Mutex::new(CatalogWriter::new(TokioWriterAdapter::new(StdChannelWriter::new(catalog_tx)))?)); |
bf6e3217 DM |
495 | |
496 | let (catalog_result_tx, catalog_result_rx) = tokio::sync::oneshot::channel(); | |
497 | ||
e43b9175 FG |
498 | let upload_options = UploadOptions { |
499 | encrypt, | |
500 | compress: true, | |
501 | ..UploadOptions::default() | |
502 | }; | |
503 | ||
bf6e3217 DM |
504 | tokio::spawn(async move { |
505 | let catalog_upload_result = client | |
e43b9175 | 506 | .upload_stream(CATALOG_NAME, catalog_chunk_stream, upload_options) |
bf6e3217 DM |
507 | .await; |
508 | ||
509 | if let Err(ref err) = catalog_upload_result { | |
510 | eprintln!("catalog upload error - {}", err); | |
511 | client.cancel(); | |
512 | } | |
513 | ||
514 | let _ = catalog_result_tx.send(catalog_upload_result); | |
515 | }); | |
516 | ||
6d233161 | 517 | Ok(CatalogUploadResult { catalog_writer, result: catalog_result_rx }) |
bf6e3217 DM |
518 | } |
519 | ||
a47a02ae DM |
520 | #[api( |
521 | input: { | |
522 | properties: { | |
523 | backupspec: { | |
524 | type: Array, | |
525 | description: "List of backup source specifications ([<label.ext>:<path>] ...)", | |
526 | items: { | |
527 | schema: BACKUP_SOURCE_SCHEMA, | |
528 | } | |
529 | }, | |
530 | repository: { | |
531 | schema: REPO_URL_SCHEMA, | |
532 | optional: true, | |
533 | }, | |
534 | "include-dev": { | |
535 | description: "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.", | |
536 | optional: true, | |
537 | items: { | |
538 | type: String, | |
539 | description: "Path to file.", | |
540 | } | |
541 | }, | |
58fcbf5a FE |
542 | "all-file-systems": { |
543 | type: Boolean, | |
544 | description: "Include all mounted subdirectories.", | |
545 | optional: true, | |
546 | }, | |
a47a02ae DM |
547 | keyfile: { |
548 | schema: KEYFILE_SCHEMA, | |
549 | optional: true, | |
550 | }, | |
0351f23b WB |
551 | "keyfd": { |
552 | schema: KEYFD_SCHEMA, | |
553 | optional: true, | |
554 | }, | |
c0a87c12 FG |
555 | "master-pubkey-file": { |
556 | schema: MASTER_PUBKEY_FILE_SCHEMA, | |
557 | optional: true, | |
558 | }, | |
559 | "master-pubkey-fd": { | |
560 | schema: MASTER_PUBKEY_FD_SCHEMA, | |
561 | optional: true, | |
562 | }, | |
24be37e3 WB |
563 | "crypt-mode": { |
564 | type: CryptMode, | |
96ee8577 WB |
565 | optional: true, |
566 | }, | |
a47a02ae DM |
567 | "skip-lost-and-found": { |
568 | type: Boolean, | |
569 | description: "Skip lost+found directory.", | |
570 | optional: true, | |
571 | }, | |
572 | "backup-type": { | |
573 | schema: BACKUP_TYPE_SCHEMA, | |
574 | optional: true, | |
575 | }, | |
576 | "backup-id": { | |
577 | schema: BACKUP_ID_SCHEMA, | |
578 | optional: true, | |
579 | }, | |
580 | "backup-time": { | |
581 | schema: BACKUP_TIME_SCHEMA, | |
582 | optional: true, | |
583 | }, | |
584 | "chunk-size": { | |
585 | schema: CHUNK_SIZE_SCHEMA, | |
586 | optional: true, | |
587 | }, | |
e4bc3e0e | 588 | rate: { |
bfd12e87 | 589 | schema: TRAFFIC_CONTROL_RATE_SCHEMA, |
e4bc3e0e | 590 | optional: true, |
e4bc3e0e DM |
591 | }, |
592 | burst: { | |
bfd12e87 | 593 | schema: TRAFFIC_CONTROL_BURST_SCHEMA, |
e4bc3e0e | 594 | optional: true, |
e4bc3e0e | 595 | }, |
189996cf CE |
596 | "exclude": { |
597 | type: Array, | |
598 | description: "List of paths or patterns for matching files to exclude.", | |
599 | optional: true, | |
600 | items: { | |
601 | type: String, | |
602 | description: "Path or match pattern.", | |
603 | } | |
604 | }, | |
6fc053ed CE |
605 | "entries-max": { |
606 | type: Integer, | |
607 | description: "Max number of entries to hold in memory.", | |
608 | optional: true, | |
2b7f8dd5 | 609 | default: pbs_client::pxar::ENCODER_MAX_ENTRIES as isize, |
6fc053ed | 610 | }, |
e02c3d46 DM |
611 | "verbose": { |
612 | type: Boolean, | |
613 | description: "Verbose output.", | |
614 | optional: true, | |
615 | }, | |
4b8395ee MF |
616 | "dry-run": { |
617 | type: Boolean, | |
618 | description: "Just show what backup would do, but do not upload anything.", | |
619 | optional: true, | |
620 | }, | |
a47a02ae DM |
621 | } |
622 | } | |
623 | )] | |
624 | /// Create (host) backup. | |
625 | async fn create_backup( | |
6049b71f DM |
626 | param: Value, |
627 | _info: &ApiMethod, | |
dd5495d6 | 628 | _rpcenv: &mut dyn RpcEnvironment, |
6049b71f | 629 | ) -> Result<Value, Error> { |
ff5d3707 | 630 | |
2665cef7 | 631 | let repo = extract_repository_from_value(¶m)?; |
ae0be2dd | 632 | |
3c8c2827 | 633 | let backupspec_list = json::required_array_param(¶m, "backupspec")?; |
a914a774 | 634 | |
eed6db39 DM |
635 | let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false); |
636 | ||
5b72c9b4 DM |
637 | let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false); |
638 | ||
219ef0e6 DM |
639 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
640 | ||
4b8395ee MF |
641 | let dry_run = param["dry-run"].as_bool().unwrap_or(false); |
642 | ||
ca5d0b61 DM |
643 | let backup_time_opt = param["backup-time"].as_i64(); |
644 | ||
36898ffc | 645 | let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize); |
2d9d143a | 646 | |
247cdbce DM |
647 | if let Some(size) = chunk_size_opt { |
648 | verify_chunk_size(size)?; | |
2d9d143a DM |
649 | } |
650 | ||
2d5287fb DM |
651 | let rate = match param["rate"].as_str() { |
652 | Some(s) => Some(s.parse::<HumanByte>()?), | |
653 | None => None, | |
654 | }; | |
655 | let burst = match param["burst"].as_str() { | |
656 | Some(s) => Some(s.parse::<HumanByte>()?), | |
657 | None => None, | |
658 | }; | |
659 | ||
660 | let rate_limit = RateLimitConfig::with_same_inout(rate, burst); | |
e4bc3e0e | 661 | |
c6a7ea0a | 662 | let crypto = crypto_parameters(¶m)?; |
6d0983db | 663 | |
9a37bd6c | 664 | let backup_id = param["backup-id"].as_str().unwrap_or(proxmox_sys::nodename()); |
fba30411 | 665 | |
bbf9e7e9 | 666 | let backup_type = param["backup-type"].as_str().unwrap_or("host"); |
ca5d0b61 | 667 | |
2eeaacb9 DM |
668 | let include_dev = param["include-dev"].as_array(); |
669 | ||
c443f58b | 670 | let entries_max = param["entries-max"].as_u64() |
2b7f8dd5 | 671 | .unwrap_or(pbs_client::pxar::ENCODER_MAX_ENTRIES as u64); |
6fc053ed | 672 | |
189996cf | 673 | let empty = Vec::new(); |
c443f58b WB |
674 | let exclude_args = param["exclude"].as_array().unwrap_or(&empty); |
675 | ||
239e49f9 | 676 | let mut pattern_list = Vec::with_capacity(exclude_args.len()); |
c443f58b WB |
677 | for entry in exclude_args { |
678 | let entry = entry.as_str().ok_or_else(|| format_err!("Invalid pattern string slice"))?; | |
239e49f9 | 679 | pattern_list.push( |
c443f58b WB |
680 | MatchEntry::parse_pattern(entry, PatternFlag::PATH_NAME, MatchType::Exclude) |
681 | .map_err(|err| format_err!("invalid exclude pattern entry: {}", err))? | |
682 | ); | |
189996cf CE |
683 | } |
684 | ||
2eeaacb9 DM |
685 | let mut devices = if all_file_systems { None } else { Some(HashSet::new()) }; |
686 | ||
687 | if let Some(include_dev) = include_dev { | |
688 | if all_file_systems { | |
689 | bail!("option 'all-file-systems' conflicts with option 'include-dev'"); | |
690 | } | |
691 | ||
692 | let mut set = HashSet::new(); | |
693 | for path in include_dev { | |
694 | let path = path.as_str().unwrap(); | |
695 | let stat = nix::sys::stat::stat(path) | |
696 | .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?; | |
697 | set.insert(stat.st_dev); | |
698 | } | |
699 | devices = Some(set); | |
700 | } | |
701 | ||
ae0be2dd | 702 | let mut upload_list = vec![]; |
f2b4b4b9 | 703 | let mut target_set = HashSet::new(); |
a914a774 | 704 | |
ae0be2dd | 705 | for backupspec in backupspec_list { |
7cc3473a DM |
706 | let spec = parse_backup_specification(backupspec.as_str().unwrap())?; |
707 | let filename = &spec.config_string; | |
708 | let target = &spec.archive_name; | |
bcd879cf | 709 | |
f2b4b4b9 SI |
710 | if target_set.contains(target) { |
711 | bail!("got target twice: '{}'", target); | |
712 | } | |
713 | target_set.insert(target.to_string()); | |
714 | ||
eb1804c5 DM |
715 | use std::os::unix::fs::FileTypeExt; |
716 | ||
3fa71727 CE |
717 | let metadata = std::fs::metadata(filename) |
718 | .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?; | |
eb1804c5 | 719 | let file_type = metadata.file_type(); |
23bb8780 | 720 | |
7cc3473a DM |
721 | match spec.spec_type { |
722 | BackupSpecificationType::PXAR => { | |
ec8a9bb9 DM |
723 | if !file_type.is_dir() { |
724 | bail!("got unexpected file type (expected directory)"); | |
725 | } | |
7cc3473a | 726 | upload_list.push((BackupSpecificationType::PXAR, filename.to_owned(), format!("{}.didx", target), 0)); |
ec8a9bb9 | 727 | } |
7cc3473a | 728 | BackupSpecificationType::IMAGE => { |
ec8a9bb9 DM |
729 | if !(file_type.is_file() || file_type.is_block_device()) { |
730 | bail!("got unexpected file type (expected file or block device)"); | |
731 | } | |
eb1804c5 | 732 | |
e18a6c9e | 733 | let size = image_size(&PathBuf::from(filename))?; |
23bb8780 | 734 | |
ec8a9bb9 | 735 | if size == 0 { bail!("got zero-sized file '{}'", filename); } |
ae0be2dd | 736 | |
7cc3473a | 737 | upload_list.push((BackupSpecificationType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size)); |
ec8a9bb9 | 738 | } |
7cc3473a | 739 | BackupSpecificationType::CONFIG => { |
ec8a9bb9 DM |
740 | if !file_type.is_file() { |
741 | bail!("got unexpected file type (expected regular file)"); | |
742 | } | |
7cc3473a | 743 | upload_list.push((BackupSpecificationType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len())); |
ec8a9bb9 | 744 | } |
7cc3473a | 745 | BackupSpecificationType::LOGFILE => { |
79679c2d DM |
746 | if !file_type.is_file() { |
747 | bail!("got unexpected file type (expected regular file)"); | |
748 | } | |
7cc3473a | 749 | upload_list.push((BackupSpecificationType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len())); |
ec8a9bb9 | 750 | } |
ae0be2dd DM |
751 | } |
752 | } | |
753 | ||
22a9189e | 754 | let backup_time = backup_time_opt.unwrap_or_else(epoch_i64); |
ae0be2dd | 755 | |
2d5287fb | 756 | let client = connect_rate_limited(&repo, rate_limit)?; |
d0a03d40 DM |
757 | record_repository(&repo); |
758 | ||
6a7be83e | 759 | println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time)?); |
ca5d0b61 | 760 | |
25877d05 | 761 | println!("Client name: {}", proxmox_sys::nodename()); |
ca5d0b61 | 762 | |
6a7be83e | 763 | let start_time = std::time::Instant::now(); |
ca5d0b61 | 764 | |
6a7be83e | 765 | println!("Starting backup protocol: {}", strftime_local("%c", epoch_i64())?); |
51144821 | 766 | |
c6a7ea0a | 767 | let (crypt_config, rsa_encrypted_key) = match crypto.enc_key { |
bb823140 | 768 | None => (None, None), |
2f26b866 FG |
769 | Some(key_with_source) => { |
770 | println!( | |
771 | "{}", | |
772 | format_key_source(&key_with_source.source, "encryption") | |
773 | ); | |
774 | ||
775 | let (key, created, fingerprint) = | |
ff8945fd | 776 | decrypt_key(&key_with_source.key, &get_encryption_key_password)?; |
6f2626ae | 777 | println!("Encryption key fingerprint: {}", fingerprint); |
bb823140 | 778 | |
44288184 | 779 | let crypt_config = CryptConfig::new(key)?; |
bb823140 | 780 | |
c0a87c12 | 781 | match crypto.master_pubkey { |
2f26b866 FG |
782 | Some(pem_with_source) => { |
783 | println!("{}", format_key_source(&pem_with_source.source, "master")); | |
784 | ||
785 | let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_with_source.key)?; | |
82a103c8 | 786 | |
1c86893d | 787 | let mut key_config = KeyConfig::without_password(key)?; |
82a103c8 | 788 | key_config.created = created; // keep original value |
82a103c8 | 789 | |
8acfd15d | 790 | let enc_key = rsa_encrypt_key_config(rsa, &key_config)?; |
6f2626ae | 791 | |
05389a01 | 792 | (Some(Arc::new(crypt_config)), Some(enc_key)) |
2f26b866 | 793 | }, |
05389a01 | 794 | _ => (Some(Arc::new(crypt_config)), None), |
bb823140 | 795 | } |
6d0983db DM |
796 | } |
797 | }; | |
f98ac774 | 798 | |
8a8a4703 DM |
799 | let client = BackupWriter::start( |
800 | client, | |
b957aa81 | 801 | crypt_config.clone(), |
8a8a4703 DM |
802 | repo.store(), |
803 | backup_type, | |
9a37bd6c | 804 | backup_id, |
8a8a4703 DM |
805 | backup_time, |
806 | verbose, | |
61d7b501 | 807 | false |
8a8a4703 DM |
808 | ).await?; |
809 | ||
8b7f8d3f FG |
810 | let download_previous_manifest = match client.previous_backup_time().await { |
811 | Ok(Some(backup_time)) => { | |
812 | println!( | |
813 | "Downloading previous manifest ({})", | |
814 | strftime_local("%c", backup_time)? | |
815 | ); | |
816 | true | |
817 | } | |
818 | Ok(None) => { | |
819 | println!("No previous manifest available."); | |
820 | false | |
821 | } | |
822 | Err(_) => { | |
823 | // Fallback for outdated server, TODO remove/bubble up with 2.0 | |
824 | true | |
825 | } | |
826 | }; | |
827 | ||
828 | let previous_manifest = if download_previous_manifest { | |
829 | match client.download_previous_manifest().await { | |
830 | Ok(previous_manifest) => { | |
831 | match previous_manifest.check_fingerprint(crypt_config.as_ref().map(Arc::as_ref)) { | |
832 | Ok(()) => Some(Arc::new(previous_manifest)), | |
833 | Err(err) => { | |
834 | println!("Couldn't re-use previous manifest - {}", err); | |
835 | None | |
836 | } | |
837 | } | |
23f9503a | 838 | } |
8b7f8d3f FG |
839 | Err(err) => { |
840 | println!("Couldn't download previous manifest - {}", err); | |
841 | None | |
842 | } | |
843 | } | |
844 | } else { | |
845 | None | |
b957aa81 DM |
846 | }; |
847 | ||
6a7be83e | 848 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time)?; |
8a8a4703 DM |
849 | let mut manifest = BackupManifest::new(snapshot); |
850 | ||
5d85847f | 851 | let mut catalog = None; |
6d233161 | 852 | let mut catalog_result_rx = None; |
8a8a4703 | 853 | |
4b8395ee MF |
854 | let printfileinfo = |butype:&str, filename:&str, repo:&pbs_client::BackupRepository, target:&str| { |
855 | if dry_run{ | |
856 | println!("Would upload {} '{}' to '{}' as {}", butype, filename, repo, target); | |
857 | } else { | |
858 | println!("Upload {} '{}' to '{}' as {}", butype, filename, repo, target); | |
859 | } | |
860 | }; | |
861 | ||
8a8a4703 | 862 | for (backup_type, filename, target, size) in upload_list { |
4b8395ee MF |
863 | match (backup_type, dry_run) { |
864 | (BackupSpecificationType::CONFIG, true) => { | |
865 | printfileinfo("config file", &filename, &repo, &target); | |
866 | } | |
867 | (BackupSpecificationType::LOGFILE, true) => { | |
868 | printfileinfo("log file", &filename, &repo, &target); | |
869 | } | |
870 | (BackupSpecificationType::PXAR, true) => { | |
871 | printfileinfo("directory", &filename, &repo, &target); | |
872 | } | |
873 | (BackupSpecificationType::IMAGE, true) => { | |
874 | printfileinfo("image", &filename, &repo, &target); | |
875 | } | |
876 | (BackupSpecificationType::CONFIG, false) => { | |
e43b9175 FG |
877 | let upload_options = UploadOptions { |
878 | compress: true, | |
c6a7ea0a | 879 | encrypt: crypto.mode == CryptMode::Encrypt, |
e43b9175 FG |
880 | ..UploadOptions::default() |
881 | }; | |
882 | ||
4b8395ee | 883 | printfileinfo("config file", &filename, &repo, &target); |
8a8a4703 | 884 | let stats = client |
e43b9175 | 885 | .upload_blob_from_file(&filename, &target, upload_options) |
8a8a4703 | 886 | .await?; |
c6a7ea0a | 887 | manifest.add_file(target, stats.size, stats.csum, crypto.mode)?; |
8a8a4703 | 888 | } |
4b8395ee | 889 | (BackupSpecificationType::LOGFILE, false) => { // fixme: remove - not needed anymore ? |
e43b9175 FG |
890 | let upload_options = UploadOptions { |
891 | compress: true, | |
c6a7ea0a | 892 | encrypt: crypto.mode == CryptMode::Encrypt, |
e43b9175 FG |
893 | ..UploadOptions::default() |
894 | }; | |
895 | ||
4b8395ee | 896 | printfileinfo("log file", &filename, &repo, &target); |
8a8a4703 | 897 | let stats = client |
e43b9175 | 898 | .upload_blob_from_file(&filename, &target, upload_options) |
8a8a4703 | 899 | .await?; |
c6a7ea0a | 900 | manifest.add_file(target, stats.size, stats.csum, crypto.mode)?; |
8a8a4703 | 901 | } |
4b8395ee | 902 | (BackupSpecificationType::PXAR, false) => { |
5d85847f DC |
903 | // start catalog upload on first use |
904 | if catalog.is_none() { | |
c6a7ea0a | 905 | let catalog_upload_res = spawn_catalog_upload(client.clone(), crypto.mode == CryptMode::Encrypt)?; |
6d233161 FG |
906 | catalog = Some(catalog_upload_res.catalog_writer); |
907 | catalog_result_rx = Some(catalog_upload_res.result); | |
5d85847f DC |
908 | } |
909 | let catalog = catalog.as_ref().unwrap(); | |
910 | ||
4b8395ee | 911 | printfileinfo("directory", &filename, &repo, &target); |
8a8a4703 | 912 | catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?; |
77486a60 | 913 | |
2b7f8dd5 | 914 | let pxar_options = pbs_client::pxar::PxarCreateOptions { |
77486a60 FG |
915 | device_set: devices.clone(), |
916 | patterns: pattern_list.clone(), | |
917 | entries_max: entries_max as usize, | |
918 | skip_lost_and_found, | |
919 | verbose, | |
920 | }; | |
921 | ||
e43b9175 FG |
922 | let upload_options = UploadOptions { |
923 | previous_manifest: previous_manifest.clone(), | |
924 | compress: true, | |
c6a7ea0a | 925 | encrypt: crypto.mode == CryptMode::Encrypt, |
e43b9175 FG |
926 | ..UploadOptions::default() |
927 | }; | |
928 | ||
8a8a4703 DM |
929 | let stats = backup_directory( |
930 | &client, | |
931 | &filename, | |
932 | &target, | |
933 | chunk_size_opt, | |
8a8a4703 | 934 | catalog.clone(), |
77486a60 | 935 | pxar_options, |
e43b9175 | 936 | upload_options, |
8a8a4703 | 937 | ).await?; |
c6a7ea0a | 938 | manifest.add_file(target, stats.size, stats.csum, crypto.mode)?; |
8a8a4703 DM |
939 | catalog.lock().unwrap().end_directory()?; |
940 | } | |
4b8395ee MF |
941 | (BackupSpecificationType::IMAGE, false) => { |
942 | printfileinfo("image", &filename, &repo, &target); | |
e43b9175 FG |
943 | |
944 | let upload_options = UploadOptions { | |
945 | previous_manifest: previous_manifest.clone(), | |
946 | fixed_size: Some(size), | |
947 | compress: true, | |
c6a7ea0a | 948 | encrypt: crypto.mode == CryptMode::Encrypt, |
e43b9175 FG |
949 | }; |
950 | ||
8a8a4703 DM |
951 | let stats = backup_image( |
952 | &client, | |
e43b9175 | 953 | &filename, |
8a8a4703 | 954 | &target, |
8a8a4703 | 955 | chunk_size_opt, |
e43b9175 | 956 | upload_options, |
8a8a4703 | 957 | ).await?; |
c6a7ea0a | 958 | manifest.add_file(target, stats.size, stats.csum, crypto.mode)?; |
6af905c1 DM |
959 | } |
960 | } | |
8a8a4703 | 961 | } |
4818c8b6 | 962 | |
4b8395ee MF |
963 | if dry_run { |
964 | println!("dry-run: no upload happend"); | |
965 | return Ok(Value::Null); | |
966 | } | |
967 | ||
8a8a4703 | 968 | // finalize and upload catalog |
5d85847f | 969 | if let Some(catalog) = catalog { |
8a8a4703 DM |
970 | let mutex = Arc::try_unwrap(catalog) |
971 | .map_err(|_| format_err!("unable to get catalog (still used)"))?; | |
972 | let mut catalog = mutex.into_inner().unwrap(); | |
bf6e3217 | 973 | |
8a8a4703 | 974 | catalog.finish()?; |
2761d6a4 | 975 | |
8a8a4703 | 976 | drop(catalog); // close upload stream |
2761d6a4 | 977 | |
6d233161 | 978 | if let Some(catalog_result_rx) = catalog_result_rx { |
5d85847f | 979 | let stats = catalog_result_rx.await??; |
c6a7ea0a | 980 | manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum, crypto.mode)?; |
5d85847f | 981 | } |
8a8a4703 | 982 | } |
2761d6a4 | 983 | |
8a8a4703 | 984 | if let Some(rsa_encrypted_key) = rsa_encrypted_key { |
9990af30 | 985 | let target = ENCRYPTED_KEY_BLOB_NAME; |
8a8a4703 | 986 | println!("Upload RSA encoded key to '{:?}' as {}", repo, target); |
e43b9175 | 987 | let options = UploadOptions { compress: false, encrypt: false, ..UploadOptions::default() }; |
8a8a4703 | 988 | let stats = client |
e43b9175 | 989 | .upload_blob_from_data(rsa_encrypted_key, target, options) |
8a8a4703 | 990 | .await?; |
c6a7ea0a | 991 | manifest.add_file(target.to_string(), stats.size, stats.csum, crypto.mode)?; |
8a8a4703 | 992 | |
8a8a4703 | 993 | } |
8a8a4703 | 994 | // create manifest (index.json) |
3638341a | 995 | // manifests are never encrypted, but include a signature |
dfa517ad | 996 | let manifest = manifest.to_string(crypt_config.as_ref().map(Arc::as_ref)) |
b53f6379 | 997 | .map_err(|err| format_err!("unable to format manifest - {}", err))?; |
3638341a | 998 | |
b53f6379 | 999 | |
9688f6de | 1000 | if verbose { println!("Upload index.json to '{}'", repo) }; |
e43b9175 | 1001 | let options = UploadOptions { compress: true, encrypt: false, ..UploadOptions::default() }; |
8a8a4703 | 1002 | client |
e43b9175 | 1003 | .upload_blob_from_data(manifest.into_bytes(), MANIFEST_BLOB_NAME, options) |
8a8a4703 | 1004 | .await?; |
2c3891d1 | 1005 | |
8a8a4703 | 1006 | client.finish().await?; |
c4ff3dce | 1007 | |
6a7be83e DM |
1008 | let end_time = std::time::Instant::now(); |
1009 | let elapsed = end_time.duration_since(start_time); | |
1010 | println!("Duration: {:.2}s", elapsed.as_secs_f64()); | |
3ec3ec3f | 1011 | |
6a7be83e | 1012 | println!("End Time: {}", strftime_local("%c", epoch_i64())?); |
3d5c11e5 | 1013 | |
8a8a4703 | 1014 | Ok(Value::Null) |
f98ea63d DM |
1015 | } |
1016 | ||
8e6e18b7 | 1017 | async fn dump_image<W: Write>( |
88892ea8 DM |
1018 | client: Arc<BackupReader>, |
1019 | crypt_config: Option<Arc<CryptConfig>>, | |
14f6c9cb | 1020 | crypt_mode: CryptMode, |
88892ea8 DM |
1021 | index: FixedIndexReader, |
1022 | mut writer: W, | |
fd04ca7a | 1023 | verbose: bool, |
88892ea8 DM |
1024 | ) -> Result<(), Error> { |
1025 | ||
1026 | let most_used = index.find_most_used_chunks(8); | |
1027 | ||
14f6c9cb | 1028 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, crypt_mode, most_used); |
88892ea8 DM |
1029 | |
1030 | // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy | |
1031 | // and thus slows down reading. Instead, directly use RemoteChunkReader | |
fd04ca7a DM |
1032 | let mut per = 0; |
1033 | let mut bytes = 0; | |
1034 | let start_time = std::time::Instant::now(); | |
1035 | ||
88892ea8 DM |
1036 | for pos in 0..index.index_count() { |
1037 | let digest = index.index_digest(pos).unwrap(); | |
9a37bd6c | 1038 | let raw_data = chunk_reader.read_chunk(digest).await?; |
88892ea8 | 1039 | writer.write_all(&raw_data)?; |
fd04ca7a DM |
1040 | bytes += raw_data.len(); |
1041 | if verbose { | |
1042 | let next_per = ((pos+1)*100)/index.index_count(); | |
1043 | if per != next_per { | |
1044 | eprintln!("progress {}% (read {} bytes, duration {} sec)", | |
1045 | next_per, bytes, start_time.elapsed().as_secs()); | |
1046 | per = next_per; | |
1047 | } | |
1048 | } | |
88892ea8 DM |
1049 | } |
1050 | ||
fd04ca7a DM |
1051 | let end_time = std::time::Instant::now(); |
1052 | let elapsed = end_time.duration_since(start_time); | |
1053 | eprintln!("restore image complete (bytes={}, duration={:.2}s, speed={:.2}MB/s)", | |
1054 | bytes, | |
1055 | elapsed.as_secs_f64(), | |
1056 | bytes as f64/(1024.0*1024.0*elapsed.as_secs_f64()) | |
1057 | ); | |
1058 | ||
1059 | ||
88892ea8 DM |
1060 | Ok(()) |
1061 | } | |
1062 | ||
dc155e9b | 1063 | fn parse_archive_type(name: &str) -> (String, ArchiveType) { |
2d32fe2c TL |
1064 | if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") { |
1065 | (name.into(), archive_type(name).unwrap()) | |
1066 | } else if name.ends_with(".pxar") { | |
dc155e9b TL |
1067 | (format!("{}.didx", name), ArchiveType::DynamicIndex) |
1068 | } else if name.ends_with(".img") { | |
1069 | (format!("{}.fidx", name), ArchiveType::FixedIndex) | |
1070 | } else { | |
1071 | (format!("{}.blob", name), ArchiveType::Blob) | |
1072 | } | |
1073 | } | |
1074 | ||
a47a02ae DM |
1075 | #[api( |
1076 | input: { | |
1077 | properties: { | |
1078 | repository: { | |
1079 | schema: REPO_URL_SCHEMA, | |
1080 | optional: true, | |
1081 | }, | |
1082 | snapshot: { | |
1083 | type: String, | |
1084 | description: "Group/Snapshot path.", | |
1085 | }, | |
1086 | "archive-name": { | |
1087 | description: "Backup archive name.", | |
1088 | type: String, | |
1089 | }, | |
1090 | target: { | |
1091 | type: String, | |
90c815bf | 1092 | description: r###"Target directory path. Use '-' to write to standard output. |
8a8a4703 | 1093 | |
d1d74c43 | 1094 | We do not extract '.pxar' archives when writing to standard output. |
8a8a4703 | 1095 | |
a47a02ae DM |
1096 | "### |
1097 | }, | |
bfd12e87 DM |
1098 | rate: { |
1099 | schema: TRAFFIC_CONTROL_RATE_SCHEMA, | |
1100 | optional: true, | |
1101 | }, | |
1102 | burst: { | |
1103 | schema: TRAFFIC_CONTROL_BURST_SCHEMA, | |
1104 | optional: true, | |
1105 | }, | |
a47a02ae DM |
1106 | "allow-existing-dirs": { |
1107 | type: Boolean, | |
1108 | description: "Do not fail if directories already exists.", | |
1109 | optional: true, | |
1110 | }, | |
1111 | keyfile: { | |
1112 | schema: KEYFILE_SCHEMA, | |
1113 | optional: true, | |
1114 | }, | |
0351f23b WB |
1115 | "keyfd": { |
1116 | schema: KEYFD_SCHEMA, | |
1117 | optional: true, | |
1118 | }, | |
24be37e3 WB |
1119 | "crypt-mode": { |
1120 | type: CryptMode, | |
96ee8577 WB |
1121 | optional: true, |
1122 | }, | |
a47a02ae DM |
1123 | } |
1124 | } | |
1125 | )] | |
1126 | /// Restore backup repository. | |
1127 | async fn restore(param: Value) -> Result<Value, Error> { | |
2665cef7 | 1128 | let repo = extract_repository_from_value(¶m)?; |
9f912493 | 1129 | |
86eda3eb DM |
1130 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
1131 | ||
46d5aa0a DM |
1132 | let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false); |
1133 | ||
3c8c2827 | 1134 | let archive_name = json::required_string_param(¶m, "archive-name")?; |
d5c34d98 | 1135 | |
2d5287fb DM |
1136 | let rate = match param["rate"].as_str() { |
1137 | Some(s) => Some(s.parse::<HumanByte>()?), | |
1138 | None => None, | |
1139 | }; | |
1140 | let burst = match param["burst"].as_str() { | |
1141 | Some(s) => Some(s.parse::<HumanByte>()?), | |
1142 | None => None, | |
1143 | }; | |
1144 | ||
1145 | let rate_limit = RateLimitConfig::with_same_inout(rate, burst); | |
d0a03d40 | 1146 | |
2d5287fb | 1147 | let client = connect_rate_limited(&repo, rate_limit)?; |
d0a03d40 | 1148 | record_repository(&repo); |
d5c34d98 | 1149 | |
3c8c2827 | 1150 | let path = json::required_string_param(¶m, "snapshot")?; |
9f912493 | 1151 | |
86eda3eb | 1152 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { |
d6d3b353 | 1153 | let group: BackupGroup = path.parse()?; |
27c9affb | 1154 | api_datastore_latest_snapshot(&client, repo.store(), group).await? |
d5c34d98 | 1155 | } else { |
a67f7d0a | 1156 | let snapshot: BackupDir = path.parse()?; |
86eda3eb DM |
1157 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) |
1158 | }; | |
9f912493 | 1159 | |
3c8c2827 | 1160 | let target = json::required_string_param(¶m, "target")?; |
bf125261 | 1161 | let target = if target == "-" { None } else { Some(target) }; |
2ae7d196 | 1162 | |
c6a7ea0a | 1163 | let crypto = crypto_parameters(¶m)?; |
2ae7d196 | 1164 | |
c6a7ea0a | 1165 | let crypt_config = match crypto.enc_key { |
86eda3eb | 1166 | None => None, |
2f26b866 FG |
1167 | Some(ref key) => { |
1168 | let (key, _, _) = | |
ff8945fd | 1169 | decrypt_key(&key.key, &get_encryption_key_password).map_err(|err| { |
2f26b866 FG |
1170 | eprintln!("{}", format_key_source(&key.source, "encryption")); |
1171 | err | |
1172 | })?; | |
86eda3eb DM |
1173 | Some(Arc::new(CryptConfig::new(key)?)) |
1174 | } | |
1175 | }; | |
d5c34d98 | 1176 | |
296c50ba DM |
1177 | let client = BackupReader::start( |
1178 | client, | |
1179 | crypt_config.clone(), | |
1180 | repo.store(), | |
1181 | &backup_type, | |
1182 | &backup_id, | |
1183 | backup_time, | |
1184 | true, | |
1185 | ).await?; | |
86eda3eb | 1186 | |
48fbbfeb FG |
1187 | let (archive_name, archive_type) = parse_archive_type(archive_name); |
1188 | ||
2107a5ae | 1189 | let (manifest, backup_index_data) = client.download_manifest().await?; |
02fcf372 | 1190 | |
48fbbfeb FG |
1191 | if archive_name == ENCRYPTED_KEY_BLOB_NAME && crypt_config.is_none() { |
1192 | eprintln!("Restoring encrypted key blob without original key - skipping manifest fingerprint check!") | |
1193 | } else { | |
2f26b866 FG |
1194 | if manifest.signature.is_some() { |
1195 | if let Some(key) = &crypto.enc_key { | |
1196 | eprintln!("{}", format_key_source(&key.source, "encryption")); | |
1197 | } | |
1198 | if let Some(config) = &crypt_config { | |
bbdda58b | 1199 | eprintln!("Fingerprint: {}", Fingerprint::new(config.fingerprint())); |
2f26b866 FG |
1200 | } |
1201 | } | |
48fbbfeb FG |
1202 | manifest.check_fingerprint(crypt_config.as_ref().map(Arc::as_ref))?; |
1203 | } | |
dc155e9b TL |
1204 | |
1205 | if archive_name == MANIFEST_BLOB_NAME { | |
02fcf372 | 1206 | if let Some(target) = target { |
e0a19d33 | 1207 | replace_file(target, &backup_index_data, CreateOptions::new(), false)?; |
02fcf372 DM |
1208 | } else { |
1209 | let stdout = std::io::stdout(); | |
1210 | let mut writer = stdout.lock(); | |
2107a5ae | 1211 | writer.write_all(&backup_index_data) |
02fcf372 DM |
1212 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1213 | } | |
1214 | ||
14f6c9cb FG |
1215 | return Ok(Value::Null); |
1216 | } | |
1217 | ||
1218 | let file_info = manifest.lookup_file_info(&archive_name)?; | |
1219 | ||
1220 | if archive_type == ArchiveType::Blob { | |
d2267b11 | 1221 | |
dc155e9b | 1222 | let mut reader = client.download_blob(&manifest, &archive_name).await?; |
f8100e96 | 1223 | |
bf125261 | 1224 | if let Some(target) = target { |
0d986280 DM |
1225 | let mut writer = std::fs::OpenOptions::new() |
1226 | .write(true) | |
1227 | .create(true) | |
1228 | .create_new(true) | |
1229 | .open(target) | |
1230 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?; | |
1231 | std::io::copy(&mut reader, &mut writer)?; | |
bf125261 DM |
1232 | } else { |
1233 | let stdout = std::io::stdout(); | |
1234 | let mut writer = stdout.lock(); | |
0d986280 | 1235 | std::io::copy(&mut reader, &mut writer) |
bf125261 DM |
1236 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1237 | } | |
f8100e96 | 1238 | |
dc155e9b | 1239 | } else if archive_type == ArchiveType::DynamicIndex { |
86eda3eb | 1240 | |
dc155e9b | 1241 | let index = client.download_dynamic_index(&manifest, &archive_name).await?; |
df65bd3d | 1242 | |
f4bf7dfc DM |
1243 | let most_used = index.find_most_used_chunks(8); |
1244 | ||
14f6c9cb | 1245 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, file_info.chunk_crypt_mode(), most_used); |
f4bf7dfc | 1246 | |
afb4cd28 | 1247 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); |
86eda3eb | 1248 | |
2b7f8dd5 | 1249 | let options = pbs_client::pxar::PxarExtractOptions { |
72064fd0 FG |
1250 | match_list: &[], |
1251 | extract_match_default: true, | |
1252 | allow_existing_dirs, | |
1253 | on_error: None, | |
1254 | }; | |
1255 | ||
bf125261 | 1256 | if let Some(target) = target { |
2b7f8dd5 | 1257 | pbs_client::pxar::extract_archive( |
c443f58b WB |
1258 | pxar::decoder::Decoder::from_std(reader)?, |
1259 | Path::new(target), | |
2b7f8dd5 | 1260 | pbs_client::pxar::Flags::DEFAULT, |
c443f58b WB |
1261 | |path| { |
1262 | if verbose { | |
1263 | println!("{:?}", path); | |
1264 | } | |
1265 | }, | |
72064fd0 | 1266 | options, |
c443f58b WB |
1267 | ) |
1268 | .map_err(|err| format_err!("error extracting archive - {}", err))?; | |
bf125261 | 1269 | } else { |
88892ea8 DM |
1270 | let mut writer = std::fs::OpenOptions::new() |
1271 | .write(true) | |
1272 | .open("/dev/stdout") | |
1273 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?; | |
afb4cd28 | 1274 | |
bf125261 DM |
1275 | std::io::copy(&mut reader, &mut writer) |
1276 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
1277 | } | |
dc155e9b | 1278 | } else if archive_type == ArchiveType::FixedIndex { |
afb4cd28 | 1279 | |
dc155e9b | 1280 | let index = client.download_fixed_index(&manifest, &archive_name).await?; |
df65bd3d | 1281 | |
88892ea8 DM |
1282 | let mut writer = if let Some(target) = target { |
1283 | std::fs::OpenOptions::new() | |
bf125261 DM |
1284 | .write(true) |
1285 | .create(true) | |
1286 | .create_new(true) | |
1287 | .open(target) | |
88892ea8 | 1288 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))? |
bf125261 | 1289 | } else { |
88892ea8 DM |
1290 | std::fs::OpenOptions::new() |
1291 | .write(true) | |
1292 | .open("/dev/stdout") | |
1293 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))? | |
1294 | }; | |
afb4cd28 | 1295 | |
14f6c9cb | 1296 | dump_image(client.clone(), crypt_config.clone(), file_info.chunk_crypt_mode(), index, &mut writer, verbose).await?; |
3031e44c | 1297 | } |
fef44d4f DM |
1298 | |
1299 | Ok(Value::Null) | |
45db6f89 DM |
1300 | } |
1301 | ||
e0665a64 DC |
1302 | #[api( |
1303 | input: { | |
1304 | properties: { | |
1305 | "dry-run": { | |
1306 | type: bool, | |
1307 | optional: true, | |
1308 | description: "Just show what prune would do, but do not delete anything.", | |
1309 | }, | |
1310 | group: { | |
1311 | type: String, | |
1312 | description: "Backup group", | |
1313 | }, | |
1314 | "prune-options": { | |
1315 | type: PruneOptions, | |
1316 | flatten: true, | |
1317 | }, | |
1318 | "output-format": { | |
1319 | schema: OUTPUT_FORMAT, | |
1320 | optional: true, | |
1321 | }, | |
1322 | quiet: { | |
1323 | type: bool, | |
1324 | optional: true, | |
1325 | default: false, | |
1326 | description: "Minimal output - only show removals.", | |
1327 | }, | |
1328 | repository: { | |
1329 | schema: REPO_URL_SCHEMA, | |
1330 | optional: true, | |
1331 | }, | |
1332 | }, | |
1333 | }, | |
1334 | )] | |
1335 | /// Prune a backup repository. | |
1336 | async fn prune( | |
1337 | dry_run: Option<bool>, | |
1338 | group: String, | |
1339 | prune_options: PruneOptions, | |
1340 | quiet: bool, | |
1341 | mut param: Value | |
1342 | ) -> Result<Value, Error> { | |
2665cef7 | 1343 | let repo = extract_repository_from_value(¶m)?; |
83b7db02 | 1344 | |
d4877712 | 1345 | let client = connect(&repo)?; |
83b7db02 | 1346 | |
d0a03d40 | 1347 | let path = format!("api2/json/admin/datastore/{}/prune", repo.store()); |
83b7db02 | 1348 | |
d6d3b353 | 1349 | let group: BackupGroup = group.parse()?; |
c2043614 | 1350 | |
671c6a96 | 1351 | let output_format = extract_output_format(&mut param); |
9fdc3ef4 | 1352 | |
e0665a64 DC |
1353 | let mut api_param = serde_json::to_value(prune_options)?; |
1354 | if let Some(dry_run) = dry_run { | |
1355 | api_param["dry-run"] = dry_run.into(); | |
1356 | } | |
1357 | api_param["backup-type"] = group.backup_type().into(); | |
1358 | api_param["backup-id"] = group.backup_id().into(); | |
83b7db02 | 1359 | |
e0665a64 | 1360 | let mut result = client.post(&path, Some(api_param)).await?; |
74fa81b8 | 1361 | |
87c42375 | 1362 | record_repository(&repo); |
3b03abfe | 1363 | |
db1e061d DM |
1364 | let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> { |
1365 | let item: PruneListItem = serde_json::from_value(record.to_owned())?; | |
e0e5b442 | 1366 | let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time)?; |
db1e061d DM |
1367 | Ok(snapshot.relative_path().to_str().unwrap().to_owned()) |
1368 | }; | |
1369 | ||
c48aa39f DM |
1370 | let render_prune_action = |v: &Value, _record: &Value| -> Result<String, Error> { |
1371 | Ok(match v.as_bool() { | |
1372 | Some(true) => "keep", | |
1373 | Some(false) => "remove", | |
1374 | None => "unknown", | |
1375 | }.to_string()) | |
1376 | }; | |
1377 | ||
db1e061d DM |
1378 | let options = default_table_format_options() |
1379 | .sortby("backup-type", false) | |
1380 | .sortby("backup-id", false) | |
1381 | .sortby("backup-time", false) | |
1382 | .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot")) | |
770a36e5 | 1383 | .column(ColumnConfig::new("backup-time").renderer(pbs_tools::format::render_epoch).header("date")) |
c48aa39f | 1384 | .column(ColumnConfig::new("keep").renderer(render_prune_action).header("action")) |
db1e061d DM |
1385 | ; |
1386 | ||
e351ac78 | 1387 | let return_type = &pbs_api_types::ADMIN_DATASTORE_PRUNE_RETURN_TYPE; |
db1e061d DM |
1388 | |
1389 | let mut data = result["data"].take(); | |
1390 | ||
c48aa39f DM |
1391 | if quiet { |
1392 | let list: Vec<Value> = data.as_array().unwrap().iter().filter(|item| { | |
1393 | item["keep"].as_bool() == Some(false) | |
a375df6f | 1394 | }).cloned().collect(); |
c48aa39f DM |
1395 | data = list.into(); |
1396 | } | |
1397 | ||
b2362a12 | 1398 | format_and_print_result_full(&mut data, return_type, &output_format, &options); |
d0a03d40 | 1399 | |
43a406fd | 1400 | Ok(Value::Null) |
83b7db02 DM |
1401 | } |
1402 | ||
a47a02ae DM |
1403 | #[api( |
1404 | input: { | |
1405 | properties: { | |
1406 | repository: { | |
1407 | schema: REPO_URL_SCHEMA, | |
1408 | optional: true, | |
1409 | }, | |
1410 | "output-format": { | |
1411 | schema: OUTPUT_FORMAT, | |
1412 | optional: true, | |
1413 | }, | |
1414 | } | |
f9beae9c TL |
1415 | }, |
1416 | returns: { | |
1417 | type: StorageStatus, | |
1418 | }, | |
a47a02ae DM |
1419 | )] |
1420 | /// Get repository status. | |
1421 | async fn status(param: Value) -> Result<Value, Error> { | |
34a816cc DM |
1422 | |
1423 | let repo = extract_repository_from_value(¶m)?; | |
1424 | ||
c2043614 | 1425 | let output_format = get_output_format(¶m); |
34a816cc | 1426 | |
f3fde36b | 1427 | let client = connect(&repo)?; |
34a816cc DM |
1428 | |
1429 | let path = format!("api2/json/admin/datastore/{}/status", repo.store()); | |
1430 | ||
1dc117bb | 1431 | let mut result = client.get(&path, None).await?; |
14e08625 | 1432 | let mut data = result["data"].take(); |
34a816cc DM |
1433 | |
1434 | record_repository(&repo); | |
1435 | ||
390c5bdd DM |
1436 | let render_total_percentage = |v: &Value, record: &Value| -> Result<String, Error> { |
1437 | let v = v.as_u64().unwrap(); | |
1438 | let total = record["total"].as_u64().unwrap(); | |
1439 | let roundup = total/200; | |
1440 | let per = ((v+roundup)*100)/total; | |
e23f5863 DM |
1441 | let info = format!(" ({} %)", per); |
1442 | Ok(format!("{} {:>8}", v, info)) | |
390c5bdd | 1443 | }; |
1dc117bb | 1444 | |
c2043614 | 1445 | let options = default_table_format_options() |
be2425ff | 1446 | .noheader(true) |
e23f5863 | 1447 | .column(ColumnConfig::new("total").renderer(render_total_percentage)) |
390c5bdd DM |
1448 | .column(ColumnConfig::new("used").renderer(render_total_percentage)) |
1449 | .column(ColumnConfig::new("avail").renderer(render_total_percentage)); | |
34a816cc | 1450 | |
b2362a12 | 1451 | let return_type = &API_METHOD_STATUS.returns; |
390c5bdd | 1452 | |
b2362a12 | 1453 | format_and_print_result_full(&mut data, return_type, &output_format, &options); |
34a816cc DM |
1454 | |
1455 | Ok(Value::Null) | |
1456 | } | |
1457 | ||
c443f58b WB |
1458 | /// This is a workaround until we have cleaned up the chunk/reader/... infrastructure for better |
1459 | /// async use! | |
1460 | /// | |
1461 | /// Ideally BufferedDynamicReader gets replaced so the LruCache maps to `BroadcastFuture<Chunk>`, | |
1462 | /// so that we can properly access it from multiple threads simultaneously while not issuing | |
1463 | /// duplicate simultaneous reads over http. | |
43abba4b | 1464 | pub struct BufferedDynamicReadAt { |
c443f58b WB |
1465 | inner: Mutex<BufferedDynamicReader<RemoteChunkReader>>, |
1466 | } | |
1467 | ||
1468 | impl BufferedDynamicReadAt { | |
1469 | fn new(inner: BufferedDynamicReader<RemoteChunkReader>) -> Self { | |
1470 | Self { | |
1471 | inner: Mutex::new(inner), | |
1472 | } | |
1473 | } | |
1474 | } | |
1475 | ||
a6f87283 WB |
1476 | impl ReadAt for BufferedDynamicReadAt { |
1477 | fn start_read_at<'a>( | |
1478 | self: Pin<&'a Self>, | |
c443f58b | 1479 | _cx: &mut Context, |
a6f87283 | 1480 | buf: &'a mut [u8], |
c443f58b | 1481 | offset: u64, |
a6f87283 | 1482 | ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> { |
a6f87283 | 1483 | MaybeReady::Ready(tokio::task::block_in_place(move || { |
c443f58b WB |
1484 | let mut reader = self.inner.lock().unwrap(); |
1485 | reader.seek(SeekFrom::Start(offset))?; | |
dcf5a0f6 | 1486 | reader.read(buf) |
a6f87283 WB |
1487 | })) |
1488 | } | |
1489 | ||
1490 | fn poll_complete<'a>( | |
1491 | self: Pin<&'a Self>, | |
1492 | _op: ReadAtOperation<'a>, | |
1493 | ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> { | |
bbc71e3b | 1494 | panic!("BufferedDynamicReadAt::start_read_at returned Pending"); |
c443f58b WB |
1495 | } |
1496 | } | |
1497 | ||
f2401311 | 1498 | fn main() { |
d91a0f9f | 1499 | pbs_tools::setup_libc_malloc_opts(); |
33d64b81 | 1500 | |
255f378a | 1501 | let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP) |
49fddd98 | 1502 | .arg_param(&["backupspec"]) |
d0a03d40 | 1503 | .completion_cb("repository", complete_repository) |
49811347 | 1504 | .completion_cb("backupspec", complete_backup_source) |
b3f279e2 DM |
1505 | .completion_cb("keyfile", complete_file_name) |
1506 | .completion_cb("master-pubkey-file", complete_file_name) | |
49811347 | 1507 | .completion_cb("chunk-size", complete_chunk_size); |
f8838fe9 | 1508 | |
caea8d61 DM |
1509 | let benchmark_cmd_def = CliCommand::new(&API_METHOD_BENCHMARK) |
1510 | .completion_cb("repository", complete_repository) | |
b3f279e2 | 1511 | .completion_cb("keyfile", complete_file_name); |
caea8d61 | 1512 | |
255f378a | 1513 | let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS) |
d0a03d40 | 1514 | .completion_cb("repository", complete_repository); |
41c039e1 | 1515 | |
255f378a | 1516 | let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION) |
d0a03d40 | 1517 | .completion_cb("repository", complete_repository); |
8cc0d6af | 1518 | |
255f378a | 1519 | let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE) |
49fddd98 | 1520 | .arg_param(&["snapshot", "archive-name", "target"]) |
b2388518 | 1521 | .completion_cb("repository", complete_repository) |
08dc340a DM |
1522 | .completion_cb("snapshot", complete_group_or_snapshot) |
1523 | .completion_cb("archive-name", complete_archive_name) | |
b3f279e2 | 1524 | .completion_cb("target", complete_file_name); |
9f912493 | 1525 | |
255f378a | 1526 | let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE) |
49fddd98 | 1527 | .arg_param(&["group"]) |
9fdc3ef4 | 1528 | .completion_cb("group", complete_backup_group) |
d0a03d40 | 1529 | .completion_cb("repository", complete_repository); |
9f912493 | 1530 | |
255f378a | 1531 | let status_cmd_def = CliCommand::new(&API_METHOD_STATUS) |
34a816cc DM |
1532 | .completion_cb("repository", complete_repository); |
1533 | ||
255f378a | 1534 | let login_cmd_def = CliCommand::new(&API_METHOD_API_LOGIN) |
e240d8be DM |
1535 | .completion_cb("repository", complete_repository); |
1536 | ||
255f378a | 1537 | let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT) |
e240d8be | 1538 | .completion_cb("repository", complete_repository); |
32efac1c | 1539 | |
e39974af TL |
1540 | let version_cmd_def = CliCommand::new(&API_METHOD_API_VERSION) |
1541 | .completion_cb("repository", complete_repository); | |
1542 | ||
344add38 DW |
1543 | let change_owner_cmd_def = CliCommand::new(&API_METHOD_CHANGE_BACKUP_OWNER) |
1544 | .arg_param(&["group", "new-owner"]) | |
1545 | .completion_cb("group", complete_backup_group) | |
0224c3c2 | 1546 | .completion_cb("new-owner", complete_auth_id) |
344add38 DW |
1547 | .completion_cb("repository", complete_repository); |
1548 | ||
41c039e1 | 1549 | let cmd_def = CliCommandMap::new() |
48ef3c33 | 1550 | .insert("backup", backup_cmd_def) |
48ef3c33 DM |
1551 | .insert("garbage-collect", garbage_collect_cmd_def) |
1552 | .insert("list", list_cmd_def) | |
1553 | .insert("login", login_cmd_def) | |
1554 | .insert("logout", logout_cmd_def) | |
1555 | .insert("prune", prune_cmd_def) | |
1556 | .insert("restore", restore_cmd_def) | |
a65e3e4b | 1557 | .insert("snapshot", snapshot_mgtm_cli()) |
48ef3c33 | 1558 | .insert("status", status_cmd_def) |
9696f519 | 1559 | .insert("key", key::cli()) |
43abba4b | 1560 | .insert("mount", mount_cmd_def()) |
45f9b32e SR |
1561 | .insert("map", map_cmd_def()) |
1562 | .insert("unmap", unmap_cmd_def()) | |
5830c205 | 1563 | .insert("catalog", catalog_mgmt_cli()) |
caea8d61 | 1564 | .insert("task", task_mgmt_cli()) |
e39974af | 1565 | .insert("version", version_cmd_def) |
344add38 | 1566 | .insert("benchmark", benchmark_cmd_def) |
731eeef2 DM |
1567 | .insert("change-owner", change_owner_cmd_def) |
1568 | ||
61205f00 | 1569 | .alias(&["files"], &["snapshot", "files"]) |
edebd523 | 1570 | .alias(&["forget"], &["snapshot", "forget"]) |
0c9209b0 | 1571 | .alias(&["upload-log"], &["snapshot", "upload-log"]) |
731eeef2 DM |
1572 | .alias(&["snapshots"], &["snapshot", "list"]) |
1573 | ; | |
48ef3c33 | 1574 | |
7b22acd0 DM |
1575 | let rpcenv = CliEnvironment::new(); |
1576 | run_cli_command(cmd_def, rpcenv, Some(|future| { | |
9a1b24b6 | 1577 | proxmox_async::runtime::main(future) |
d08bc483 | 1578 | })); |
ff5d3707 | 1579 | } |