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