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