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