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