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