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