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