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