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