]>
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(), | |
4a2e4467 | 464 | Err(e) => log::error!("could not connect to server - {}", e), |
e39974af TL |
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 { | |
4a2e4467 | 550 | log::error!("catalog upload error - {}", err); |
bf6e3217 DM |
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 | }, |
4b8395ee MF |
660 | "dry-run": { |
661 | type: Boolean, | |
662 | description: "Just show what backup would do, but do not upload anything.", | |
663 | optional: true, | |
667476f1 | 664 | default: false, |
4b8395ee | 665 | }, |
a47a02ae DM |
666 | } |
667 | } | |
668 | )] | |
669 | /// Create (host) backup. | |
670 | async fn create_backup( | |
6049b71f | 671 | param: Value, |
667476f1 TL |
672 | all_file_systems: bool, |
673 | skip_lost_and_found: bool, | |
674 | dry_run: bool, | |
6049b71f | 675 | _info: &ApiMethod, |
dd5495d6 | 676 | _rpcenv: &mut dyn RpcEnvironment, |
6049b71f | 677 | ) -> Result<Value, Error> { |
2665cef7 | 678 | let repo = extract_repository_from_value(¶m)?; |
ae0be2dd | 679 | |
3c8c2827 | 680 | let backupspec_list = json::required_array_param(¶m, "backupspec")?; |
a914a774 | 681 | |
ca5d0b61 DM |
682 | let backup_time_opt = param["backup-time"].as_i64(); |
683 | ||
118f8589 | 684 | let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v * 1024) as usize); |
2d9d143a | 685 | |
247cdbce DM |
686 | if let Some(size) = chunk_size_opt { |
687 | verify_chunk_size(size)?; | |
2d9d143a DM |
688 | } |
689 | ||
2d5287fb DM |
690 | let rate = match param["rate"].as_str() { |
691 | Some(s) => Some(s.parse::<HumanByte>()?), | |
692 | None => None, | |
693 | }; | |
694 | let burst = match param["burst"].as_str() { | |
695 | Some(s) => Some(s.parse::<HumanByte>()?), | |
696 | None => None, | |
697 | }; | |
698 | ||
699 | let rate_limit = RateLimitConfig::with_same_inout(rate, burst); | |
e4bc3e0e | 700 | |
c6a7ea0a | 701 | let crypto = crypto_parameters(¶m)?; |
6d0983db | 702 | |
118f8589 TL |
703 | let backup_id = param["backup-id"] |
704 | .as_str() | |
705 | .unwrap_or(proxmox_sys::nodename()); | |
fba30411 | 706 | |
03d4f43d | 707 | let backup_ns = optional_ns_param(¶m)?; |
8c74349b | 708 | |
988d575d | 709 | let backup_type: BackupType = param["backup-type"].as_str().unwrap_or("host").parse()?; |
ca5d0b61 | 710 | |
2eeaacb9 DM |
711 | let include_dev = param["include-dev"].as_array(); |
712 | ||
118f8589 TL |
713 | let entries_max = param["entries-max"] |
714 | .as_u64() | |
2b7f8dd5 | 715 | .unwrap_or(pbs_client::pxar::ENCODER_MAX_ENTRIES as u64); |
6fc053ed | 716 | |
189996cf | 717 | let empty = Vec::new(); |
c443f58b WB |
718 | let exclude_args = param["exclude"].as_array().unwrap_or(&empty); |
719 | ||
239e49f9 | 720 | let mut pattern_list = Vec::with_capacity(exclude_args.len()); |
c443f58b | 721 | for entry in exclude_args { |
118f8589 TL |
722 | let entry = entry |
723 | .as_str() | |
724 | .ok_or_else(|| format_err!("Invalid pattern string slice"))?; | |
239e49f9 | 725 | pattern_list.push( |
c443f58b | 726 | MatchEntry::parse_pattern(entry, PatternFlag::PATH_NAME, MatchType::Exclude) |
118f8589 | 727 | .map_err(|err| format_err!("invalid exclude pattern entry: {}", err))?, |
c443f58b | 728 | ); |
189996cf CE |
729 | } |
730 | ||
118f8589 TL |
731 | let mut devices = if all_file_systems { |
732 | None | |
733 | } else { | |
734 | Some(HashSet::new()) | |
735 | }; | |
2eeaacb9 DM |
736 | |
737 | if let Some(include_dev) = include_dev { | |
738 | if all_file_systems { | |
739 | bail!("option 'all-file-systems' conflicts with option 'include-dev'"); | |
740 | } | |
741 | ||
742 | let mut set = HashSet::new(); | |
743 | for path in include_dev { | |
744 | let path = path.as_str().unwrap(); | |
745 | let stat = nix::sys::stat::stat(path) | |
746 | .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?; | |
747 | set.insert(stat.st_dev); | |
748 | } | |
749 | devices = Some(set); | |
750 | } | |
751 | ||
ae0be2dd | 752 | let mut upload_list = vec![]; |
f2b4b4b9 | 753 | let mut target_set = HashSet::new(); |
a914a774 | 754 | |
ae0be2dd | 755 | for backupspec in backupspec_list { |
7cc3473a DM |
756 | let spec = parse_backup_specification(backupspec.as_str().unwrap())?; |
757 | let filename = &spec.config_string; | |
758 | let target = &spec.archive_name; | |
bcd879cf | 759 | |
f2b4b4b9 SI |
760 | if target_set.contains(target) { |
761 | bail!("got target twice: '{}'", target); | |
762 | } | |
763 | target_set.insert(target.to_string()); | |
764 | ||
eb1804c5 DM |
765 | use std::os::unix::fs::FileTypeExt; |
766 | ||
3fa71727 CE |
767 | let metadata = std::fs::metadata(filename) |
768 | .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?; | |
eb1804c5 | 769 | let file_type = metadata.file_type(); |
23bb8780 | 770 | |
7cc3473a DM |
771 | match spec.spec_type { |
772 | BackupSpecificationType::PXAR => { | |
ec8a9bb9 DM |
773 | if !file_type.is_dir() { |
774 | bail!("got unexpected file type (expected directory)"); | |
775 | } | |
118f8589 TL |
776 | upload_list.push(( |
777 | BackupSpecificationType::PXAR, | |
778 | filename.to_owned(), | |
779 | format!("{}.didx", target), | |
780 | 0, | |
781 | )); | |
ec8a9bb9 | 782 | } |
7cc3473a | 783 | BackupSpecificationType::IMAGE => { |
ec8a9bb9 DM |
784 | if !(file_type.is_file() || file_type.is_block_device()) { |
785 | bail!("got unexpected file type (expected file or block device)"); | |
786 | } | |
eb1804c5 | 787 | |
e18a6c9e | 788 | let size = image_size(&PathBuf::from(filename))?; |
23bb8780 | 789 | |
118f8589 TL |
790 | if size == 0 { |
791 | bail!("got zero-sized file '{}'", filename); | |
792 | } | |
ae0be2dd | 793 | |
118f8589 TL |
794 | upload_list.push(( |
795 | BackupSpecificationType::IMAGE, | |
796 | filename.to_owned(), | |
797 | format!("{}.fidx", target), | |
798 | size, | |
799 | )); | |
ec8a9bb9 | 800 | } |
7cc3473a | 801 | BackupSpecificationType::CONFIG => { |
ec8a9bb9 DM |
802 | if !file_type.is_file() { |
803 | bail!("got unexpected file type (expected regular file)"); | |
804 | } | |
118f8589 TL |
805 | upload_list.push(( |
806 | BackupSpecificationType::CONFIG, | |
807 | filename.to_owned(), | |
808 | format!("{}.blob", target), | |
809 | metadata.len(), | |
810 | )); | |
ec8a9bb9 | 811 | } |
7cc3473a | 812 | BackupSpecificationType::LOGFILE => { |
79679c2d DM |
813 | if !file_type.is_file() { |
814 | bail!("got unexpected file type (expected regular file)"); | |
815 | } | |
118f8589 TL |
816 | upload_list.push(( |
817 | BackupSpecificationType::LOGFILE, | |
818 | filename.to_owned(), | |
819 | format!("{}.blob", target), | |
820 | metadata.len(), | |
821 | )); | |
ec8a9bb9 | 822 | } |
ae0be2dd DM |
823 | } |
824 | } | |
825 | ||
22a9189e | 826 | let backup_time = backup_time_opt.unwrap_or_else(epoch_i64); |
ae0be2dd | 827 | |
2d5287fb | 828 | let client = connect_rate_limited(&repo, rate_limit)?; |
d0a03d40 DM |
829 | record_repository(&repo); |
830 | ||
133d718f WB |
831 | let snapshot = BackupDir::from((backup_type, backup_id.to_owned(), backup_time)); |
832 | if backup_ns.is_root() { | |
4a2e4467 | 833 | log::info!("Starting backup: {snapshot}"); |
133d718f | 834 | } else { |
4a2e4467 | 835 | log::info!("Starting backup: [{backup_ns}]:{snapshot}"); |
133d718f | 836 | } |
ca5d0b61 | 837 | |
4a2e4467 | 838 | log::info!("Client name: {}", proxmox_sys::nodename()); |
ca5d0b61 | 839 | |
6a7be83e | 840 | let start_time = std::time::Instant::now(); |
ca5d0b61 | 841 | |
4a2e4467 | 842 | log::info!( |
118f8589 TL |
843 | "Starting backup protocol: {}", |
844 | strftime_local("%c", epoch_i64())? | |
845 | ); | |
51144821 | 846 | |
c6a7ea0a | 847 | let (crypt_config, rsa_encrypted_key) = match crypto.enc_key { |
bb823140 | 848 | None => (None, None), |
2f26b866 | 849 | Some(key_with_source) => { |
4a2e4467 | 850 | log::info!( |
2f26b866 FG |
851 | "{}", |
852 | format_key_source(&key_with_source.source, "encryption") | |
853 | ); | |
854 | ||
855 | let (key, created, fingerprint) = | |
ff8945fd | 856 | decrypt_key(&key_with_source.key, &get_encryption_key_password)?; |
4a2e4467 | 857 | log::info!("Encryption key fingerprint: {}", fingerprint); |
bb823140 | 858 | |
44288184 | 859 | let crypt_config = CryptConfig::new(key)?; |
bb823140 | 860 | |
c0a87c12 | 861 | match crypto.master_pubkey { |
2f26b866 | 862 | Some(pem_with_source) => { |
4a2e4467 | 863 | log::info!("{}", format_key_source(&pem_with_source.source, "master")); |
2f26b866 FG |
864 | |
865 | let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_with_source.key)?; | |
82a103c8 | 866 | |
1c86893d | 867 | let mut key_config = KeyConfig::without_password(key)?; |
82a103c8 | 868 | key_config.created = created; // keep original value |
82a103c8 | 869 | |
8acfd15d | 870 | let enc_key = rsa_encrypt_key_config(rsa, &key_config)?; |
6f2626ae | 871 | |
05389a01 | 872 | (Some(Arc::new(crypt_config)), Some(enc_key)) |
118f8589 | 873 | } |
05389a01 | 874 | _ => (Some(Arc::new(crypt_config)), None), |
bb823140 | 875 | } |
6d0983db DM |
876 | } |
877 | }; | |
f98ac774 | 878 | |
8a8a4703 DM |
879 | let client = BackupWriter::start( |
880 | client, | |
b957aa81 | 881 | crypt_config.clone(), |
8a8a4703 | 882 | repo.store(), |
133d718f | 883 | &backup_ns, |
8c74349b | 884 | &snapshot, |
4a2e4467 | 885 | true, |
118f8589 TL |
886 | false, |
887 | ) | |
888 | .await?; | |
8a8a4703 | 889 | |
8b7f8d3f FG |
890 | let download_previous_manifest = match client.previous_backup_time().await { |
891 | Ok(Some(backup_time)) => { | |
4a2e4467 | 892 | log::info!( |
8b7f8d3f FG |
893 | "Downloading previous manifest ({})", |
894 | strftime_local("%c", backup_time)? | |
895 | ); | |
896 | true | |
897 | } | |
898 | Ok(None) => { | |
4a2e4467 | 899 | log::info!("No previous manifest available."); |
8b7f8d3f FG |
900 | false |
901 | } | |
902 | Err(_) => { | |
903 | // Fallback for outdated server, TODO remove/bubble up with 2.0 | |
904 | true | |
905 | } | |
906 | }; | |
907 | ||
908 | let previous_manifest = if download_previous_manifest { | |
909 | match client.download_previous_manifest().await { | |
910 | Ok(previous_manifest) => { | |
911 | match previous_manifest.check_fingerprint(crypt_config.as_ref().map(Arc::as_ref)) { | |
912 | Ok(()) => Some(Arc::new(previous_manifest)), | |
913 | Err(err) => { | |
4a2e4467 | 914 | log::error!("Couldn't re-use previous manifest - {}", err); |
8b7f8d3f FG |
915 | None |
916 | } | |
917 | } | |
23f9503a | 918 | } |
8b7f8d3f | 919 | Err(err) => { |
4a2e4467 | 920 | log::error!("Couldn't download previous manifest - {}", err); |
8b7f8d3f FG |
921 | None |
922 | } | |
923 | } | |
924 | } else { | |
925 | None | |
b957aa81 DM |
926 | }; |
927 | ||
8a8a4703 DM |
928 | let mut manifest = BackupManifest::new(snapshot); |
929 | ||
5d85847f | 930 | let mut catalog = None; |
6d233161 | 931 | let mut catalog_result_rx = None; |
8a8a4703 | 932 | |
118f8589 TL |
933 | let log_file = |desc: &str, file: &str, target: &str| { |
934 | let what = if dry_run { "Would upload" } else { "Upload" }; | |
4a2e4467 | 935 | log::info!("{} {} '{}' to '{}' as {}", what, desc, file, repo, target); |
4b8395ee MF |
936 | }; |
937 | ||
8a8a4703 | 938 | for (backup_type, filename, target, size) in upload_list { |
4b8395ee | 939 | match (backup_type, dry_run) { |
a1b800c2 TL |
940 | // dry-run |
941 | (BackupSpecificationType::CONFIG, true) => log_file("config file", &filename, &target), | |
942 | (BackupSpecificationType::LOGFILE, true) => log_file("log file", &filename, &target), | |
943 | (BackupSpecificationType::PXAR, true) => log_file("directory", &filename, &target), | |
944 | (BackupSpecificationType::IMAGE, true) => log_file("image", &filename, &target), | |
945 | // no dry-run | |
4b8395ee | 946 | (BackupSpecificationType::CONFIG, false) => { |
e43b9175 FG |
947 | let upload_options = UploadOptions { |
948 | compress: true, | |
c6a7ea0a | 949 | encrypt: crypto.mode == CryptMode::Encrypt, |
e43b9175 FG |
950 | ..UploadOptions::default() |
951 | }; | |
952 | ||
a1b800c2 | 953 | log_file("config file", &filename, &target); |
8a8a4703 | 954 | let stats = client |
e43b9175 | 955 | .upload_blob_from_file(&filename, &target, upload_options) |
8a8a4703 | 956 | .await?; |
c6a7ea0a | 957 | manifest.add_file(target, stats.size, stats.csum, crypto.mode)?; |
8a8a4703 | 958 | } |
118f8589 TL |
959 | (BackupSpecificationType::LOGFILE, false) => { |
960 | // fixme: remove - not needed anymore ? | |
e43b9175 FG |
961 | let upload_options = UploadOptions { |
962 | compress: true, | |
c6a7ea0a | 963 | encrypt: crypto.mode == CryptMode::Encrypt, |
e43b9175 FG |
964 | ..UploadOptions::default() |
965 | }; | |
966 | ||
a1b800c2 | 967 | log_file("log file", &filename, &target); |
8a8a4703 | 968 | let stats = client |
e43b9175 | 969 | .upload_blob_from_file(&filename, &target, upload_options) |
8a8a4703 | 970 | .await?; |
c6a7ea0a | 971 | manifest.add_file(target, stats.size, stats.csum, crypto.mode)?; |
8a8a4703 | 972 | } |
4b8395ee | 973 | (BackupSpecificationType::PXAR, false) => { |
5d85847f DC |
974 | // start catalog upload on first use |
975 | if catalog.is_none() { | |
118f8589 TL |
976 | let catalog_upload_res = |
977 | spawn_catalog_upload(client.clone(), crypto.mode == CryptMode::Encrypt)?; | |
6d233161 FG |
978 | catalog = Some(catalog_upload_res.catalog_writer); |
979 | catalog_result_rx = Some(catalog_upload_res.result); | |
5d85847f DC |
980 | } |
981 | let catalog = catalog.as_ref().unwrap(); | |
982 | ||
a1b800c2 | 983 | log_file("directory", &filename, &target); |
118f8589 TL |
984 | catalog |
985 | .lock() | |
986 | .unwrap() | |
987 | .start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?; | |
77486a60 | 988 | |
2b7f8dd5 | 989 | let pxar_options = pbs_client::pxar::PxarCreateOptions { |
77486a60 FG |
990 | device_set: devices.clone(), |
991 | patterns: pattern_list.clone(), | |
992 | entries_max: entries_max as usize, | |
993 | skip_lost_and_found, | |
77486a60 FG |
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 | 1034 | if dry_run { |
4a2e4467 | 1035 | log::info!("dry-run: no upload happend"); |
4b8395ee MF |
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; |
4a2e4467 | 1057 | log::info!("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 | |
4a2e4467 HL |
1074 | log::debug!("Upload index.json to '{}'", repo); |
1075 | ||
118f8589 TL |
1076 | let options = UploadOptions { |
1077 | compress: true, | |
1078 | encrypt: false, | |
1079 | ..UploadOptions::default() | |
1080 | }; | |
8a8a4703 | 1081 | client |
e43b9175 | 1082 | .upload_blob_from_data(manifest.into_bytes(), MANIFEST_BLOB_NAME, options) |
8a8a4703 | 1083 | .await?; |
2c3891d1 | 1084 | |
8a8a4703 | 1085 | client.finish().await?; |
c4ff3dce | 1086 | |
6a7be83e DM |
1087 | let end_time = std::time::Instant::now(); |
1088 | let elapsed = end_time.duration_since(start_time); | |
4a2e4467 HL |
1089 | log::info!("Duration: {:.2}s", elapsed.as_secs_f64()); |
1090 | log::info!("End Time: {}", strftime_local("%c", epoch_i64())?); | |
8a8a4703 | 1091 | Ok(Value::Null) |
f98ea63d DM |
1092 | } |
1093 | ||
8e6e18b7 | 1094 | async fn dump_image<W: Write>( |
88892ea8 DM |
1095 | client: Arc<BackupReader>, |
1096 | crypt_config: Option<Arc<CryptConfig>>, | |
14f6c9cb | 1097 | crypt_mode: CryptMode, |
88892ea8 DM |
1098 | index: FixedIndexReader, |
1099 | mut writer: W, | |
1100 | ) -> Result<(), Error> { | |
88892ea8 DM |
1101 | let most_used = index.find_most_used_chunks(8); |
1102 | ||
14f6c9cb | 1103 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, crypt_mode, most_used); |
88892ea8 DM |
1104 | |
1105 | // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy | |
1106 | // and thus slows down reading. Instead, directly use RemoteChunkReader | |
fd04ca7a DM |
1107 | let mut per = 0; |
1108 | let mut bytes = 0; | |
1109 | let start_time = std::time::Instant::now(); | |
1110 | ||
88892ea8 DM |
1111 | for pos in 0..index.index_count() { |
1112 | let digest = index.index_digest(pos).unwrap(); | |
9a37bd6c | 1113 | let raw_data = chunk_reader.read_chunk(digest).await?; |
88892ea8 | 1114 | writer.write_all(&raw_data)?; |
fd04ca7a | 1115 | bytes += raw_data.len(); |
4a2e4467 HL |
1116 | let next_per = ((pos + 1) * 100) / index.index_count(); |
1117 | if per != next_per { | |
1118 | log::debug!( | |
1119 | "progress {}% (read {} bytes, duration {} sec)", | |
1120 | next_per, | |
1121 | bytes, | |
1122 | start_time.elapsed().as_secs() | |
1123 | ); | |
1124 | per = next_per; | |
fd04ca7a | 1125 | } |
88892ea8 DM |
1126 | } |
1127 | ||
fd04ca7a DM |
1128 | let end_time = std::time::Instant::now(); |
1129 | let elapsed = end_time.duration_since(start_time); | |
4a2e4467 | 1130 | log::info!( |
118f8589 TL |
1131 | "restore image complete (bytes={}, duration={:.2}s, speed={:.2}MB/s)", |
1132 | bytes, | |
1133 | elapsed.as_secs_f64(), | |
1134 | bytes as f64 / (1024.0 * 1024.0 * elapsed.as_secs_f64()) | |
fd04ca7a DM |
1135 | ); |
1136 | ||
88892ea8 DM |
1137 | Ok(()) |
1138 | } | |
1139 | ||
dc155e9b | 1140 | fn parse_archive_type(name: &str) -> (String, ArchiveType) { |
2d32fe2c TL |
1141 | if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") { |
1142 | (name.into(), archive_type(name).unwrap()) | |
1143 | } else if name.ends_with(".pxar") { | |
dc155e9b TL |
1144 | (format!("{}.didx", name), ArchiveType::DynamicIndex) |
1145 | } else if name.ends_with(".img") { | |
1146 | (format!("{}.fidx", name), ArchiveType::FixedIndex) | |
1147 | } else { | |
1148 | (format!("{}.blob", name), ArchiveType::Blob) | |
1149 | } | |
1150 | } | |
1151 | ||
a47a02ae | 1152 | #[api( |
133d718f WB |
1153 | input: { |
1154 | properties: { | |
1155 | repository: { | |
1156 | schema: REPO_URL_SCHEMA, | |
1157 | optional: true, | |
1158 | }, | |
1159 | ns: { | |
1160 | type: BackupNamespace, | |
1161 | optional: true, | |
1162 | }, | |
1163 | snapshot: { | |
1164 | type: String, | |
1165 | description: "Group/Snapshot path.", | |
1166 | }, | |
1167 | "archive-name": { | |
1168 | description: "Backup archive name.", | |
1169 | type: String, | |
1170 | }, | |
1171 | target: { | |
1172 | type: String, | |
1173 | description: r###"Target directory path. Use '-' to write to standard output. | |
8a8a4703 | 1174 | |
d1d74c43 | 1175 | We do not extract '.pxar' archives when writing to standard output. |
8a8a4703 | 1176 | |
a47a02ae | 1177 | "### |
133d718f WB |
1178 | }, |
1179 | rate: { | |
1180 | schema: TRAFFIC_CONTROL_RATE_SCHEMA, | |
1181 | optional: true, | |
1182 | }, | |
1183 | burst: { | |
1184 | schema: TRAFFIC_CONTROL_BURST_SCHEMA, | |
1185 | optional: true, | |
1186 | }, | |
1187 | "allow-existing-dirs": { | |
1188 | type: Boolean, | |
1189 | description: "Do not fail if directories already exists.", | |
1190 | optional: true, | |
1191 | }, | |
1192 | keyfile: { | |
1193 | schema: KEYFILE_SCHEMA, | |
1194 | optional: true, | |
1195 | }, | |
1196 | "keyfd": { | |
1197 | schema: KEYFD_SCHEMA, | |
1198 | optional: true, | |
1199 | }, | |
1200 | "crypt-mode": { | |
1201 | type: CryptMode, | |
1202 | optional: true, | |
1203 | }, | |
1204 | } | |
1205 | } | |
a47a02ae DM |
1206 | )] |
1207 | /// Restore backup repository. | |
1208 | async fn restore(param: Value) -> Result<Value, Error> { | |
2665cef7 | 1209 | let repo = extract_repository_from_value(¶m)?; |
9f912493 | 1210 | |
46d5aa0a DM |
1211 | let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false); |
1212 | ||
3c8c2827 | 1213 | let archive_name = json::required_string_param(¶m, "archive-name")?; |
d5c34d98 | 1214 | |
2d5287fb DM |
1215 | let rate = match param["rate"].as_str() { |
1216 | Some(s) => Some(s.parse::<HumanByte>()?), | |
1217 | None => None, | |
1218 | }; | |
1219 | let burst = match param["burst"].as_str() { | |
1220 | Some(s) => Some(s.parse::<HumanByte>()?), | |
1221 | None => None, | |
1222 | }; | |
1223 | ||
1224 | let rate_limit = RateLimitConfig::with_same_inout(rate, burst); | |
d0a03d40 | 1225 | |
2d5287fb | 1226 | let client = connect_rate_limited(&repo, rate_limit)?; |
d0a03d40 | 1227 | record_repository(&repo); |
d5c34d98 | 1228 | |
1f71e441 | 1229 | let ns = optional_ns_param(¶m)?; |
3c8c2827 | 1230 | let path = json::required_string_param(¶m, "snapshot")?; |
9f912493 | 1231 | |
fbfb64a6 | 1232 | let backup_dir = dir_or_last_from_group(&client, &repo, &ns, path).await?; |
9f912493 | 1233 | |
3c8c2827 | 1234 | let target = json::required_string_param(¶m, "target")?; |
bf125261 | 1235 | let target = if target == "-" { None } else { Some(target) }; |
2ae7d196 | 1236 | |
c6a7ea0a | 1237 | let crypto = crypto_parameters(¶m)?; |
2ae7d196 | 1238 | |
c6a7ea0a | 1239 | let crypt_config = match crypto.enc_key { |
86eda3eb | 1240 | None => None, |
2f26b866 FG |
1241 | Some(ref key) => { |
1242 | let (key, _, _) = | |
ff8945fd | 1243 | decrypt_key(&key.key, &get_encryption_key_password).map_err(|err| { |
4a2e4467 | 1244 | log::error!("{}", format_key_source(&key.source, "encryption")); |
2f26b866 FG |
1245 | err |
1246 | })?; | |
86eda3eb DM |
1247 | Some(Arc::new(CryptConfig::new(key)?)) |
1248 | } | |
1249 | }; | |
d5c34d98 | 1250 | |
296c50ba DM |
1251 | let client = BackupReader::start( |
1252 | client, | |
1253 | crypt_config.clone(), | |
1254 | repo.store(), | |
133d718f | 1255 | &ns, |
8c74349b | 1256 | &backup_dir, |
296c50ba | 1257 | true, |
118f8589 TL |
1258 | ) |
1259 | .await?; | |
86eda3eb | 1260 | |
48fbbfeb FG |
1261 | let (archive_name, archive_type) = parse_archive_type(archive_name); |
1262 | ||
2107a5ae | 1263 | let (manifest, backup_index_data) = client.download_manifest().await?; |
02fcf372 | 1264 | |
48fbbfeb | 1265 | if archive_name == ENCRYPTED_KEY_BLOB_NAME && crypt_config.is_none() { |
4a2e4467 | 1266 | log::info!("Restoring encrypted key blob without original key - skipping manifest fingerprint check!") |
48fbbfeb | 1267 | } else { |
2f26b866 FG |
1268 | if manifest.signature.is_some() { |
1269 | if let Some(key) = &crypto.enc_key { | |
4a2e4467 | 1270 | log::info!("{}", format_key_source(&key.source, "encryption")); |
2f26b866 FG |
1271 | } |
1272 | if let Some(config) = &crypt_config { | |
4a2e4467 | 1273 | log::info!("Fingerprint: {}", Fingerprint::new(config.fingerprint())); |
2f26b866 FG |
1274 | } |
1275 | } | |
48fbbfeb FG |
1276 | manifest.check_fingerprint(crypt_config.as_ref().map(Arc::as_ref))?; |
1277 | } | |
dc155e9b TL |
1278 | |
1279 | if archive_name == MANIFEST_BLOB_NAME { | |
02fcf372 | 1280 | if let Some(target) = target { |
e0a19d33 | 1281 | replace_file(target, &backup_index_data, CreateOptions::new(), false)?; |
02fcf372 DM |
1282 | } else { |
1283 | let stdout = std::io::stdout(); | |
1284 | let mut writer = stdout.lock(); | |
118f8589 TL |
1285 | writer |
1286 | .write_all(&backup_index_data) | |
02fcf372 DM |
1287 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1288 | } | |
1289 | ||
14f6c9cb FG |
1290 | return Ok(Value::Null); |
1291 | } | |
1292 | ||
1293 | let file_info = manifest.lookup_file_info(&archive_name)?; | |
1294 | ||
1295 | if archive_type == ArchiveType::Blob { | |
dc155e9b | 1296 | let mut reader = client.download_blob(&manifest, &archive_name).await?; |
f8100e96 | 1297 | |
bf125261 | 1298 | if let Some(target) = target { |
118f8589 | 1299 | let mut writer = std::fs::OpenOptions::new() |
0d986280 DM |
1300 | .write(true) |
1301 | .create(true) | |
1302 | .create_new(true) | |
1303 | .open(target) | |
118f8589 TL |
1304 | .map_err(|err| { |
1305 | format_err!("unable to create target file {:?} - {}", target, err) | |
1306 | })?; | |
0d986280 | 1307 | std::io::copy(&mut reader, &mut writer)?; |
bf125261 DM |
1308 | } else { |
1309 | let stdout = std::io::stdout(); | |
1310 | let mut writer = stdout.lock(); | |
0d986280 | 1311 | std::io::copy(&mut reader, &mut writer) |
bf125261 DM |
1312 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1313 | } | |
dc155e9b | 1314 | } else if archive_type == ArchiveType::DynamicIndex { |
118f8589 TL |
1315 | let index = client |
1316 | .download_dynamic_index(&manifest, &archive_name) | |
1317 | .await?; | |
df65bd3d | 1318 | |
f4bf7dfc DM |
1319 | let most_used = index.find_most_used_chunks(8); |
1320 | ||
118f8589 TL |
1321 | let chunk_reader = RemoteChunkReader::new( |
1322 | client.clone(), | |
1323 | crypt_config, | |
1324 | file_info.chunk_crypt_mode(), | |
1325 | most_used, | |
1326 | ); | |
f4bf7dfc | 1327 | |
afb4cd28 | 1328 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); |
86eda3eb | 1329 | |
2b7f8dd5 | 1330 | let options = pbs_client::pxar::PxarExtractOptions { |
72064fd0 FG |
1331 | match_list: &[], |
1332 | extract_match_default: true, | |
1333 | allow_existing_dirs, | |
1334 | on_error: None, | |
1335 | }; | |
1336 | ||
bf125261 | 1337 | if let Some(target) = target { |
2b7f8dd5 | 1338 | pbs_client::pxar::extract_archive( |
c443f58b WB |
1339 | pxar::decoder::Decoder::from_std(reader)?, |
1340 | Path::new(target), | |
2b7f8dd5 | 1341 | pbs_client::pxar::Flags::DEFAULT, |
c443f58b | 1342 | |path| { |
4a2e4467 | 1343 | log::debug!("{:?}", path); |
c443f58b | 1344 | }, |
72064fd0 | 1345 | options, |
c443f58b WB |
1346 | ) |
1347 | .map_err(|err| format_err!("error extracting archive - {}", err))?; | |
bf125261 | 1348 | } else { |
88892ea8 DM |
1349 | let mut writer = std::fs::OpenOptions::new() |
1350 | .write(true) | |
1351 | .open("/dev/stdout") | |
1352 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?; | |
afb4cd28 | 1353 | |
bf125261 DM |
1354 | std::io::copy(&mut reader, &mut writer) |
1355 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
1356 | } | |
dc155e9b | 1357 | } else if archive_type == ArchiveType::FixedIndex { |
118f8589 TL |
1358 | let index = client |
1359 | .download_fixed_index(&manifest, &archive_name) | |
1360 | .await?; | |
df65bd3d | 1361 | |
88892ea8 DM |
1362 | let mut writer = if let Some(target) = target { |
1363 | std::fs::OpenOptions::new() | |
bf125261 DM |
1364 | .write(true) |
1365 | .create(true) | |
1366 | .create_new(true) | |
1367 | .open(target) | |
88892ea8 | 1368 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))? |
bf125261 | 1369 | } else { |
88892ea8 DM |
1370 | std::fs::OpenOptions::new() |
1371 | .write(true) | |
1372 | .open("/dev/stdout") | |
1373 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))? | |
1374 | }; | |
afb4cd28 | 1375 | |
118f8589 TL |
1376 | dump_image( |
1377 | client.clone(), | |
1378 | crypt_config.clone(), | |
1379 | file_info.chunk_crypt_mode(), | |
1380 | index, | |
1381 | &mut writer, | |
118f8589 TL |
1382 | ) |
1383 | .await?; | |
3031e44c | 1384 | } |
fef44d4f DM |
1385 | |
1386 | Ok(Value::Null) | |
45db6f89 DM |
1387 | } |
1388 | ||
e0665a64 DC |
1389 | #[api( |
1390 | input: { | |
1391 | properties: { | |
1392 | "dry-run": { | |
1393 | type: bool, | |
1394 | optional: true, | |
1395 | description: "Just show what prune would do, but do not delete anything.", | |
1396 | }, | |
1397 | group: { | |
1398 | type: String, | |
1399 | description: "Backup group", | |
1400 | }, | |
1401 | "prune-options": { | |
434dd3cc | 1402 | type: PruneJobOptions, |
e0665a64 DC |
1403 | flatten: true, |
1404 | }, | |
1405 | "output-format": { | |
1406 | schema: OUTPUT_FORMAT, | |
1407 | optional: true, | |
1408 | }, | |
1409 | quiet: { | |
1410 | type: bool, | |
1411 | optional: true, | |
1412 | default: false, | |
1413 | description: "Minimal output - only show removals.", | |
1414 | }, | |
1415 | repository: { | |
1416 | schema: REPO_URL_SCHEMA, | |
1417 | optional: true, | |
1418 | }, | |
1419 | }, | |
1420 | }, | |
1421 | )] | |
1422 | /// Prune a backup repository. | |
1423 | async fn prune( | |
1424 | dry_run: Option<bool>, | |
1425 | group: String, | |
434dd3cc | 1426 | prune_options: PruneJobOptions, |
e0665a64 | 1427 | quiet: bool, |
118f8589 | 1428 | mut param: Value, |
e0665a64 | 1429 | ) -> Result<Value, Error> { |
2665cef7 | 1430 | let repo = extract_repository_from_value(¶m)?; |
83b7db02 | 1431 | |
d4877712 | 1432 | let client = connect(&repo)?; |
83b7db02 | 1433 | |
d0a03d40 | 1434 | let path = format!("api2/json/admin/datastore/{}/prune", repo.store()); |
83b7db02 | 1435 | |
d6d3b353 | 1436 | let group: BackupGroup = group.parse()?; |
c2043614 | 1437 | |
671c6a96 | 1438 | let output_format = extract_output_format(&mut param); |
9fdc3ef4 | 1439 | |
e0665a64 DC |
1440 | let mut api_param = serde_json::to_value(prune_options)?; |
1441 | if let Some(dry_run) = dry_run { | |
1442 | api_param["dry-run"] = dry_run.into(); | |
1443 | } | |
89ae3c32 | 1444 | merge_group_into(api_param.as_object_mut().unwrap(), group); |
83b7db02 | 1445 | |
e0665a64 | 1446 | let mut result = client.post(&path, Some(api_param)).await?; |
74fa81b8 | 1447 | |
87c42375 | 1448 | record_repository(&repo); |
3b03abfe | 1449 | |
db1e061d DM |
1450 | let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> { |
1451 | let item: PruneListItem = serde_json::from_value(record.to_owned())?; | |
db87d93e | 1452 | Ok(item.backup.to_string()) |
db1e061d DM |
1453 | }; |
1454 | ||
c48aa39f DM |
1455 | let render_prune_action = |v: &Value, _record: &Value| -> Result<String, Error> { |
1456 | Ok(match v.as_bool() { | |
1457 | Some(true) => "keep", | |
1458 | Some(false) => "remove", | |
1459 | None => "unknown", | |
118f8589 TL |
1460 | } |
1461 | .to_string()) | |
c48aa39f DM |
1462 | }; |
1463 | ||
db1e061d DM |
1464 | let options = default_table_format_options() |
1465 | .sortby("backup-type", false) | |
1466 | .sortby("backup-id", false) | |
1467 | .sortby("backup-time", false) | |
118f8589 TL |
1468 | .column( |
1469 | ColumnConfig::new("backup-id") | |
1470 | .renderer(render_snapshot_path) | |
1471 | .header("snapshot"), | |
1472 | ) | |
1473 | .column( | |
1474 | ColumnConfig::new("backup-time") | |
1475 | .renderer(pbs_tools::format::render_epoch) | |
1476 | .header("date"), | |
1477 | ) | |
1478 | .column( | |
1479 | ColumnConfig::new("keep") | |
1480 | .renderer(render_prune_action) | |
1481 | .header("action"), | |
1482 | ); | |
db1e061d | 1483 | |
e351ac78 | 1484 | let return_type = &pbs_api_types::ADMIN_DATASTORE_PRUNE_RETURN_TYPE; |
db1e061d DM |
1485 | |
1486 | let mut data = result["data"].take(); | |
1487 | ||
c48aa39f | 1488 | if quiet { |
118f8589 TL |
1489 | let list: Vec<Value> = data |
1490 | .as_array() | |
1491 | .unwrap() | |
1492 | .iter() | |
1493 | .filter(|item| item["keep"].as_bool() == Some(false)) | |
1494 | .cloned() | |
1495 | .collect(); | |
c48aa39f DM |
1496 | data = list.into(); |
1497 | } | |
1498 | ||
b2362a12 | 1499 | format_and_print_result_full(&mut data, return_type, &output_format, &options); |
d0a03d40 | 1500 | |
43a406fd | 1501 | Ok(Value::Null) |
83b7db02 DM |
1502 | } |
1503 | ||
a47a02ae DM |
1504 | #[api( |
1505 | input: { | |
1506 | properties: { | |
1507 | repository: { | |
1508 | schema: REPO_URL_SCHEMA, | |
1509 | optional: true, | |
1510 | }, | |
1511 | "output-format": { | |
1512 | schema: OUTPUT_FORMAT, | |
1513 | optional: true, | |
1514 | }, | |
1515 | } | |
f9beae9c TL |
1516 | }, |
1517 | returns: { | |
1518 | type: StorageStatus, | |
1519 | }, | |
a47a02ae DM |
1520 | )] |
1521 | /// Get repository status. | |
1522 | async fn status(param: Value) -> Result<Value, Error> { | |
34a816cc DM |
1523 | let repo = extract_repository_from_value(¶m)?; |
1524 | ||
c2043614 | 1525 | let output_format = get_output_format(¶m); |
34a816cc | 1526 | |
f3fde36b | 1527 | let client = connect(&repo)?; |
34a816cc DM |
1528 | |
1529 | let path = format!("api2/json/admin/datastore/{}/status", repo.store()); | |
1530 | ||
1dc117bb | 1531 | let mut result = client.get(&path, None).await?; |
14e08625 | 1532 | let mut data = result["data"].take(); |
34a816cc DM |
1533 | |
1534 | record_repository(&repo); | |
1535 | ||
390c5bdd DM |
1536 | let render_total_percentage = |v: &Value, record: &Value| -> Result<String, Error> { |
1537 | let v = v.as_u64().unwrap(); | |
1538 | let total = record["total"].as_u64().unwrap(); | |
118f8589 TL |
1539 | let roundup = total / 200; |
1540 | let per = ((v + roundup) * 100) / total; | |
e23f5863 DM |
1541 | let info = format!(" ({} %)", per); |
1542 | Ok(format!("{} {:>8}", v, info)) | |
390c5bdd | 1543 | }; |
1dc117bb | 1544 | |
c2043614 | 1545 | let options = default_table_format_options() |
be2425ff | 1546 | .noheader(true) |
e23f5863 | 1547 | .column(ColumnConfig::new("total").renderer(render_total_percentage)) |
390c5bdd DM |
1548 | .column(ColumnConfig::new("used").renderer(render_total_percentage)) |
1549 | .column(ColumnConfig::new("avail").renderer(render_total_percentage)); | |
34a816cc | 1550 | |
b2362a12 | 1551 | let return_type = &API_METHOD_STATUS.returns; |
390c5bdd | 1552 | |
b2362a12 | 1553 | format_and_print_result_full(&mut data, return_type, &output_format, &options); |
34a816cc DM |
1554 | |
1555 | Ok(Value::Null) | |
1556 | } | |
1557 | ||
c443f58b WB |
1558 | /// This is a workaround until we have cleaned up the chunk/reader/... infrastructure for better |
1559 | /// async use! | |
1560 | /// | |
1561 | /// Ideally BufferedDynamicReader gets replaced so the LruCache maps to `BroadcastFuture<Chunk>`, | |
1562 | /// so that we can properly access it from multiple threads simultaneously while not issuing | |
1563 | /// duplicate simultaneous reads over http. | |
43abba4b | 1564 | pub struct BufferedDynamicReadAt { |
c443f58b WB |
1565 | inner: Mutex<BufferedDynamicReader<RemoteChunkReader>>, |
1566 | } | |
1567 | ||
1568 | impl BufferedDynamicReadAt { | |
1569 | fn new(inner: BufferedDynamicReader<RemoteChunkReader>) -> Self { | |
1570 | Self { | |
1571 | inner: Mutex::new(inner), | |
1572 | } | |
1573 | } | |
1574 | } | |
1575 | ||
a6f87283 WB |
1576 | impl ReadAt for BufferedDynamicReadAt { |
1577 | fn start_read_at<'a>( | |
1578 | self: Pin<&'a Self>, | |
c443f58b | 1579 | _cx: &mut Context, |
a6f87283 | 1580 | buf: &'a mut [u8], |
c443f58b | 1581 | offset: u64, |
a6f87283 | 1582 | ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> { |
a6f87283 | 1583 | MaybeReady::Ready(tokio::task::block_in_place(move || { |
c443f58b WB |
1584 | let mut reader = self.inner.lock().unwrap(); |
1585 | reader.seek(SeekFrom::Start(offset))?; | |
dcf5a0f6 | 1586 | reader.read(buf) |
a6f87283 WB |
1587 | })) |
1588 | } | |
1589 | ||
1590 | fn poll_complete<'a>( | |
1591 | self: Pin<&'a Self>, | |
1592 | _op: ReadAtOperation<'a>, | |
1593 | ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> { | |
bbc71e3b | 1594 | panic!("BufferedDynamicReadAt::start_read_at returned Pending"); |
c443f58b WB |
1595 | } |
1596 | } | |
1597 | ||
f2401311 | 1598 | fn main() { |
d91a0f9f | 1599 | pbs_tools::setup_libc_malloc_opts(); |
955aea8a | 1600 | init_cli_logger("PBS_LOG", "info"); |
33d64b81 | 1601 | |
255f378a | 1602 | let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP) |
49fddd98 | 1603 | .arg_param(&["backupspec"]) |
d0a03d40 | 1604 | .completion_cb("repository", complete_repository) |
49811347 | 1605 | .completion_cb("backupspec", complete_backup_source) |
b3f279e2 DM |
1606 | .completion_cb("keyfile", complete_file_name) |
1607 | .completion_cb("master-pubkey-file", complete_file_name) | |
49811347 | 1608 | .completion_cb("chunk-size", complete_chunk_size); |
f8838fe9 | 1609 | |
caea8d61 DM |
1610 | let benchmark_cmd_def = CliCommand::new(&API_METHOD_BENCHMARK) |
1611 | .completion_cb("repository", complete_repository) | |
b3f279e2 | 1612 | .completion_cb("keyfile", complete_file_name); |
caea8d61 | 1613 | |
255f378a | 1614 | let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS) |
4adb574d | 1615 | .completion_cb("ns", complete_namespace) |
d0a03d40 | 1616 | .completion_cb("repository", complete_repository); |
41c039e1 | 1617 | |
255f378a | 1618 | let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION) |
d0a03d40 | 1619 | .completion_cb("repository", complete_repository); |
8cc0d6af | 1620 | |
255f378a | 1621 | let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE) |
49fddd98 | 1622 | .arg_param(&["snapshot", "archive-name", "target"]) |
b2388518 | 1623 | .completion_cb("repository", complete_repository) |
4adb574d | 1624 | .completion_cb("ns", complete_namespace) |
08dc340a DM |
1625 | .completion_cb("snapshot", complete_group_or_snapshot) |
1626 | .completion_cb("archive-name", complete_archive_name) | |
b3f279e2 | 1627 | .completion_cb("target", complete_file_name); |
9f912493 | 1628 | |
255f378a | 1629 | let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE) |
49fddd98 | 1630 | .arg_param(&["group"]) |
4adb574d | 1631 | .completion_cb("ns", complete_namespace) |
9fdc3ef4 | 1632 | .completion_cb("group", complete_backup_group) |
d0a03d40 | 1633 | .completion_cb("repository", complete_repository); |
9f912493 | 1634 | |
118f8589 TL |
1635 | let status_cmd_def = |
1636 | CliCommand::new(&API_METHOD_STATUS).completion_cb("repository", complete_repository); | |
34a816cc | 1637 | |
118f8589 TL |
1638 | let login_cmd_def = |
1639 | CliCommand::new(&API_METHOD_API_LOGIN).completion_cb("repository", complete_repository); | |
e240d8be | 1640 | |
118f8589 TL |
1641 | let logout_cmd_def = |
1642 | CliCommand::new(&API_METHOD_API_LOGOUT).completion_cb("repository", complete_repository); | |
32efac1c | 1643 | |
118f8589 TL |
1644 | let version_cmd_def = |
1645 | CliCommand::new(&API_METHOD_API_VERSION).completion_cb("repository", complete_repository); | |
e39974af | 1646 | |
344add38 DW |
1647 | let change_owner_cmd_def = CliCommand::new(&API_METHOD_CHANGE_BACKUP_OWNER) |
1648 | .arg_param(&["group", "new-owner"]) | |
4adb574d | 1649 | .completion_cb("ns", complete_namespace) |
344add38 | 1650 | .completion_cb("group", complete_backup_group) |
118f8589 | 1651 | .completion_cb("new-owner", complete_auth_id) |
344add38 DW |
1652 | .completion_cb("repository", complete_repository); |
1653 | ||
41c039e1 | 1654 | let cmd_def = CliCommandMap::new() |
48ef3c33 | 1655 | .insert("backup", backup_cmd_def) |
48ef3c33 DM |
1656 | .insert("garbage-collect", garbage_collect_cmd_def) |
1657 | .insert("list", list_cmd_def) | |
1658 | .insert("login", login_cmd_def) | |
1659 | .insert("logout", logout_cmd_def) | |
1660 | .insert("prune", prune_cmd_def) | |
1661 | .insert("restore", restore_cmd_def) | |
a65e3e4b | 1662 | .insert("snapshot", snapshot_mgtm_cli()) |
48ef3c33 | 1663 | .insert("status", status_cmd_def) |
9696f519 | 1664 | .insert("key", key::cli()) |
43abba4b | 1665 | .insert("mount", mount_cmd_def()) |
45f9b32e SR |
1666 | .insert("map", map_cmd_def()) |
1667 | .insert("unmap", unmap_cmd_def()) | |
5830c205 | 1668 | .insert("catalog", catalog_mgmt_cli()) |
caea8d61 | 1669 | .insert("task", task_mgmt_cli()) |
e39974af | 1670 | .insert("version", version_cmd_def) |
344add38 | 1671 | .insert("benchmark", benchmark_cmd_def) |
731eeef2 | 1672 | .insert("change-owner", change_owner_cmd_def) |
226a4e68 | 1673 | .insert("namespace", namespace::cli_map()) |
61205f00 | 1674 | .alias(&["files"], &["snapshot", "files"]) |
edebd523 | 1675 | .alias(&["forget"], &["snapshot", "forget"]) |
0c9209b0 | 1676 | .alias(&["upload-log"], &["snapshot", "upload-log"]) |
118f8589 | 1677 | .alias(&["snapshots"], &["snapshot", "list"]); |
48ef3c33 | 1678 | |
7b22acd0 | 1679 | let rpcenv = CliEnvironment::new(); |
118f8589 TL |
1680 | run_cli_command( |
1681 | cmd_def, | |
1682 | rpcenv, | |
1683 | Some(|future| proxmox_async::runtime::main(future)), | |
1684 | ); | |
ff5d3707 | 1685 | } |