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