]>
Commit | Line | Data |
---|---|---|
2eeaacb9 | 1 | use std::collections::{HashSet, HashMap}; |
0351f23b WB |
2 | use std::convert::TryFrom; |
3 | use std::io::{self, Read, Write, Seek, SeekFrom}; | |
4 | use std::os::unix::io::{FromRawFd, RawFd}; | |
c443f58b WB |
5 | use std::path::{Path, PathBuf}; |
6 | use std::pin::Pin; | |
7 | use std::sync::{Arc, Mutex}; | |
a6f87283 | 8 | use std::task::Context; |
c443f58b WB |
9 | |
10 | use anyhow::{bail, format_err, Error}; | |
c443f58b | 11 | use futures::future::FutureExt; |
c443f58b | 12 | use futures::stream::{StreamExt, TryStreamExt}; |
c443f58b | 13 | use serde_json::{json, Value}; |
c443f58b | 14 | use tokio::sync::mpsc; |
7c667013 | 15 | use tokio_stream::wrappers::ReceiverStream; |
c443f58b | 16 | use xdg::BaseDirectories; |
2761d6a4 | 17 | |
c443f58b | 18 | use pathpatterns::{MatchEntry, MatchType, PatternFlag}; |
6a7be83e DM |
19 | use proxmox::{ |
20 | tools::{ | |
21 | time::{strftime_local, epoch_i64}, | |
22 | fs::{file_get_contents, file_get_json, replace_file, CreateOptions, image_size}, | |
23 | }, | |
24 | api::{ | |
25 | api, | |
26 | ApiHandler, | |
27 | ApiMethod, | |
28 | RpcEnvironment, | |
29 | schema::*, | |
30 | cli::*, | |
31 | }, | |
32 | }; | |
a6f87283 | 33 | use pxar::accessor::{MaybeReady, ReadAt, ReadAtOperation}; |
ff5d3707 | 34 | |
fe0e04c6 | 35 | use proxmox_backup::tools; |
0224c3c2 | 36 | use proxmox_backup::api2::access::user::UserWithTokens; |
bbf9e7e9 | 37 | use proxmox_backup::api2::types::*; |
e39974af | 38 | use proxmox_backup::api2::version; |
151c6ce2 | 39 | use proxmox_backup::client::*; |
c443f58b | 40 | use proxmox_backup::pxar::catalog::*; |
4d16badf WB |
41 | use proxmox_backup::backup::{ |
42 | archive_type, | |
0351f23b | 43 | decrypt_key, |
8acfd15d | 44 | rsa_encrypt_key_config, |
4d16badf WB |
45 | verify_chunk_size, |
46 | ArchiveType, | |
8e6e18b7 | 47 | AsyncReadChunk, |
4d16badf WB |
48 | BackupDir, |
49 | BackupGroup, | |
50 | BackupManifest, | |
51 | BufferedDynamicReader, | |
f28d9088 | 52 | CATALOG_NAME, |
4d16badf WB |
53 | CatalogReader, |
54 | CatalogWriter, | |
4d16badf WB |
55 | ChunkStream, |
56 | CryptConfig, | |
f28d9088 | 57 | CryptMode, |
4d16badf | 58 | DynamicIndexReader, |
9990af30 | 59 | ENCRYPTED_KEY_BLOB_NAME, |
4d16badf WB |
60 | FixedChunkStream, |
61 | FixedIndexReader, | |
8acfd15d | 62 | KeyConfig, |
4d16badf | 63 | IndexFile, |
4d16badf | 64 | MANIFEST_BLOB_NAME, |
4d16badf WB |
65 | Shell, |
66 | }; | |
ae0be2dd | 67 | |
caea8d61 DM |
68 | mod proxmox_backup_client; |
69 | use proxmox_backup_client::*; | |
70 | ||
a05c0c6f | 71 | const ENV_VAR_PBS_FINGERPRINT: &str = "PBS_FINGERPRINT"; |
d1c65727 | 72 | const ENV_VAR_PBS_PASSWORD: &str = "PBS_PASSWORD"; |
a05c0c6f | 73 | |
33d64b81 | 74 | |
caea8d61 | 75 | pub const REPO_URL_SCHEMA: Schema = StringSchema::new("Repository URL.") |
255f378a DM |
76 | .format(&BACKUP_REPO_URL) |
77 | .max_length(256) | |
78 | .schema(); | |
d0a03d40 | 79 | |
c0a87c12 FG |
80 | pub const KEYFILE_SCHEMA: Schema = |
81 | StringSchema::new("Path to encryption key. All data will be encrypted using this key.") | |
82 | .schema(); | |
83 | ||
84 | pub const KEYFD_SCHEMA: Schema = | |
85 | IntegerSchema::new("Pass an encryption key via an already opened file descriptor.") | |
86 | .minimum(0) | |
87 | .schema(); | |
a47a02ae | 88 | |
c0a87c12 FG |
89 | pub const MASTER_PUBKEY_FILE_SCHEMA: Schema = StringSchema::new( |
90 | "Path to master public key. The encryption key used for a backup will be encrypted using this key and appended to the backup.") | |
0351f23b WB |
91 | .schema(); |
92 | ||
c0a87c12 FG |
93 | pub const MASTER_PUBKEY_FD_SCHEMA: Schema = |
94 | IntegerSchema::new("Pass a master public key via an already opened file descriptor.") | |
95 | .minimum(0) | |
96 | .schema(); | |
97 | ||
a47a02ae DM |
98 | const CHUNK_SIZE_SCHEMA: Schema = IntegerSchema::new( |
99 | "Chunk size in KB. Must be a power of 2.") | |
100 | .minimum(64) | |
101 | .maximum(4096) | |
102 | .default(4096) | |
103 | .schema(); | |
104 | ||
2665cef7 DM |
105 | fn get_default_repository() -> Option<String> { |
106 | std::env::var("PBS_REPOSITORY").ok() | |
107 | } | |
108 | ||
caea8d61 | 109 | pub fn extract_repository_from_value( |
2665cef7 DM |
110 | param: &Value, |
111 | ) -> Result<BackupRepository, Error> { | |
112 | ||
113 | let repo_url = param["repository"] | |
114 | .as_str() | |
115 | .map(String::from) | |
116 | .or_else(get_default_repository) | |
117 | .ok_or_else(|| format_err!("unable to get (default) repository"))?; | |
118 | ||
119 | let repo: BackupRepository = repo_url.parse()?; | |
120 | ||
121 | Ok(repo) | |
122 | } | |
123 | ||
124 | fn extract_repository_from_map( | |
125 | param: &HashMap<String, String>, | |
126 | ) -> Option<BackupRepository> { | |
127 | ||
128 | param.get("repository") | |
129 | .map(String::from) | |
130 | .or_else(get_default_repository) | |
131 | .and_then(|repo_url| repo_url.parse::<BackupRepository>().ok()) | |
132 | } | |
133 | ||
d0a03d40 DM |
134 | fn record_repository(repo: &BackupRepository) { |
135 | ||
136 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
137 | Ok(v) => v, | |
138 | _ => return, | |
139 | }; | |
140 | ||
141 | // usually $HOME/.cache/proxmox-backup/repo-list | |
142 | let path = match base.place_cache_file("repo-list") { | |
143 | Ok(v) => v, | |
144 | _ => return, | |
145 | }; | |
146 | ||
11377a47 | 147 | let mut data = file_get_json(&path, None).unwrap_or_else(|_| json!({})); |
d0a03d40 DM |
148 | |
149 | let repo = repo.to_string(); | |
150 | ||
151 | data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 }; | |
152 | ||
153 | let mut map = serde_json::map::Map::new(); | |
154 | ||
155 | loop { | |
156 | let mut max_used = 0; | |
157 | let mut max_repo = None; | |
158 | for (repo, count) in data.as_object().unwrap() { | |
159 | if map.contains_key(repo) { continue; } | |
160 | if let Some(count) = count.as_i64() { | |
161 | if count > max_used { | |
162 | max_used = count; | |
163 | max_repo = Some(repo); | |
164 | } | |
165 | } | |
166 | } | |
167 | if let Some(repo) = max_repo { | |
168 | map.insert(repo.to_owned(), json!(max_used)); | |
169 | } else { | |
170 | break; | |
171 | } | |
172 | if map.len() > 10 { // store max. 10 repos | |
173 | break; | |
174 | } | |
175 | } | |
176 | ||
177 | let new_data = json!(map); | |
178 | ||
feaa1ad3 | 179 | let _ = replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new()); |
d0a03d40 DM |
180 | } |
181 | ||
43abba4b | 182 | pub fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
d0a03d40 DM |
183 | |
184 | let mut result = vec![]; | |
185 | ||
186 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
187 | Ok(v) => v, | |
188 | _ => return result, | |
189 | }; | |
190 | ||
191 | // usually $HOME/.cache/proxmox-backup/repo-list | |
192 | let path = match base.place_cache_file("repo-list") { | |
193 | Ok(v) => v, | |
194 | _ => return result, | |
195 | }; | |
196 | ||
11377a47 | 197 | let data = file_get_json(&path, None).unwrap_or_else(|_| json!({})); |
d0a03d40 DM |
198 | |
199 | if let Some(map) = data.as_object() { | |
49811347 | 200 | for (repo, _count) in map { |
d0a03d40 DM |
201 | result.push(repo.to_owned()); |
202 | } | |
203 | } | |
204 | ||
205 | result | |
206 | } | |
207 | ||
f3fde36b WB |
208 | fn connect(repo: &BackupRepository) -> Result<HttpClient, Error> { |
209 | connect_do(repo.host(), repo.port(), repo.auth_id()) | |
210 | .map_err(|err| format_err!("error building client for repository {} - {}", repo, err)) | |
211 | } | |
d59dbeca | 212 | |
f3fde36b | 213 | fn connect_do(server: &str, port: u16, auth_id: &Authid) -> Result<HttpClient, Error> { |
a05c0c6f DM |
214 | let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok(); |
215 | ||
d1c65727 DM |
216 | use std::env::VarError::*; |
217 | let password = match std::env::var(ENV_VAR_PBS_PASSWORD) { | |
218 | Ok(p) => Some(p), | |
219 | Err(NotUnicode(_)) => bail!(format!("{} contains bad characters", ENV_VAR_PBS_PASSWORD)), | |
220 | Err(NotPresent) => None, | |
221 | }; | |
222 | ||
93e3581c | 223 | let options = HttpClientOptions::new_interactive(password, fingerprint); |
d59dbeca | 224 | |
34aa8e13 | 225 | HttpClient::new(server, port, auth_id, options) |
d59dbeca DM |
226 | } |
227 | ||
42af4b8f DM |
228 | async fn api_datastore_list_snapshots( |
229 | client: &HttpClient, | |
230 | store: &str, | |
231 | group: Option<BackupGroup>, | |
f24fc116 | 232 | ) -> Result<Value, Error> { |
42af4b8f DM |
233 | |
234 | let path = format!("api2/json/admin/datastore/{}/snapshots", store); | |
235 | ||
236 | let mut args = json!({}); | |
237 | if let Some(group) = group { | |
238 | args["backup-type"] = group.backup_type().into(); | |
239 | args["backup-id"] = group.backup_id().into(); | |
240 | } | |
241 | ||
242 | let mut result = client.get(&path, Some(args)).await?; | |
243 | ||
f24fc116 | 244 | Ok(result["data"].take()) |
42af4b8f DM |
245 | } |
246 | ||
43abba4b | 247 | pub async fn api_datastore_latest_snapshot( |
27c9affb DM |
248 | client: &HttpClient, |
249 | store: &str, | |
250 | group: BackupGroup, | |
6a7be83e | 251 | ) -> Result<(String, String, i64), Error> { |
27c9affb | 252 | |
f24fc116 DM |
253 | let list = api_datastore_list_snapshots(client, store, Some(group.clone())).await?; |
254 | let mut list: Vec<SnapshotListItem> = serde_json::from_value(list)?; | |
27c9affb DM |
255 | |
256 | if list.is_empty() { | |
257 | bail!("backup group {:?} does not contain any snapshots.", group.group_path()); | |
258 | } | |
259 | ||
260 | list.sort_unstable_by(|a, b| b.backup_time.cmp(&a.backup_time)); | |
261 | ||
6a7be83e | 262 | let backup_time = list[0].backup_time; |
27c9affb DM |
263 | |
264 | Ok((group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time)) | |
265 | } | |
266 | ||
e9722f8b | 267 | async fn backup_directory<P: AsRef<Path>>( |
cf9271e2 | 268 | client: &BackupWriter, |
17d6979a | 269 | dir_path: P, |
247cdbce | 270 | archive_name: &str, |
36898ffc | 271 | chunk_size: Option<usize>, |
f1d99e3f | 272 | catalog: Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>, |
77486a60 | 273 | pxar_create_options: proxmox_backup::pxar::PxarCreateOptions, |
e43b9175 | 274 | upload_options: UploadOptions, |
2c3891d1 | 275 | ) -> Result<BackupStats, Error> { |
33d64b81 | 276 | |
6fc053ed CE |
277 | let pxar_stream = PxarBackupStream::open( |
278 | dir_path.as_ref(), | |
6fc053ed | 279 | catalog, |
77486a60 | 280 | pxar_create_options, |
6fc053ed | 281 | )?; |
e9722f8b | 282 | let mut chunk_stream = ChunkStream::new(pxar_stream, chunk_size); |
ff3d3100 | 283 | |
0bfcea6a | 284 | let (tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks |
5e7a09be | 285 | |
7c667013 | 286 | let stream = ReceiverStream::new(rx) |
e9722f8b | 287 | .map_err(Error::from); |
17d6979a | 288 | |
c4ff3dce | 289 | // spawn chunker inside a separate task so that it can run parallel |
e9722f8b | 290 | tokio::spawn(async move { |
db0cb9ce WB |
291 | while let Some(v) = chunk_stream.next().await { |
292 | let _ = tx.send(v).await; | |
293 | } | |
e9722f8b | 294 | }); |
17d6979a | 295 | |
e43b9175 FG |
296 | if upload_options.fixed_size.is_some() { |
297 | bail!("cannot backup directory with fixed chunk size!"); | |
298 | } | |
299 | ||
e9722f8b | 300 | let stats = client |
e43b9175 | 301 | .upload_stream(archive_name, stream, upload_options) |
e9722f8b | 302 | .await?; |
bcd879cf | 303 | |
2c3891d1 | 304 | Ok(stats) |
bcd879cf DM |
305 | } |
306 | ||
e9722f8b | 307 | async fn backup_image<P: AsRef<Path>>( |
cf9271e2 | 308 | client: &BackupWriter, |
6af905c1 DM |
309 | image_path: P, |
310 | archive_name: &str, | |
36898ffc | 311 | chunk_size: Option<usize>, |
e43b9175 | 312 | upload_options: UploadOptions, |
2c3891d1 | 313 | ) -> Result<BackupStats, Error> { |
6af905c1 | 314 | |
6af905c1 DM |
315 | let path = image_path.as_ref().to_owned(); |
316 | ||
e9722f8b | 317 | let file = tokio::fs::File::open(path).await?; |
6af905c1 | 318 | |
db0cb9ce | 319 | let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new()) |
6af905c1 DM |
320 | .map_err(Error::from); |
321 | ||
36898ffc | 322 | let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024)); |
6af905c1 | 323 | |
e43b9175 FG |
324 | if upload_options.fixed_size.is_none() { |
325 | bail!("cannot backup image with dynamic chunk size!"); | |
326 | } | |
327 | ||
e9722f8b | 328 | let stats = client |
e43b9175 | 329 | .upload_stream(archive_name, stream, upload_options) |
e9722f8b | 330 | .await?; |
6af905c1 | 331 | |
2c3891d1 | 332 | Ok(stats) |
6af905c1 DM |
333 | } |
334 | ||
a47a02ae DM |
335 | #[api( |
336 | input: { | |
337 | properties: { | |
338 | repository: { | |
339 | schema: REPO_URL_SCHEMA, | |
340 | optional: true, | |
341 | }, | |
342 | "output-format": { | |
343 | schema: OUTPUT_FORMAT, | |
344 | optional: true, | |
345 | }, | |
346 | } | |
347 | } | |
348 | )] | |
349 | /// List backup groups. | |
350 | async fn list_backup_groups(param: Value) -> Result<Value, Error> { | |
812c6f87 | 351 | |
c81b2b7c DM |
352 | let output_format = get_output_format(¶m); |
353 | ||
2665cef7 | 354 | let repo = extract_repository_from_value(¶m)?; |
812c6f87 | 355 | |
f3fde36b | 356 | let client = connect(&repo)?; |
812c6f87 | 357 | |
d0a03d40 | 358 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
812c6f87 | 359 | |
8a8a4703 | 360 | let mut result = client.get(&path, None).await?; |
812c6f87 | 361 | |
d0a03d40 DM |
362 | record_repository(&repo); |
363 | ||
c81b2b7c DM |
364 | let render_group_path = |_v: &Value, record: &Value| -> Result<String, Error> { |
365 | let item: GroupListItem = serde_json::from_value(record.to_owned())?; | |
366 | let group = BackupGroup::new(item.backup_type, item.backup_id); | |
367 | Ok(group.group_path().to_str().unwrap().to_owned()) | |
368 | }; | |
812c6f87 | 369 | |
18deda40 DM |
370 | let render_last_backup = |_v: &Value, record: &Value| -> Result<String, Error> { |
371 | let item: GroupListItem = serde_json::from_value(record.to_owned())?; | |
e0e5b442 | 372 | let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.last_backup)?; |
18deda40 | 373 | Ok(snapshot.relative_path().to_str().unwrap().to_owned()) |
c81b2b7c | 374 | }; |
812c6f87 | 375 | |
c81b2b7c DM |
376 | let render_files = |_v: &Value, record: &Value| -> Result<String, Error> { |
377 | let item: GroupListItem = serde_json::from_value(record.to_owned())?; | |
4939255f | 378 | Ok(tools::format::render_backup_file_list(&item.files)) |
c81b2b7c | 379 | }; |
812c6f87 | 380 | |
c81b2b7c DM |
381 | let options = default_table_format_options() |
382 | .sortby("backup-type", false) | |
383 | .sortby("backup-id", false) | |
384 | .column(ColumnConfig::new("backup-id").renderer(render_group_path).header("group")) | |
18deda40 DM |
385 | .column( |
386 | ColumnConfig::new("last-backup") | |
387 | .renderer(render_last_backup) | |
388 | .header("last snapshot") | |
389 | .right_align(false) | |
390 | ) | |
c81b2b7c DM |
391 | .column(ColumnConfig::new("backup-count")) |
392 | .column(ColumnConfig::new("files").renderer(render_files)); | |
ad20d198 | 393 | |
c81b2b7c | 394 | let mut data: Value = result["data"].take(); |
ad20d198 | 395 | |
b2362a12 | 396 | let return_type = &proxmox_backup::api2::admin::datastore::API_METHOD_LIST_GROUPS.returns; |
812c6f87 | 397 | |
b2362a12 | 398 | format_and_print_result_full(&mut data, return_type, &output_format, &options); |
34a816cc | 399 | |
812c6f87 DM |
400 | Ok(Value::Null) |
401 | } | |
402 | ||
344add38 DW |
403 | #[api( |
404 | input: { | |
405 | properties: { | |
406 | repository: { | |
407 | schema: REPO_URL_SCHEMA, | |
408 | optional: true, | |
409 | }, | |
410 | group: { | |
411 | type: String, | |
412 | description: "Backup group.", | |
413 | }, | |
414 | "new-owner": { | |
e6dc35ac | 415 | type: Authid, |
344add38 DW |
416 | }, |
417 | } | |
418 | } | |
419 | )] | |
420 | /// Change owner of a backup group | |
421 | async fn change_backup_owner(group: String, mut param: Value) -> Result<(), Error> { | |
422 | ||
423 | let repo = extract_repository_from_value(¶m)?; | |
424 | ||
f3fde36b | 425 | let mut client = connect(&repo)?; |
344add38 DW |
426 | |
427 | param.as_object_mut().unwrap().remove("repository"); | |
428 | ||
429 | let group: BackupGroup = group.parse()?; | |
430 | ||
431 | param["backup-type"] = group.backup_type().into(); | |
432 | param["backup-id"] = group.backup_id().into(); | |
433 | ||
434 | let path = format!("api2/json/admin/datastore/{}/change-owner", repo.store()); | |
435 | client.post(&path, Some(param)).await?; | |
436 | ||
437 | record_repository(&repo); | |
438 | ||
439 | Ok(()) | |
440 | } | |
441 | ||
a47a02ae DM |
442 | #[api( |
443 | input: { | |
444 | properties: { | |
445 | repository: { | |
446 | schema: REPO_URL_SCHEMA, | |
447 | optional: true, | |
448 | }, | |
449 | } | |
450 | } | |
451 | )] | |
452 | /// Try to login. If successful, store ticket. | |
453 | async fn api_login(param: Value) -> Result<Value, Error> { | |
e240d8be DM |
454 | |
455 | let repo = extract_repository_from_value(¶m)?; | |
456 | ||
f3fde36b | 457 | let client = connect(&repo)?; |
8a8a4703 | 458 | client.login().await?; |
e240d8be DM |
459 | |
460 | record_repository(&repo); | |
461 | ||
462 | Ok(Value::Null) | |
463 | } | |
464 | ||
a47a02ae DM |
465 | #[api( |
466 | input: { | |
467 | properties: { | |
468 | repository: { | |
469 | schema: REPO_URL_SCHEMA, | |
470 | optional: true, | |
471 | }, | |
472 | } | |
473 | } | |
474 | )] | |
475 | /// Logout (delete stored ticket). | |
476 | fn api_logout(param: Value) -> Result<Value, Error> { | |
e240d8be DM |
477 | |
478 | let repo = extract_repository_from_value(¶m)?; | |
479 | ||
5030b7ce | 480 | delete_ticket_info("proxmox-backup", repo.host(), repo.user())?; |
e240d8be DM |
481 | |
482 | Ok(Value::Null) | |
483 | } | |
484 | ||
e39974af TL |
485 | #[api( |
486 | input: { | |
487 | properties: { | |
488 | repository: { | |
489 | schema: REPO_URL_SCHEMA, | |
490 | optional: true, | |
491 | }, | |
492 | "output-format": { | |
493 | schema: OUTPUT_FORMAT, | |
494 | optional: true, | |
495 | }, | |
496 | } | |
497 | } | |
498 | )] | |
499 | /// Show client and optional server version | |
500 | async fn api_version(param: Value) -> Result<(), Error> { | |
501 | ||
502 | let output_format = get_output_format(¶m); | |
503 | ||
504 | let mut version_info = json!({ | |
505 | "client": { | |
506 | "version": version::PROXMOX_PKG_VERSION, | |
507 | "release": version::PROXMOX_PKG_RELEASE, | |
508 | "repoid": version::PROXMOX_PKG_REPOID, | |
509 | } | |
510 | }); | |
511 | ||
512 | let repo = extract_repository_from_value(¶m); | |
513 | if let Ok(repo) = repo { | |
f3fde36b | 514 | let client = connect(&repo)?; |
e39974af TL |
515 | |
516 | match client.get("api2/json/version", None).await { | |
517 | Ok(mut result) => version_info["server"] = result["data"].take(), | |
518 | Err(e) => eprintln!("could not connect to server - {}", e), | |
519 | } | |
520 | } | |
521 | if output_format == "text" { | |
522 | println!("client version: {}.{}", version::PROXMOX_PKG_VERSION, version::PROXMOX_PKG_RELEASE); | |
523 | if let Some(server) = version_info["server"].as_object() { | |
524 | let server_version = server["version"].as_str().unwrap(); | |
525 | let server_release = server["release"].as_str().unwrap(); | |
526 | println!("server version: {}.{}", server_version, server_release); | |
527 | } | |
528 | } else { | |
529 | format_and_print_result(&version_info, &output_format); | |
530 | } | |
531 | ||
532 | Ok(()) | |
533 | } | |
534 | ||
a47a02ae | 535 | #[api( |
94913f35 | 536 | input: { |
a47a02ae DM |
537 | properties: { |
538 | repository: { | |
539 | schema: REPO_URL_SCHEMA, | |
540 | optional: true, | |
541 | }, | |
94913f35 DM |
542 | "output-format": { |
543 | schema: OUTPUT_FORMAT, | |
544 | optional: true, | |
545 | }, | |
546 | }, | |
547 | }, | |
a47a02ae DM |
548 | )] |
549 | /// Start garbage collection for a specific repository. | |
550 | async fn start_garbage_collection(param: Value) -> Result<Value, Error> { | |
8cc0d6af | 551 | |
2665cef7 | 552 | let repo = extract_repository_from_value(¶m)?; |
c2043614 DM |
553 | |
554 | let output_format = get_output_format(¶m); | |
8cc0d6af | 555 | |
f3fde36b | 556 | let mut client = connect(&repo)?; |
8cc0d6af | 557 | |
d0a03d40 | 558 | let path = format!("api2/json/admin/datastore/{}/gc", repo.store()); |
8cc0d6af | 559 | |
8a8a4703 | 560 | let result = client.post(&path, None).await?; |
8cc0d6af | 561 | |
8a8a4703 | 562 | record_repository(&repo); |
d0a03d40 | 563 | |
e68269fc | 564 | view_task_result(&mut client, result, &output_format).await?; |
e5f7def4 | 565 | |
e5f7def4 | 566 | Ok(Value::Null) |
8cc0d6af | 567 | } |
33d64b81 | 568 | |
6d233161 FG |
569 | struct CatalogUploadResult { |
570 | catalog_writer: Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>, | |
571 | result: tokio::sync::oneshot::Receiver<Result<BackupStats, Error>>, | |
572 | } | |
573 | ||
bf6e3217 | 574 | fn spawn_catalog_upload( |
3bad3e6e | 575 | client: Arc<BackupWriter>, |
3638341a | 576 | encrypt: bool, |
6d233161 | 577 | ) -> Result<CatalogUploadResult, Error> { |
f1d99e3f DM |
578 | let (catalog_tx, catalog_rx) = std::sync::mpsc::sync_channel(10); // allow to buffer 10 writes |
579 | let catalog_stream = crate::tools::StdChannelStream(catalog_rx); | |
bf6e3217 DM |
580 | let catalog_chunk_size = 512*1024; |
581 | let catalog_chunk_stream = ChunkStream::new(catalog_stream, Some(catalog_chunk_size)); | |
582 | ||
6d233161 | 583 | let catalog_writer = Arc::new(Mutex::new(CatalogWriter::new(crate::tools::StdChannelWriter::new(catalog_tx))?)); |
bf6e3217 DM |
584 | |
585 | let (catalog_result_tx, catalog_result_rx) = tokio::sync::oneshot::channel(); | |
586 | ||
e43b9175 FG |
587 | let upload_options = UploadOptions { |
588 | encrypt, | |
589 | compress: true, | |
590 | ..UploadOptions::default() | |
591 | }; | |
592 | ||
bf6e3217 DM |
593 | tokio::spawn(async move { |
594 | let catalog_upload_result = client | |
e43b9175 | 595 | .upload_stream(CATALOG_NAME, catalog_chunk_stream, upload_options) |
bf6e3217 DM |
596 | .await; |
597 | ||
598 | if let Err(ref err) = catalog_upload_result { | |
599 | eprintln!("catalog upload error - {}", err); | |
600 | client.cancel(); | |
601 | } | |
602 | ||
603 | let _ = catalog_result_tx.send(catalog_upload_result); | |
604 | }); | |
605 | ||
6d233161 | 606 | Ok(CatalogUploadResult { catalog_writer, result: catalog_result_rx }) |
bf6e3217 DM |
607 | } |
608 | ||
2f26b866 FG |
609 | #[derive(Clone, Debug, Eq, PartialEq)] |
610 | enum KeySource { | |
611 | DefaultKey, | |
612 | Fd, | |
613 | Path(String), | |
614 | } | |
615 | ||
616 | fn format_key_source(source: &KeySource, key_type: &str) -> String { | |
617 | match source { | |
618 | KeySource::DefaultKey => format!("Using default {} key..", key_type), | |
619 | KeySource::Fd => format!("Using {} key from file descriptor..", key_type), | |
620 | KeySource::Path(path) => format!("Using {} key from '{}'..", key_type, path), | |
621 | } | |
622 | } | |
623 | ||
624 | #[derive(Clone, Debug, Eq, PartialEq)] | |
625 | struct KeyWithSource { | |
626 | pub source: KeySource, | |
627 | pub key: Vec<u8>, | |
628 | } | |
629 | ||
630 | impl KeyWithSource { | |
631 | pub fn from_fd(key: Vec<u8>) -> Self { | |
632 | Self { | |
633 | source: KeySource::Fd, | |
634 | key, | |
635 | } | |
636 | } | |
637 | ||
638 | pub fn from_default(key: Vec<u8>) -> Self { | |
639 | Self { | |
640 | source: KeySource::DefaultKey, | |
641 | key, | |
642 | } | |
643 | } | |
644 | ||
645 | pub fn from_path(path: String, key: Vec<u8>) -> Self { | |
646 | Self { | |
647 | source: KeySource::Path(path), | |
648 | key, | |
649 | } | |
650 | } | |
651 | } | |
652 | ||
c6a7ea0a FG |
653 | #[derive(Debug, Eq, PartialEq)] |
654 | struct CryptoParams { | |
655 | mode: CryptMode, | |
2f26b866 | 656 | enc_key: Option<KeyWithSource>, |
c0a87c12 | 657 | // FIXME switch to openssl::rsa::rsa<openssl::pkey::Public> once that is Eq? |
2f26b866 | 658 | master_pubkey: Option<KeyWithSource>, |
c6a7ea0a FG |
659 | } |
660 | ||
661 | fn crypto_parameters(param: &Value) -> Result<CryptoParams, Error> { | |
f28d9088 WB |
662 | let keyfile = match param.get("keyfile") { |
663 | Some(Value::String(keyfile)) => Some(keyfile), | |
664 | Some(_) => bail!("bad --keyfile parameter type"), | |
665 | None => None, | |
666 | }; | |
667 | ||
0351f23b WB |
668 | let key_fd = match param.get("keyfd") { |
669 | Some(Value::Number(key_fd)) => Some( | |
670 | RawFd::try_from(key_fd | |
671 | .as_i64() | |
672 | .ok_or_else(|| format_err!("bad key fd: {:?}", key_fd))? | |
673 | ) | |
674 | .map_err(|err| format_err!("bad key fd: {:?}: {}", key_fd, err))? | |
675 | ), | |
676 | Some(_) => bail!("bad --keyfd parameter type"), | |
677 | None => None, | |
678 | }; | |
679 | ||
c0a87c12 FG |
680 | let master_pubkey_file = match param.get("master-pubkey-file") { |
681 | Some(Value::String(keyfile)) => Some(keyfile), | |
682 | Some(_) => bail!("bad --master-pubkey-file parameter type"), | |
683 | None => None, | |
684 | }; | |
685 | ||
686 | let master_pubkey_fd = match param.get("master-pubkey-fd") { | |
687 | Some(Value::Number(key_fd)) => Some( | |
688 | RawFd::try_from(key_fd | |
689 | .as_i64() | |
690 | .ok_or_else(|| format_err!("bad master public key fd: {:?}", key_fd))? | |
691 | ) | |
692 | .map_err(|err| format_err!("bad public master key fd: {:?}: {}", key_fd, err))? | |
693 | ), | |
694 | Some(_) => bail!("bad --master-pubkey-fd parameter type"), | |
695 | None => None, | |
696 | }; | |
697 | ||
c6a7ea0a | 698 | let mode: Option<CryptMode> = match param.get("crypt-mode") { |
f28d9088 WB |
699 | Some(mode) => Some(serde_json::from_value(mode.clone())?), |
700 | None => None, | |
701 | }; | |
702 | ||
2f26b866 | 703 | let key = match (keyfile, key_fd) { |
0351f23b WB |
704 | (None, None) => None, |
705 | (Some(_), Some(_)) => bail!("--keyfile and --keyfd are mutually exclusive"), | |
2f26b866 FG |
706 | (Some(keyfile), None) => Some(KeyWithSource::from_path( |
707 | keyfile.clone(), | |
708 | file_get_contents(keyfile)?, | |
709 | )), | |
0351f23b WB |
710 | (None, Some(fd)) => { |
711 | let input = unsafe { std::fs::File::from_raw_fd(fd) }; | |
712 | let mut data = Vec::new(); | |
2f26b866 FG |
713 | let _len: usize = { input }.read_to_end(&mut data).map_err(|err| { |
714 | format_err!("error reading encryption key from fd {}: {}", fd, err) | |
715 | })?; | |
716 | Some(KeyWithSource::from_fd(data)) | |
0351f23b WB |
717 | } |
718 | }; | |
719 | ||
2f26b866 | 720 | let master_pubkey = match (master_pubkey_file, master_pubkey_fd) { |
c0a87c12 FG |
721 | (None, None) => None, |
722 | (Some(_), Some(_)) => bail!("--keyfile and --keyfd are mutually exclusive"), | |
2f26b866 FG |
723 | (Some(keyfile), None) => Some(KeyWithSource::from_path( |
724 | keyfile.clone(), | |
725 | file_get_contents(keyfile)?, | |
726 | )), | |
c0a87c12 FG |
727 | (None, Some(fd)) => { |
728 | let input = unsafe { std::fs::File::from_raw_fd(fd) }; | |
729 | let mut data = Vec::new(); | |
2f26b866 FG |
730 | let _len: usize = { input } |
731 | .read_to_end(&mut data) | |
732 | .map_err(|err| format_err!("error reading master key from fd {}: {}", fd, err))?; | |
733 | Some(KeyWithSource::from_fd(data)) | |
c0a87c12 FG |
734 | } |
735 | }; | |
736 | ||
94328389 FG |
737 | let res = match mode { |
738 | // no crypt mode, enable encryption if keys are available | |
2f26b866 | 739 | None => match (key, master_pubkey) { |
94328389 FG |
740 | // only default keys if available |
741 | (None, None) => match key::read_optional_default_encryption_key()? { | |
742 | None => CryptoParams { mode: CryptMode::None, enc_key: None, master_pubkey: None }, | |
743 | enc_key => { | |
94328389 FG |
744 | let master_pubkey = key::read_optional_default_master_pubkey()?; |
745 | CryptoParams { | |
746 | mode: CryptMode::Encrypt, | |
747 | enc_key, | |
748 | master_pubkey, | |
749 | } | |
750 | }, | |
751 | }, | |
752 | ||
753 | // explicit master key, default enc key needed | |
754 | (None, master_pubkey) => match key::read_optional_default_encryption_key()? { | |
755 | None => bail!("--master-pubkey-file/--master-pubkey-fd specified, but no key available"), | |
756 | enc_key => { | |
94328389 FG |
757 | CryptoParams { |
758 | mode: CryptMode::Encrypt, | |
759 | enc_key, | |
760 | master_pubkey, | |
761 | } | |
762 | }, | |
8c6854c8 | 763 | }, |
96ee8577 | 764 | |
94328389 FG |
765 | // explicit keyfile, maybe default master key |
766 | (enc_key, None) => CryptoParams { mode: CryptMode::Encrypt, enc_key, master_pubkey: key::read_optional_default_master_pubkey()? }, | |
c0a87c12 | 767 | |
94328389 FG |
768 | // explicit keyfile and master key |
769 | (enc_key, master_pubkey) => CryptoParams { mode: CryptMode::Encrypt, enc_key, master_pubkey }, | |
c0a87c12 FG |
770 | }, |
771 | ||
94328389 | 772 | // explicitly disabled encryption |
2f26b866 | 773 | Some(CryptMode::None) => match (key, master_pubkey) { |
94328389 FG |
774 | // no keys => OK, no encryption |
775 | (None, None) => CryptoParams { mode: CryptMode::None, enc_key: None, master_pubkey: None }, | |
776 | ||
777 | // --keyfile and --crypt-mode=none | |
778 | (Some(_), _) => bail!("--keyfile/--keyfd and --crypt-mode=none are mutually exclusive"), | |
779 | ||
780 | // --master-pubkey-file and --crypt-mode=none | |
781 | (_, Some(_)) => bail!("--master-pubkey-file/--master-pubkey-fd and --crypt-mode=none are mutually exclusive"), | |
c0a87c12 | 782 | }, |
96ee8577 | 783 | |
94328389 | 784 | // explicitly enabled encryption |
2f26b866 | 785 | Some(mode) => match (key, master_pubkey) { |
94328389 FG |
786 | // no key, maybe master key |
787 | (None, master_pubkey) => match key::read_optional_default_encryption_key()? { | |
788 | None => bail!("--crypt-mode without --keyfile and no default key file available"), | |
c0a87c12 FG |
789 | enc_key => { |
790 | eprintln!("Encrypting with default encryption key!"); | |
94328389 FG |
791 | let master_pubkey = match master_pubkey { |
792 | None => key::read_optional_default_master_pubkey()?, | |
793 | master_pubkey => master_pubkey, | |
794 | }; | |
795 | ||
c0a87c12 | 796 | CryptoParams { |
94328389 | 797 | mode, |
c0a87c12 FG |
798 | enc_key, |
799 | master_pubkey, | |
800 | } | |
801 | }, | |
94328389 | 802 | }, |
c0a87c12 | 803 | |
94328389 FG |
804 | // --keyfile and --crypt-mode other than none |
805 | (enc_key, master_pubkey) => { | |
c0a87c12 FG |
806 | let master_pubkey = match master_pubkey { |
807 | None => key::read_optional_default_master_pubkey()?, | |
808 | master_pubkey => master_pubkey, | |
809 | }; | |
c6a7ea0a | 810 | |
94328389 | 811 | CryptoParams { mode, enc_key, master_pubkey } |
beb07279 | 812 | }, |
c0a87c12 | 813 | }, |
94328389 | 814 | }; |
96ee8577 | 815 | |
94328389 | 816 | Ok(res) |
96ee8577 WB |
817 | } |
818 | ||
5bb057e5 | 819 | #[test] |
c6a7ea0a | 820 | // WARNING: there must only be one test for crypto_parameters as the default key handling is not |
5bb057e5 | 821 | // safe w.r.t. concurrency |
c6a7ea0a | 822 | fn test_crypto_parameters_handling() -> Result<(), Error> { |
2f26b866 FG |
823 | let some_key = vec![1;1]; |
824 | let default_key = vec![2;1]; | |
5bb057e5 | 825 | |
2f26b866 FG |
826 | let some_master_key = vec![3;1]; |
827 | let default_master_key = vec![4;1]; | |
828 | ||
15d2c778 FG |
829 | let keypath = "./target/testout/keyfile.test"; |
830 | let master_keypath = "./target/testout/masterkeyfile.test"; | |
831 | let invalid_keypath = "./target/testout/invalid_keyfile.test"; | |
1a89a779 | 832 | |
c0a87c12 FG |
833 | let no_key_res = CryptoParams { |
834 | enc_key: None, | |
835 | master_pubkey: None, | |
836 | mode: CryptMode::None, | |
837 | }; | |
838 | let some_key_res = CryptoParams { | |
2f26b866 FG |
839 | enc_key: Some(KeyWithSource::from_path( |
840 | keypath.to_string(), | |
841 | some_key.clone(), | |
842 | )), | |
c0a87c12 FG |
843 | master_pubkey: None, |
844 | mode: CryptMode::Encrypt, | |
845 | }; | |
1a89a779 | 846 | let some_key_some_master_res = CryptoParams { |
2f26b866 FG |
847 | enc_key: Some(KeyWithSource::from_path( |
848 | keypath.to_string(), | |
849 | some_key.clone(), | |
850 | )), | |
851 | master_pubkey: Some(KeyWithSource::from_path( | |
852 | master_keypath.to_string(), | |
853 | some_master_key.clone(), | |
854 | )), | |
1a89a779 FG |
855 | mode: CryptMode::Encrypt, |
856 | }; | |
857 | let some_key_default_master_res = CryptoParams { | |
2f26b866 FG |
858 | enc_key: Some(KeyWithSource::from_path( |
859 | keypath.to_string(), | |
860 | some_key.clone(), | |
861 | )), | |
862 | master_pubkey: Some(KeyWithSource::from_default(default_master_key.clone())), | |
1a89a779 FG |
863 | mode: CryptMode::Encrypt, |
864 | }; | |
865 | ||
c0a87c12 | 866 | let some_key_sign_res = CryptoParams { |
2f26b866 FG |
867 | enc_key: Some(KeyWithSource::from_path( |
868 | keypath.to_string(), | |
869 | some_key.clone(), | |
870 | )), | |
c0a87c12 FG |
871 | master_pubkey: None, |
872 | mode: CryptMode::SignOnly, | |
873 | }; | |
874 | let default_key_res = CryptoParams { | |
2f26b866 | 875 | enc_key: Some(KeyWithSource::from_default(default_key.clone())), |
c0a87c12 FG |
876 | master_pubkey: None, |
877 | mode: CryptMode::Encrypt, | |
878 | }; | |
879 | let default_key_sign_res = CryptoParams { | |
2f26b866 | 880 | enc_key: Some(KeyWithSource::from_default(default_key.clone())), |
c0a87c12 FG |
881 | master_pubkey: None, |
882 | mode: CryptMode::SignOnly, | |
883 | }; | |
5bb057e5 | 884 | |
2f26b866 FG |
885 | replace_file(&keypath, &some_key, CreateOptions::default())?; |
886 | replace_file(&master_keypath, &some_master_key, CreateOptions::default())?; | |
5bb057e5 FG |
887 | |
888 | // no params, no default key == no key | |
c6a7ea0a | 889 | let res = crypto_parameters(&json!({})); |
5bb057e5 FG |
890 | assert_eq!(res.unwrap(), no_key_res); |
891 | ||
892 | // keyfile param == key from keyfile | |
c6a7ea0a | 893 | let res = crypto_parameters(&json!({"keyfile": keypath})); |
5bb057e5 FG |
894 | assert_eq!(res.unwrap(), some_key_res); |
895 | ||
896 | // crypt mode none == no key | |
c6a7ea0a | 897 | let res = crypto_parameters(&json!({"crypt-mode": "none"})); |
5bb057e5 FG |
898 | assert_eq!(res.unwrap(), no_key_res); |
899 | ||
900 | // crypt mode encrypt/sign-only, no keyfile, no default key == Error | |
c6a7ea0a FG |
901 | assert!(crypto_parameters(&json!({"crypt-mode": "sign-only"})).is_err()); |
902 | assert!(crypto_parameters(&json!({"crypt-mode": "encrypt"})).is_err()); | |
5bb057e5 FG |
903 | |
904 | // crypt mode none with explicit key == Error | |
c6a7ea0a | 905 | assert!(crypto_parameters(&json!({"crypt-mode": "none", "keyfile": keypath})).is_err()); |
5bb057e5 FG |
906 | |
907 | // crypt mode sign-only/encrypt with keyfile == key from keyfile with correct mode | |
c6a7ea0a | 908 | let res = crypto_parameters(&json!({"crypt-mode": "sign-only", "keyfile": keypath})); |
5bb057e5 | 909 | assert_eq!(res.unwrap(), some_key_sign_res); |
c6a7ea0a | 910 | let res = crypto_parameters(&json!({"crypt-mode": "encrypt", "keyfile": keypath})); |
5bb057e5 FG |
911 | assert_eq!(res.unwrap(), some_key_res); |
912 | ||
913 | // invalid keyfile parameter always errors | |
c6a7ea0a FG |
914 | assert!(crypto_parameters(&json!({"keyfile": invalid_keypath})).is_err()); |
915 | assert!(crypto_parameters(&json!({"keyfile": invalid_keypath, "crypt-mode": "none"})).is_err()); | |
916 | assert!(crypto_parameters(&json!({"keyfile": invalid_keypath, "crypt-mode": "sign-only"})).is_err()); | |
917 | assert!(crypto_parameters(&json!({"keyfile": invalid_keypath, "crypt-mode": "encrypt"})).is_err()); | |
5bb057e5 FG |
918 | |
919 | // now set a default key | |
2f26b866 | 920 | unsafe { key::set_test_encryption_key(Ok(Some(default_key.clone()))); } |
5bb057e5 FG |
921 | |
922 | // and repeat | |
923 | ||
924 | // no params but default key == default key | |
c6a7ea0a | 925 | let res = crypto_parameters(&json!({})); |
5bb057e5 FG |
926 | assert_eq!(res.unwrap(), default_key_res); |
927 | ||
928 | // keyfile param == key from keyfile | |
c6a7ea0a | 929 | let res = crypto_parameters(&json!({"keyfile": keypath})); |
5bb057e5 FG |
930 | assert_eq!(res.unwrap(), some_key_res); |
931 | ||
932 | // crypt mode none == no key | |
c6a7ea0a | 933 | let res = crypto_parameters(&json!({"crypt-mode": "none"})); |
5bb057e5 FG |
934 | assert_eq!(res.unwrap(), no_key_res); |
935 | ||
936 | // crypt mode encrypt/sign-only, no keyfile, default key == default key with correct mode | |
c6a7ea0a | 937 | let res = crypto_parameters(&json!({"crypt-mode": "sign-only"})); |
5bb057e5 | 938 | assert_eq!(res.unwrap(), default_key_sign_res); |
c6a7ea0a | 939 | let res = crypto_parameters(&json!({"crypt-mode": "encrypt"})); |
5bb057e5 FG |
940 | assert_eq!(res.unwrap(), default_key_res); |
941 | ||
942 | // crypt mode none with explicit key == Error | |
c6a7ea0a | 943 | assert!(crypto_parameters(&json!({"crypt-mode": "none", "keyfile": keypath})).is_err()); |
5bb057e5 FG |
944 | |
945 | // crypt mode sign-only/encrypt with keyfile == key from keyfile with correct mode | |
c6a7ea0a | 946 | let res = crypto_parameters(&json!({"crypt-mode": "sign-only", "keyfile": keypath})); |
5bb057e5 | 947 | assert_eq!(res.unwrap(), some_key_sign_res); |
c6a7ea0a | 948 | let res = crypto_parameters(&json!({"crypt-mode": "encrypt", "keyfile": keypath})); |
5bb057e5 FG |
949 | assert_eq!(res.unwrap(), some_key_res); |
950 | ||
951 | // invalid keyfile parameter always errors | |
c6a7ea0a FG |
952 | assert!(crypto_parameters(&json!({"keyfile": invalid_keypath})).is_err()); |
953 | assert!(crypto_parameters(&json!({"keyfile": invalid_keypath, "crypt-mode": "none"})).is_err()); | |
954 | assert!(crypto_parameters(&json!({"keyfile": invalid_keypath, "crypt-mode": "sign-only"})).is_err()); | |
955 | assert!(crypto_parameters(&json!({"keyfile": invalid_keypath, "crypt-mode": "encrypt"})).is_err()); | |
5bb057e5 FG |
956 | |
957 | // now make default key retrieval error | |
958 | unsafe { key::set_test_encryption_key(Err(format_err!("test error"))); } | |
959 | ||
960 | // and repeat | |
961 | ||
962 | // no params, default key retrieval errors == Error | |
c6a7ea0a | 963 | assert!(crypto_parameters(&json!({})).is_err()); |
5bb057e5 FG |
964 | |
965 | // keyfile param == key from keyfile | |
c6a7ea0a | 966 | let res = crypto_parameters(&json!({"keyfile": keypath})); |
5bb057e5 FG |
967 | assert_eq!(res.unwrap(), some_key_res); |
968 | ||
969 | // crypt mode none == no key | |
c6a7ea0a | 970 | let res = crypto_parameters(&json!({"crypt-mode": "none"})); |
5bb057e5 FG |
971 | assert_eq!(res.unwrap(), no_key_res); |
972 | ||
973 | // crypt mode encrypt/sign-only, no keyfile, default key error == Error | |
c6a7ea0a FG |
974 | assert!(crypto_parameters(&json!({"crypt-mode": "sign-only"})).is_err()); |
975 | assert!(crypto_parameters(&json!({"crypt-mode": "encrypt"})).is_err()); | |
5bb057e5 FG |
976 | |
977 | // crypt mode none with explicit key == Error | |
c6a7ea0a | 978 | assert!(crypto_parameters(&json!({"crypt-mode": "none", "keyfile": keypath})).is_err()); |
5bb057e5 FG |
979 | |
980 | // crypt mode sign-only/encrypt with keyfile == key from keyfile with correct mode | |
c6a7ea0a | 981 | let res = crypto_parameters(&json!({"crypt-mode": "sign-only", "keyfile": keypath})); |
5bb057e5 | 982 | assert_eq!(res.unwrap(), some_key_sign_res); |
c6a7ea0a | 983 | let res = crypto_parameters(&json!({"crypt-mode": "encrypt", "keyfile": keypath})); |
5bb057e5 FG |
984 | assert_eq!(res.unwrap(), some_key_res); |
985 | ||
986 | // invalid keyfile parameter always errors | |
c6a7ea0a FG |
987 | assert!(crypto_parameters(&json!({"keyfile": invalid_keypath})).is_err()); |
988 | assert!(crypto_parameters(&json!({"keyfile": invalid_keypath, "crypt-mode": "none"})).is_err()); | |
989 | assert!(crypto_parameters(&json!({"keyfile": invalid_keypath, "crypt-mode": "sign-only"})).is_err()); | |
990 | assert!(crypto_parameters(&json!({"keyfile": invalid_keypath, "crypt-mode": "encrypt"})).is_err()); | |
1a89a779 FG |
991 | |
992 | // now remove default key again | |
993 | unsafe { key::set_test_encryption_key(Ok(None)); } | |
994 | // set a default master key | |
2f26b866 | 995 | unsafe { key::set_test_default_master_pubkey(Ok(Some(default_master_key.clone()))); } |
1a89a779 FG |
996 | |
997 | // and use an explicit master key | |
998 | assert!(crypto_parameters(&json!({"master-pubkey-file": master_keypath})).is_err()); | |
999 | // just a default == no key | |
1000 | let res = crypto_parameters(&json!({})); | |
1001 | assert_eq!(res.unwrap(), no_key_res); | |
1002 | ||
1003 | // keyfile param == key from keyfile | |
1004 | let res = crypto_parameters(&json!({"keyfile": keypath, "master-pubkey-file": master_keypath})); | |
1005 | assert_eq!(res.unwrap(), some_key_some_master_res); | |
1006 | // same with fallback to default master key | |
1007 | let res = crypto_parameters(&json!({"keyfile": keypath})); | |
1008 | assert_eq!(res.unwrap(), some_key_default_master_res); | |
1009 | ||
1010 | // crypt mode none == error | |
1011 | assert!(crypto_parameters(&json!({"crypt-mode": "none", "master-pubkey-file": master_keypath})).is_err()); | |
1012 | // with just default master key == no key | |
1013 | let res = crypto_parameters(&json!({"crypt-mode": "none"})); | |
1014 | assert_eq!(res.unwrap(), no_key_res); | |
1015 | ||
1016 | // crypt mode encrypt without enc key == error | |
1017 | assert!(crypto_parameters(&json!({"crypt-mode": "encrypt", "master-pubkey-file": master_keypath})).is_err()); | |
1018 | assert!(crypto_parameters(&json!({"crypt-mode": "encrypt"})).is_err()); | |
1019 | ||
1020 | // crypt mode none with explicit key == Error | |
1021 | assert!(crypto_parameters(&json!({"crypt-mode": "none", "keyfile": keypath, "master-pubkey-file": master_keypath})).is_err()); | |
1022 | assert!(crypto_parameters(&json!({"crypt-mode": "none", "keyfile": keypath})).is_err()); | |
1023 | ||
1024 | // crypt mode encrypt with keyfile == key from keyfile with correct mode | |
1025 | let res = crypto_parameters(&json!({"crypt-mode": "encrypt", "keyfile": keypath, "master-pubkey-file": master_keypath})); | |
1026 | assert_eq!(res.unwrap(), some_key_some_master_res); | |
1027 | let res = crypto_parameters(&json!({"crypt-mode": "encrypt", "keyfile": keypath})); | |
1028 | assert_eq!(res.unwrap(), some_key_default_master_res); | |
1029 | ||
1030 | // invalid master keyfile parameter always errors when a key is passed, even with a valid | |
1031 | // default master key | |
1032 | assert!(crypto_parameters(&json!({"keyfile": keypath, "master-pubkey-file": invalid_keypath})).is_err()); | |
1033 | assert!(crypto_parameters(&json!({"keyfile": keypath, "master-pubkey-file": invalid_keypath,"crypt-mode": "none"})).is_err()); | |
1034 | assert!(crypto_parameters(&json!({"keyfile": keypath, "master-pubkey-file": invalid_keypath,"crypt-mode": "sign-only"})).is_err()); | |
1035 | assert!(crypto_parameters(&json!({"keyfile": keypath, "master-pubkey-file": invalid_keypath,"crypt-mode": "encrypt"})).is_err()); | |
1036 | ||
5bb057e5 FG |
1037 | Ok(()) |
1038 | } | |
1039 | ||
a47a02ae DM |
1040 | #[api( |
1041 | input: { | |
1042 | properties: { | |
1043 | backupspec: { | |
1044 | type: Array, | |
1045 | description: "List of backup source specifications ([<label.ext>:<path>] ...)", | |
1046 | items: { | |
1047 | schema: BACKUP_SOURCE_SCHEMA, | |
1048 | } | |
1049 | }, | |
1050 | repository: { | |
1051 | schema: REPO_URL_SCHEMA, | |
1052 | optional: true, | |
1053 | }, | |
1054 | "include-dev": { | |
1055 | description: "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.", | |
1056 | optional: true, | |
1057 | items: { | |
1058 | type: String, | |
1059 | description: "Path to file.", | |
1060 | } | |
1061 | }, | |
58fcbf5a FE |
1062 | "all-file-systems": { |
1063 | type: Boolean, | |
1064 | description: "Include all mounted subdirectories.", | |
1065 | optional: true, | |
1066 | }, | |
a47a02ae DM |
1067 | keyfile: { |
1068 | schema: KEYFILE_SCHEMA, | |
1069 | optional: true, | |
1070 | }, | |
0351f23b WB |
1071 | "keyfd": { |
1072 | schema: KEYFD_SCHEMA, | |
1073 | optional: true, | |
1074 | }, | |
c0a87c12 FG |
1075 | "master-pubkey-file": { |
1076 | schema: MASTER_PUBKEY_FILE_SCHEMA, | |
1077 | optional: true, | |
1078 | }, | |
1079 | "master-pubkey-fd": { | |
1080 | schema: MASTER_PUBKEY_FD_SCHEMA, | |
1081 | optional: true, | |
1082 | }, | |
24be37e3 WB |
1083 | "crypt-mode": { |
1084 | type: CryptMode, | |
96ee8577 WB |
1085 | optional: true, |
1086 | }, | |
a47a02ae DM |
1087 | "skip-lost-and-found": { |
1088 | type: Boolean, | |
1089 | description: "Skip lost+found directory.", | |
1090 | optional: true, | |
1091 | }, | |
1092 | "backup-type": { | |
1093 | schema: BACKUP_TYPE_SCHEMA, | |
1094 | optional: true, | |
1095 | }, | |
1096 | "backup-id": { | |
1097 | schema: BACKUP_ID_SCHEMA, | |
1098 | optional: true, | |
1099 | }, | |
1100 | "backup-time": { | |
1101 | schema: BACKUP_TIME_SCHEMA, | |
1102 | optional: true, | |
1103 | }, | |
1104 | "chunk-size": { | |
1105 | schema: CHUNK_SIZE_SCHEMA, | |
1106 | optional: true, | |
1107 | }, | |
189996cf CE |
1108 | "exclude": { |
1109 | type: Array, | |
1110 | description: "List of paths or patterns for matching files to exclude.", | |
1111 | optional: true, | |
1112 | items: { | |
1113 | type: String, | |
1114 | description: "Path or match pattern.", | |
1115 | } | |
1116 | }, | |
6fc053ed CE |
1117 | "entries-max": { |
1118 | type: Integer, | |
1119 | description: "Max number of entries to hold in memory.", | |
1120 | optional: true, | |
c443f58b | 1121 | default: proxmox_backup::pxar::ENCODER_MAX_ENTRIES as isize, |
6fc053ed | 1122 | }, |
e02c3d46 DM |
1123 | "verbose": { |
1124 | type: Boolean, | |
1125 | description: "Verbose output.", | |
1126 | optional: true, | |
1127 | }, | |
a47a02ae DM |
1128 | } |
1129 | } | |
1130 | )] | |
1131 | /// Create (host) backup. | |
1132 | async fn create_backup( | |
6049b71f DM |
1133 | param: Value, |
1134 | _info: &ApiMethod, | |
dd5495d6 | 1135 | _rpcenv: &mut dyn RpcEnvironment, |
6049b71f | 1136 | ) -> Result<Value, Error> { |
ff5d3707 | 1137 | |
2665cef7 | 1138 | let repo = extract_repository_from_value(¶m)?; |
ae0be2dd DM |
1139 | |
1140 | let backupspec_list = tools::required_array_param(¶m, "backupspec")?; | |
a914a774 | 1141 | |
eed6db39 DM |
1142 | let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false); |
1143 | ||
5b72c9b4 DM |
1144 | let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false); |
1145 | ||
219ef0e6 DM |
1146 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
1147 | ||
ca5d0b61 DM |
1148 | let backup_time_opt = param["backup-time"].as_i64(); |
1149 | ||
36898ffc | 1150 | let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize); |
2d9d143a | 1151 | |
247cdbce DM |
1152 | if let Some(size) = chunk_size_opt { |
1153 | verify_chunk_size(size)?; | |
2d9d143a DM |
1154 | } |
1155 | ||
c6a7ea0a | 1156 | let crypto = crypto_parameters(¶m)?; |
6d0983db | 1157 | |
f69adc81 | 1158 | let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename()); |
fba30411 | 1159 | |
bbf9e7e9 | 1160 | let backup_type = param["backup-type"].as_str().unwrap_or("host"); |
ca5d0b61 | 1161 | |
2eeaacb9 DM |
1162 | let include_dev = param["include-dev"].as_array(); |
1163 | ||
c443f58b WB |
1164 | let entries_max = param["entries-max"].as_u64() |
1165 | .unwrap_or(proxmox_backup::pxar::ENCODER_MAX_ENTRIES as u64); | |
6fc053ed | 1166 | |
189996cf | 1167 | let empty = Vec::new(); |
c443f58b WB |
1168 | let exclude_args = param["exclude"].as_array().unwrap_or(&empty); |
1169 | ||
239e49f9 | 1170 | let mut pattern_list = Vec::with_capacity(exclude_args.len()); |
c443f58b WB |
1171 | for entry in exclude_args { |
1172 | let entry = entry.as_str().ok_or_else(|| format_err!("Invalid pattern string slice"))?; | |
239e49f9 | 1173 | pattern_list.push( |
c443f58b WB |
1174 | MatchEntry::parse_pattern(entry, PatternFlag::PATH_NAME, MatchType::Exclude) |
1175 | .map_err(|err| format_err!("invalid exclude pattern entry: {}", err))? | |
1176 | ); | |
189996cf CE |
1177 | } |
1178 | ||
2eeaacb9 DM |
1179 | let mut devices = if all_file_systems { None } else { Some(HashSet::new()) }; |
1180 | ||
1181 | if let Some(include_dev) = include_dev { | |
1182 | if all_file_systems { | |
1183 | bail!("option 'all-file-systems' conflicts with option 'include-dev'"); | |
1184 | } | |
1185 | ||
1186 | let mut set = HashSet::new(); | |
1187 | for path in include_dev { | |
1188 | let path = path.as_str().unwrap(); | |
1189 | let stat = nix::sys::stat::stat(path) | |
1190 | .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?; | |
1191 | set.insert(stat.st_dev); | |
1192 | } | |
1193 | devices = Some(set); | |
1194 | } | |
1195 | ||
ae0be2dd | 1196 | let mut upload_list = vec![]; |
f2b4b4b9 | 1197 | let mut target_set = HashSet::new(); |
a914a774 | 1198 | |
ae0be2dd | 1199 | for backupspec in backupspec_list { |
7cc3473a DM |
1200 | let spec = parse_backup_specification(backupspec.as_str().unwrap())?; |
1201 | let filename = &spec.config_string; | |
1202 | let target = &spec.archive_name; | |
bcd879cf | 1203 | |
f2b4b4b9 SI |
1204 | if target_set.contains(target) { |
1205 | bail!("got target twice: '{}'", target); | |
1206 | } | |
1207 | target_set.insert(target.to_string()); | |
1208 | ||
eb1804c5 DM |
1209 | use std::os::unix::fs::FileTypeExt; |
1210 | ||
3fa71727 CE |
1211 | let metadata = std::fs::metadata(filename) |
1212 | .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?; | |
eb1804c5 | 1213 | let file_type = metadata.file_type(); |
23bb8780 | 1214 | |
7cc3473a DM |
1215 | match spec.spec_type { |
1216 | BackupSpecificationType::PXAR => { | |
ec8a9bb9 DM |
1217 | if !file_type.is_dir() { |
1218 | bail!("got unexpected file type (expected directory)"); | |
1219 | } | |
7cc3473a | 1220 | upload_list.push((BackupSpecificationType::PXAR, filename.to_owned(), format!("{}.didx", target), 0)); |
ec8a9bb9 | 1221 | } |
7cc3473a | 1222 | BackupSpecificationType::IMAGE => { |
ec8a9bb9 DM |
1223 | if !(file_type.is_file() || file_type.is_block_device()) { |
1224 | bail!("got unexpected file type (expected file or block device)"); | |
1225 | } | |
eb1804c5 | 1226 | |
e18a6c9e | 1227 | let size = image_size(&PathBuf::from(filename))?; |
23bb8780 | 1228 | |
ec8a9bb9 | 1229 | if size == 0 { bail!("got zero-sized file '{}'", filename); } |
ae0be2dd | 1230 | |
7cc3473a | 1231 | upload_list.push((BackupSpecificationType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size)); |
ec8a9bb9 | 1232 | } |
7cc3473a | 1233 | BackupSpecificationType::CONFIG => { |
ec8a9bb9 DM |
1234 | if !file_type.is_file() { |
1235 | bail!("got unexpected file type (expected regular file)"); | |
1236 | } | |
7cc3473a | 1237 | upload_list.push((BackupSpecificationType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len())); |
ec8a9bb9 | 1238 | } |
7cc3473a | 1239 | BackupSpecificationType::LOGFILE => { |
79679c2d DM |
1240 | if !file_type.is_file() { |
1241 | bail!("got unexpected file type (expected regular file)"); | |
1242 | } | |
7cc3473a | 1243 | upload_list.push((BackupSpecificationType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len())); |
ec8a9bb9 | 1244 | } |
ae0be2dd DM |
1245 | } |
1246 | } | |
1247 | ||
22a9189e | 1248 | let backup_time = backup_time_opt.unwrap_or_else(epoch_i64); |
ae0be2dd | 1249 | |
f3fde36b | 1250 | let client = connect(&repo)?; |
d0a03d40 DM |
1251 | record_repository(&repo); |
1252 | ||
6a7be83e | 1253 | println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time)?); |
ca5d0b61 | 1254 | |
f69adc81 | 1255 | println!("Client name: {}", proxmox::tools::nodename()); |
ca5d0b61 | 1256 | |
6a7be83e | 1257 | let start_time = std::time::Instant::now(); |
ca5d0b61 | 1258 | |
6a7be83e | 1259 | println!("Starting backup protocol: {}", strftime_local("%c", epoch_i64())?); |
51144821 | 1260 | |
c6a7ea0a | 1261 | let (crypt_config, rsa_encrypted_key) = match crypto.enc_key { |
bb823140 | 1262 | None => (None, None), |
2f26b866 FG |
1263 | Some(key_with_source) => { |
1264 | println!( | |
1265 | "{}", | |
1266 | format_key_source(&key_with_source.source, "encryption") | |
1267 | ); | |
1268 | ||
1269 | let (key, created, fingerprint) = | |
1270 | decrypt_key(&key_with_source.key, &key::get_encryption_key_password)?; | |
6f2626ae | 1271 | println!("Encryption key fingerprint: {}", fingerprint); |
bb823140 | 1272 | |
44288184 | 1273 | let crypt_config = CryptConfig::new(key)?; |
bb823140 | 1274 | |
c0a87c12 | 1275 | match crypto.master_pubkey { |
2f26b866 FG |
1276 | Some(pem_with_source) => { |
1277 | println!("{}", format_key_source(&pem_with_source.source, "master")); | |
1278 | ||
1279 | let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_with_source.key)?; | |
82a103c8 | 1280 | |
1c86893d | 1281 | let mut key_config = KeyConfig::without_password(key)?; |
82a103c8 | 1282 | key_config.created = created; // keep original value |
82a103c8 | 1283 | |
8acfd15d | 1284 | let enc_key = rsa_encrypt_key_config(rsa, &key_config)?; |
6f2626ae | 1285 | |
05389a01 | 1286 | (Some(Arc::new(crypt_config)), Some(enc_key)) |
2f26b866 | 1287 | }, |
05389a01 | 1288 | _ => (Some(Arc::new(crypt_config)), None), |
bb823140 | 1289 | } |
6d0983db DM |
1290 | } |
1291 | }; | |
f98ac774 | 1292 | |
8a8a4703 DM |
1293 | let client = BackupWriter::start( |
1294 | client, | |
b957aa81 | 1295 | crypt_config.clone(), |
8a8a4703 DM |
1296 | repo.store(), |
1297 | backup_type, | |
1298 | &backup_id, | |
1299 | backup_time, | |
1300 | verbose, | |
61d7b501 | 1301 | false |
8a8a4703 DM |
1302 | ).await?; |
1303 | ||
8b7f8d3f FG |
1304 | let download_previous_manifest = match client.previous_backup_time().await { |
1305 | Ok(Some(backup_time)) => { | |
1306 | println!( | |
1307 | "Downloading previous manifest ({})", | |
1308 | strftime_local("%c", backup_time)? | |
1309 | ); | |
1310 | true | |
1311 | } | |
1312 | Ok(None) => { | |
1313 | println!("No previous manifest available."); | |
1314 | false | |
1315 | } | |
1316 | Err(_) => { | |
1317 | // Fallback for outdated server, TODO remove/bubble up with 2.0 | |
1318 | true | |
1319 | } | |
1320 | }; | |
1321 | ||
1322 | let previous_manifest = if download_previous_manifest { | |
1323 | match client.download_previous_manifest().await { | |
1324 | Ok(previous_manifest) => { | |
1325 | match previous_manifest.check_fingerprint(crypt_config.as_ref().map(Arc::as_ref)) { | |
1326 | Ok(()) => Some(Arc::new(previous_manifest)), | |
1327 | Err(err) => { | |
1328 | println!("Couldn't re-use previous manifest - {}", err); | |
1329 | None | |
1330 | } | |
1331 | } | |
23f9503a | 1332 | } |
8b7f8d3f FG |
1333 | Err(err) => { |
1334 | println!("Couldn't download previous manifest - {}", err); | |
1335 | None | |
1336 | } | |
1337 | } | |
1338 | } else { | |
1339 | None | |
b957aa81 DM |
1340 | }; |
1341 | ||
6a7be83e | 1342 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time)?; |
8a8a4703 DM |
1343 | let mut manifest = BackupManifest::new(snapshot); |
1344 | ||
5d85847f | 1345 | let mut catalog = None; |
6d233161 | 1346 | let mut catalog_result_rx = None; |
8a8a4703 DM |
1347 | |
1348 | for (backup_type, filename, target, size) in upload_list { | |
1349 | match backup_type { | |
7cc3473a | 1350 | BackupSpecificationType::CONFIG => { |
e43b9175 FG |
1351 | let upload_options = UploadOptions { |
1352 | compress: true, | |
c6a7ea0a | 1353 | encrypt: crypto.mode == CryptMode::Encrypt, |
e43b9175 FG |
1354 | ..UploadOptions::default() |
1355 | }; | |
1356 | ||
5b32820e | 1357 | println!("Upload config file '{}' to '{}' as {}", filename, repo, target); |
8a8a4703 | 1358 | let stats = client |
e43b9175 | 1359 | .upload_blob_from_file(&filename, &target, upload_options) |
8a8a4703 | 1360 | .await?; |
c6a7ea0a | 1361 | manifest.add_file(target, stats.size, stats.csum, crypto.mode)?; |
8a8a4703 | 1362 | } |
7cc3473a | 1363 | BackupSpecificationType::LOGFILE => { // fixme: remove - not needed anymore ? |
e43b9175 FG |
1364 | let upload_options = UploadOptions { |
1365 | compress: true, | |
c6a7ea0a | 1366 | encrypt: crypto.mode == CryptMode::Encrypt, |
e43b9175 FG |
1367 | ..UploadOptions::default() |
1368 | }; | |
1369 | ||
5b32820e | 1370 | println!("Upload log file '{}' to '{}' as {}", filename, repo, target); |
8a8a4703 | 1371 | let stats = client |
e43b9175 | 1372 | .upload_blob_from_file(&filename, &target, upload_options) |
8a8a4703 | 1373 | .await?; |
c6a7ea0a | 1374 | manifest.add_file(target, stats.size, stats.csum, crypto.mode)?; |
8a8a4703 | 1375 | } |
7cc3473a | 1376 | BackupSpecificationType::PXAR => { |
5d85847f DC |
1377 | // start catalog upload on first use |
1378 | if catalog.is_none() { | |
c6a7ea0a | 1379 | let catalog_upload_res = spawn_catalog_upload(client.clone(), crypto.mode == CryptMode::Encrypt)?; |
6d233161 FG |
1380 | catalog = Some(catalog_upload_res.catalog_writer); |
1381 | catalog_result_rx = Some(catalog_upload_res.result); | |
5d85847f DC |
1382 | } |
1383 | let catalog = catalog.as_ref().unwrap(); | |
1384 | ||
5b32820e | 1385 | println!("Upload directory '{}' to '{}' as {}", filename, repo, target); |
8a8a4703 | 1386 | catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?; |
77486a60 FG |
1387 | |
1388 | let pxar_options = proxmox_backup::pxar::PxarCreateOptions { | |
1389 | device_set: devices.clone(), | |
1390 | patterns: pattern_list.clone(), | |
1391 | entries_max: entries_max as usize, | |
1392 | skip_lost_and_found, | |
1393 | verbose, | |
1394 | }; | |
1395 | ||
e43b9175 FG |
1396 | let upload_options = UploadOptions { |
1397 | previous_manifest: previous_manifest.clone(), | |
1398 | compress: true, | |
c6a7ea0a | 1399 | encrypt: crypto.mode == CryptMode::Encrypt, |
e43b9175 FG |
1400 | ..UploadOptions::default() |
1401 | }; | |
1402 | ||
8a8a4703 DM |
1403 | let stats = backup_directory( |
1404 | &client, | |
1405 | &filename, | |
1406 | &target, | |
1407 | chunk_size_opt, | |
8a8a4703 | 1408 | catalog.clone(), |
77486a60 | 1409 | pxar_options, |
e43b9175 | 1410 | upload_options, |
8a8a4703 | 1411 | ).await?; |
c6a7ea0a | 1412 | manifest.add_file(target, stats.size, stats.csum, crypto.mode)?; |
8a8a4703 DM |
1413 | catalog.lock().unwrap().end_directory()?; |
1414 | } | |
7cc3473a | 1415 | BackupSpecificationType::IMAGE => { |
8a8a4703 | 1416 | println!("Upload image '{}' to '{:?}' as {}", filename, repo, target); |
e43b9175 FG |
1417 | |
1418 | let upload_options = UploadOptions { | |
1419 | previous_manifest: previous_manifest.clone(), | |
1420 | fixed_size: Some(size), | |
1421 | compress: true, | |
c6a7ea0a | 1422 | encrypt: crypto.mode == CryptMode::Encrypt, |
e43b9175 FG |
1423 | }; |
1424 | ||
8a8a4703 DM |
1425 | let stats = backup_image( |
1426 | &client, | |
e43b9175 | 1427 | &filename, |
8a8a4703 | 1428 | &target, |
8a8a4703 | 1429 | chunk_size_opt, |
e43b9175 | 1430 | upload_options, |
8a8a4703 | 1431 | ).await?; |
c6a7ea0a | 1432 | manifest.add_file(target, stats.size, stats.csum, crypto.mode)?; |
6af905c1 DM |
1433 | } |
1434 | } | |
8a8a4703 | 1435 | } |
4818c8b6 | 1436 | |
8a8a4703 | 1437 | // finalize and upload catalog |
5d85847f | 1438 | if let Some(catalog) = catalog { |
8a8a4703 DM |
1439 | let mutex = Arc::try_unwrap(catalog) |
1440 | .map_err(|_| format_err!("unable to get catalog (still used)"))?; | |
1441 | let mut catalog = mutex.into_inner().unwrap(); | |
bf6e3217 | 1442 | |
8a8a4703 | 1443 | catalog.finish()?; |
2761d6a4 | 1444 | |
8a8a4703 | 1445 | drop(catalog); // close upload stream |
2761d6a4 | 1446 | |
6d233161 | 1447 | if let Some(catalog_result_rx) = catalog_result_rx { |
5d85847f | 1448 | let stats = catalog_result_rx.await??; |
c6a7ea0a | 1449 | manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum, crypto.mode)?; |
5d85847f | 1450 | } |
8a8a4703 | 1451 | } |
2761d6a4 | 1452 | |
8a8a4703 | 1453 | if let Some(rsa_encrypted_key) = rsa_encrypted_key { |
9990af30 | 1454 | let target = ENCRYPTED_KEY_BLOB_NAME; |
8a8a4703 | 1455 | println!("Upload RSA encoded key to '{:?}' as {}", repo, target); |
e43b9175 | 1456 | let options = UploadOptions { compress: false, encrypt: false, ..UploadOptions::default() }; |
8a8a4703 | 1457 | let stats = client |
e43b9175 | 1458 | .upload_blob_from_data(rsa_encrypted_key, target, options) |
8a8a4703 | 1459 | .await?; |
c6a7ea0a | 1460 | manifest.add_file(target.to_string(), stats.size, stats.csum, crypto.mode)?; |
8a8a4703 | 1461 | |
8a8a4703 | 1462 | } |
8a8a4703 | 1463 | // create manifest (index.json) |
3638341a | 1464 | // manifests are never encrypted, but include a signature |
dfa517ad | 1465 | let manifest = manifest.to_string(crypt_config.as_ref().map(Arc::as_ref)) |
b53f6379 | 1466 | .map_err(|err| format_err!("unable to format manifest - {}", err))?; |
3638341a | 1467 | |
b53f6379 | 1468 | |
9688f6de | 1469 | if verbose { println!("Upload index.json to '{}'", repo) }; |
e43b9175 | 1470 | let options = UploadOptions { compress: true, encrypt: false, ..UploadOptions::default() }; |
8a8a4703 | 1471 | client |
e43b9175 | 1472 | .upload_blob_from_data(manifest.into_bytes(), MANIFEST_BLOB_NAME, options) |
8a8a4703 | 1473 | .await?; |
2c3891d1 | 1474 | |
8a8a4703 | 1475 | client.finish().await?; |
c4ff3dce | 1476 | |
6a7be83e DM |
1477 | let end_time = std::time::Instant::now(); |
1478 | let elapsed = end_time.duration_since(start_time); | |
1479 | println!("Duration: {:.2}s", elapsed.as_secs_f64()); | |
3ec3ec3f | 1480 | |
6a7be83e | 1481 | println!("End Time: {}", strftime_local("%c", epoch_i64())?); |
3d5c11e5 | 1482 | |
8a8a4703 | 1483 | Ok(Value::Null) |
f98ea63d DM |
1484 | } |
1485 | ||
d0a03d40 | 1486 | fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
f98ea63d DM |
1487 | |
1488 | let mut result = vec![]; | |
1489 | ||
1490 | let data: Vec<&str> = arg.splitn(2, ':').collect(); | |
1491 | ||
bff11030 | 1492 | if data.len() != 2 { |
8968258b DM |
1493 | result.push(String::from("root.pxar:/")); |
1494 | result.push(String::from("etc.pxar:/etc")); | |
bff11030 DM |
1495 | return result; |
1496 | } | |
f98ea63d | 1497 | |
496a6784 | 1498 | let files = tools::complete_file_name(data[1], param); |
f98ea63d DM |
1499 | |
1500 | for file in files { | |
1501 | result.push(format!("{}:{}", data[0], file)); | |
1502 | } | |
1503 | ||
1504 | result | |
ff5d3707 | 1505 | } |
1506 | ||
8e6e18b7 | 1507 | async fn dump_image<W: Write>( |
88892ea8 DM |
1508 | client: Arc<BackupReader>, |
1509 | crypt_config: Option<Arc<CryptConfig>>, | |
14f6c9cb | 1510 | crypt_mode: CryptMode, |
88892ea8 DM |
1511 | index: FixedIndexReader, |
1512 | mut writer: W, | |
fd04ca7a | 1513 | verbose: bool, |
88892ea8 DM |
1514 | ) -> Result<(), Error> { |
1515 | ||
1516 | let most_used = index.find_most_used_chunks(8); | |
1517 | ||
14f6c9cb | 1518 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, crypt_mode, most_used); |
88892ea8 DM |
1519 | |
1520 | // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy | |
1521 | // and thus slows down reading. Instead, directly use RemoteChunkReader | |
fd04ca7a DM |
1522 | let mut per = 0; |
1523 | let mut bytes = 0; | |
1524 | let start_time = std::time::Instant::now(); | |
1525 | ||
88892ea8 DM |
1526 | for pos in 0..index.index_count() { |
1527 | let digest = index.index_digest(pos).unwrap(); | |
8e6e18b7 | 1528 | let raw_data = chunk_reader.read_chunk(&digest).await?; |
88892ea8 | 1529 | writer.write_all(&raw_data)?; |
fd04ca7a DM |
1530 | bytes += raw_data.len(); |
1531 | if verbose { | |
1532 | let next_per = ((pos+1)*100)/index.index_count(); | |
1533 | if per != next_per { | |
1534 | eprintln!("progress {}% (read {} bytes, duration {} sec)", | |
1535 | next_per, bytes, start_time.elapsed().as_secs()); | |
1536 | per = next_per; | |
1537 | } | |
1538 | } | |
88892ea8 DM |
1539 | } |
1540 | ||
fd04ca7a DM |
1541 | let end_time = std::time::Instant::now(); |
1542 | let elapsed = end_time.duration_since(start_time); | |
1543 | eprintln!("restore image complete (bytes={}, duration={:.2}s, speed={:.2}MB/s)", | |
1544 | bytes, | |
1545 | elapsed.as_secs_f64(), | |
1546 | bytes as f64/(1024.0*1024.0*elapsed.as_secs_f64()) | |
1547 | ); | |
1548 | ||
1549 | ||
88892ea8 DM |
1550 | Ok(()) |
1551 | } | |
1552 | ||
dc155e9b | 1553 | fn parse_archive_type(name: &str) -> (String, ArchiveType) { |
2d32fe2c TL |
1554 | if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") { |
1555 | (name.into(), archive_type(name).unwrap()) | |
1556 | } else if name.ends_with(".pxar") { | |
dc155e9b TL |
1557 | (format!("{}.didx", name), ArchiveType::DynamicIndex) |
1558 | } else if name.ends_with(".img") { | |
1559 | (format!("{}.fidx", name), ArchiveType::FixedIndex) | |
1560 | } else { | |
1561 | (format!("{}.blob", name), ArchiveType::Blob) | |
1562 | } | |
1563 | } | |
1564 | ||
a47a02ae DM |
1565 | #[api( |
1566 | input: { | |
1567 | properties: { | |
1568 | repository: { | |
1569 | schema: REPO_URL_SCHEMA, | |
1570 | optional: true, | |
1571 | }, | |
1572 | snapshot: { | |
1573 | type: String, | |
1574 | description: "Group/Snapshot path.", | |
1575 | }, | |
1576 | "archive-name": { | |
1577 | description: "Backup archive name.", | |
1578 | type: String, | |
1579 | }, | |
1580 | target: { | |
1581 | type: String, | |
90c815bf | 1582 | description: r###"Target directory path. Use '-' to write to standard output. |
8a8a4703 | 1583 | |
5eee6d89 | 1584 | We do not extraxt '.pxar' archives when writing to standard output. |
8a8a4703 | 1585 | |
a47a02ae DM |
1586 | "### |
1587 | }, | |
1588 | "allow-existing-dirs": { | |
1589 | type: Boolean, | |
1590 | description: "Do not fail if directories already exists.", | |
1591 | optional: true, | |
1592 | }, | |
1593 | keyfile: { | |
1594 | schema: KEYFILE_SCHEMA, | |
1595 | optional: true, | |
1596 | }, | |
0351f23b WB |
1597 | "keyfd": { |
1598 | schema: KEYFD_SCHEMA, | |
1599 | optional: true, | |
1600 | }, | |
24be37e3 WB |
1601 | "crypt-mode": { |
1602 | type: CryptMode, | |
96ee8577 WB |
1603 | optional: true, |
1604 | }, | |
a47a02ae DM |
1605 | } |
1606 | } | |
1607 | )] | |
1608 | /// Restore backup repository. | |
1609 | async fn restore(param: Value) -> Result<Value, Error> { | |
2665cef7 | 1610 | let repo = extract_repository_from_value(¶m)?; |
9f912493 | 1611 | |
86eda3eb DM |
1612 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
1613 | ||
46d5aa0a DM |
1614 | let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false); |
1615 | ||
d5c34d98 DM |
1616 | let archive_name = tools::required_string_param(¶m, "archive-name")?; |
1617 | ||
f3fde36b | 1618 | let client = connect(&repo)?; |
d0a03d40 | 1619 | |
d0a03d40 | 1620 | record_repository(&repo); |
d5c34d98 | 1621 | |
9f912493 | 1622 | let path = tools::required_string_param(¶m, "snapshot")?; |
9f912493 | 1623 | |
86eda3eb | 1624 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { |
d6d3b353 | 1625 | let group: BackupGroup = path.parse()?; |
27c9affb | 1626 | api_datastore_latest_snapshot(&client, repo.store(), group).await? |
d5c34d98 | 1627 | } else { |
a67f7d0a | 1628 | let snapshot: BackupDir = path.parse()?; |
86eda3eb DM |
1629 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) |
1630 | }; | |
9f912493 | 1631 | |
d5c34d98 | 1632 | let target = tools::required_string_param(¶m, "target")?; |
bf125261 | 1633 | let target = if target == "-" { None } else { Some(target) }; |
2ae7d196 | 1634 | |
c6a7ea0a | 1635 | let crypto = crypto_parameters(¶m)?; |
2ae7d196 | 1636 | |
c6a7ea0a | 1637 | let crypt_config = match crypto.enc_key { |
86eda3eb | 1638 | None => None, |
2f26b866 FG |
1639 | Some(ref key) => { |
1640 | let (key, _, _) = | |
1641 | decrypt_key(&key.key, &key::get_encryption_key_password).map_err(|err| { | |
1642 | eprintln!("{}", format_key_source(&key.source, "encryption")); | |
1643 | err | |
1644 | })?; | |
86eda3eb DM |
1645 | Some(Arc::new(CryptConfig::new(key)?)) |
1646 | } | |
1647 | }; | |
d5c34d98 | 1648 | |
296c50ba DM |
1649 | let client = BackupReader::start( |
1650 | client, | |
1651 | crypt_config.clone(), | |
1652 | repo.store(), | |
1653 | &backup_type, | |
1654 | &backup_id, | |
1655 | backup_time, | |
1656 | true, | |
1657 | ).await?; | |
86eda3eb | 1658 | |
48fbbfeb FG |
1659 | let (archive_name, archive_type) = parse_archive_type(archive_name); |
1660 | ||
2107a5ae | 1661 | let (manifest, backup_index_data) = client.download_manifest().await?; |
02fcf372 | 1662 | |
48fbbfeb FG |
1663 | if archive_name == ENCRYPTED_KEY_BLOB_NAME && crypt_config.is_none() { |
1664 | eprintln!("Restoring encrypted key blob without original key - skipping manifest fingerprint check!") | |
1665 | } else { | |
2f26b866 FG |
1666 | if manifest.signature.is_some() { |
1667 | if let Some(key) = &crypto.enc_key { | |
1668 | eprintln!("{}", format_key_source(&key.source, "encryption")); | |
1669 | } | |
1670 | if let Some(config) = &crypt_config { | |
1671 | eprintln!("Fingerprint: {}", config.fingerprint()); | |
1672 | } | |
1673 | } | |
48fbbfeb FG |
1674 | manifest.check_fingerprint(crypt_config.as_ref().map(Arc::as_ref))?; |
1675 | } | |
dc155e9b TL |
1676 | |
1677 | if archive_name == MANIFEST_BLOB_NAME { | |
02fcf372 | 1678 | if let Some(target) = target { |
2107a5ae | 1679 | replace_file(target, &backup_index_data, CreateOptions::new())?; |
02fcf372 DM |
1680 | } else { |
1681 | let stdout = std::io::stdout(); | |
1682 | let mut writer = stdout.lock(); | |
2107a5ae | 1683 | writer.write_all(&backup_index_data) |
02fcf372 DM |
1684 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1685 | } | |
1686 | ||
14f6c9cb FG |
1687 | return Ok(Value::Null); |
1688 | } | |
1689 | ||
1690 | let file_info = manifest.lookup_file_info(&archive_name)?; | |
1691 | ||
1692 | if archive_type == ArchiveType::Blob { | |
d2267b11 | 1693 | |
dc155e9b | 1694 | let mut reader = client.download_blob(&manifest, &archive_name).await?; |
f8100e96 | 1695 | |
bf125261 | 1696 | if let Some(target) = target { |
0d986280 DM |
1697 | let mut writer = std::fs::OpenOptions::new() |
1698 | .write(true) | |
1699 | .create(true) | |
1700 | .create_new(true) | |
1701 | .open(target) | |
1702 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?; | |
1703 | std::io::copy(&mut reader, &mut writer)?; | |
bf125261 DM |
1704 | } else { |
1705 | let stdout = std::io::stdout(); | |
1706 | let mut writer = stdout.lock(); | |
0d986280 | 1707 | std::io::copy(&mut reader, &mut writer) |
bf125261 DM |
1708 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1709 | } | |
f8100e96 | 1710 | |
dc155e9b | 1711 | } else if archive_type == ArchiveType::DynamicIndex { |
86eda3eb | 1712 | |
dc155e9b | 1713 | let index = client.download_dynamic_index(&manifest, &archive_name).await?; |
df65bd3d | 1714 | |
f4bf7dfc DM |
1715 | let most_used = index.find_most_used_chunks(8); |
1716 | ||
14f6c9cb | 1717 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, file_info.chunk_crypt_mode(), most_used); |
f4bf7dfc | 1718 | |
afb4cd28 | 1719 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); |
86eda3eb | 1720 | |
72064fd0 FG |
1721 | let options = proxmox_backup::pxar::PxarExtractOptions { |
1722 | match_list: &[], | |
1723 | extract_match_default: true, | |
1724 | allow_existing_dirs, | |
1725 | on_error: None, | |
1726 | }; | |
1727 | ||
bf125261 | 1728 | if let Some(target) = target { |
c443f58b WB |
1729 | proxmox_backup::pxar::extract_archive( |
1730 | pxar::decoder::Decoder::from_std(reader)?, | |
1731 | Path::new(target), | |
5444fa94 | 1732 | proxmox_backup::pxar::Flags::DEFAULT, |
c443f58b WB |
1733 | |path| { |
1734 | if verbose { | |
1735 | println!("{:?}", path); | |
1736 | } | |
1737 | }, | |
72064fd0 | 1738 | options, |
c443f58b WB |
1739 | ) |
1740 | .map_err(|err| format_err!("error extracting archive - {}", err))?; | |
bf125261 | 1741 | } else { |
88892ea8 DM |
1742 | let mut writer = std::fs::OpenOptions::new() |
1743 | .write(true) | |
1744 | .open("/dev/stdout") | |
1745 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?; | |
afb4cd28 | 1746 | |
bf125261 DM |
1747 | std::io::copy(&mut reader, &mut writer) |
1748 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
1749 | } | |
dc155e9b | 1750 | } else if archive_type == ArchiveType::FixedIndex { |
afb4cd28 | 1751 | |
dc155e9b | 1752 | let index = client.download_fixed_index(&manifest, &archive_name).await?; |
df65bd3d | 1753 | |
88892ea8 DM |
1754 | let mut writer = if let Some(target) = target { |
1755 | std::fs::OpenOptions::new() | |
bf125261 DM |
1756 | .write(true) |
1757 | .create(true) | |
1758 | .create_new(true) | |
1759 | .open(target) | |
88892ea8 | 1760 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))? |
bf125261 | 1761 | } else { |
88892ea8 DM |
1762 | std::fs::OpenOptions::new() |
1763 | .write(true) | |
1764 | .open("/dev/stdout") | |
1765 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))? | |
1766 | }; | |
afb4cd28 | 1767 | |
14f6c9cb | 1768 | dump_image(client.clone(), crypt_config.clone(), file_info.chunk_crypt_mode(), index, &mut writer, verbose).await?; |
3031e44c | 1769 | } |
fef44d4f DM |
1770 | |
1771 | Ok(Value::Null) | |
45db6f89 DM |
1772 | } |
1773 | ||
032d3ad8 DM |
1774 | const API_METHOD_PRUNE: ApiMethod = ApiMethod::new( |
1775 | &ApiHandler::Async(&prune), | |
1776 | &ObjectSchema::new( | |
1777 | "Prune a backup repository.", | |
1778 | &proxmox_backup::add_common_prune_prameters!([ | |
1779 | ("dry-run", true, &BooleanSchema::new( | |
1780 | "Just show what prune would do, but do not delete anything.") | |
1781 | .schema()), | |
1782 | ("group", false, &StringSchema::new("Backup group.").schema()), | |
1783 | ], [ | |
1784 | ("output-format", true, &OUTPUT_FORMAT), | |
c48aa39f DM |
1785 | ( |
1786 | "quiet", | |
1787 | true, | |
1788 | &BooleanSchema::new("Minimal output - only show removals.") | |
1789 | .schema() | |
1790 | ), | |
032d3ad8 DM |
1791 | ("repository", true, &REPO_URL_SCHEMA), |
1792 | ]) | |
1793 | ) | |
1794 | ); | |
1795 | ||
1796 | fn prune<'a>( | |
1797 | param: Value, | |
1798 | _info: &ApiMethod, | |
1799 | _rpcenv: &'a mut dyn RpcEnvironment, | |
1800 | ) -> proxmox::api::ApiFuture<'a> { | |
1801 | async move { | |
1802 | prune_async(param).await | |
1803 | }.boxed() | |
1804 | } | |
83b7db02 | 1805 | |
032d3ad8 | 1806 | async fn prune_async(mut param: Value) -> Result<Value, Error> { |
2665cef7 | 1807 | let repo = extract_repository_from_value(¶m)?; |
83b7db02 | 1808 | |
f3fde36b | 1809 | let mut client = connect(&repo)?; |
83b7db02 | 1810 | |
d0a03d40 | 1811 | let path = format!("api2/json/admin/datastore/{}/prune", repo.store()); |
83b7db02 | 1812 | |
9fdc3ef4 | 1813 | let group = tools::required_string_param(¶m, "group")?; |
d6d3b353 | 1814 | let group: BackupGroup = group.parse()?; |
c2043614 DM |
1815 | |
1816 | let output_format = get_output_format(¶m); | |
9fdc3ef4 | 1817 | |
c48aa39f DM |
1818 | let quiet = param["quiet"].as_bool().unwrap_or(false); |
1819 | ||
ea7a7ef2 DM |
1820 | param.as_object_mut().unwrap().remove("repository"); |
1821 | param.as_object_mut().unwrap().remove("group"); | |
163e9bbe | 1822 | param.as_object_mut().unwrap().remove("output-format"); |
c48aa39f | 1823 | param.as_object_mut().unwrap().remove("quiet"); |
ea7a7ef2 DM |
1824 | |
1825 | param["backup-type"] = group.backup_type().into(); | |
1826 | param["backup-id"] = group.backup_id().into(); | |
83b7db02 | 1827 | |
db1e061d | 1828 | let mut result = client.post(&path, Some(param)).await?; |
74fa81b8 | 1829 | |
87c42375 | 1830 | record_repository(&repo); |
3b03abfe | 1831 | |
db1e061d DM |
1832 | let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> { |
1833 | let item: PruneListItem = serde_json::from_value(record.to_owned())?; | |
e0e5b442 | 1834 | let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time)?; |
db1e061d DM |
1835 | Ok(snapshot.relative_path().to_str().unwrap().to_owned()) |
1836 | }; | |
1837 | ||
c48aa39f DM |
1838 | let render_prune_action = |v: &Value, _record: &Value| -> Result<String, Error> { |
1839 | Ok(match v.as_bool() { | |
1840 | Some(true) => "keep", | |
1841 | Some(false) => "remove", | |
1842 | None => "unknown", | |
1843 | }.to_string()) | |
1844 | }; | |
1845 | ||
db1e061d DM |
1846 | let options = default_table_format_options() |
1847 | .sortby("backup-type", false) | |
1848 | .sortby("backup-id", false) | |
1849 | .sortby("backup-time", false) | |
1850 | .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot")) | |
74f7240b | 1851 | .column(ColumnConfig::new("backup-time").renderer(tools::format::render_epoch).header("date")) |
c48aa39f | 1852 | .column(ColumnConfig::new("keep").renderer(render_prune_action).header("action")) |
db1e061d DM |
1853 | ; |
1854 | ||
b2362a12 | 1855 | let return_type = &proxmox_backup::api2::admin::datastore::API_METHOD_PRUNE.returns; |
db1e061d DM |
1856 | |
1857 | let mut data = result["data"].take(); | |
1858 | ||
c48aa39f DM |
1859 | if quiet { |
1860 | let list: Vec<Value> = data.as_array().unwrap().iter().filter(|item| { | |
1861 | item["keep"].as_bool() == Some(false) | |
a375df6f | 1862 | }).cloned().collect(); |
c48aa39f DM |
1863 | data = list.into(); |
1864 | } | |
1865 | ||
b2362a12 | 1866 | format_and_print_result_full(&mut data, return_type, &output_format, &options); |
d0a03d40 | 1867 | |
43a406fd | 1868 | Ok(Value::Null) |
83b7db02 DM |
1869 | } |
1870 | ||
a47a02ae DM |
1871 | #[api( |
1872 | input: { | |
1873 | properties: { | |
1874 | repository: { | |
1875 | schema: REPO_URL_SCHEMA, | |
1876 | optional: true, | |
1877 | }, | |
1878 | "output-format": { | |
1879 | schema: OUTPUT_FORMAT, | |
1880 | optional: true, | |
1881 | }, | |
1882 | } | |
f9beae9c TL |
1883 | }, |
1884 | returns: { | |
1885 | type: StorageStatus, | |
1886 | }, | |
a47a02ae DM |
1887 | )] |
1888 | /// Get repository status. | |
1889 | async fn status(param: Value) -> Result<Value, Error> { | |
34a816cc DM |
1890 | |
1891 | let repo = extract_repository_from_value(¶m)?; | |
1892 | ||
c2043614 | 1893 | let output_format = get_output_format(¶m); |
34a816cc | 1894 | |
f3fde36b | 1895 | let client = connect(&repo)?; |
34a816cc DM |
1896 | |
1897 | let path = format!("api2/json/admin/datastore/{}/status", repo.store()); | |
1898 | ||
1dc117bb | 1899 | let mut result = client.get(&path, None).await?; |
14e08625 | 1900 | let mut data = result["data"].take(); |
34a816cc DM |
1901 | |
1902 | record_repository(&repo); | |
1903 | ||
390c5bdd DM |
1904 | let render_total_percentage = |v: &Value, record: &Value| -> Result<String, Error> { |
1905 | let v = v.as_u64().unwrap(); | |
1906 | let total = record["total"].as_u64().unwrap(); | |
1907 | let roundup = total/200; | |
1908 | let per = ((v+roundup)*100)/total; | |
e23f5863 DM |
1909 | let info = format!(" ({} %)", per); |
1910 | Ok(format!("{} {:>8}", v, info)) | |
390c5bdd | 1911 | }; |
1dc117bb | 1912 | |
c2043614 | 1913 | let options = default_table_format_options() |
be2425ff | 1914 | .noheader(true) |
e23f5863 | 1915 | .column(ColumnConfig::new("total").renderer(render_total_percentage)) |
390c5bdd DM |
1916 | .column(ColumnConfig::new("used").renderer(render_total_percentage)) |
1917 | .column(ColumnConfig::new("avail").renderer(render_total_percentage)); | |
34a816cc | 1918 | |
b2362a12 | 1919 | let return_type = &API_METHOD_STATUS.returns; |
390c5bdd | 1920 | |
b2362a12 | 1921 | format_and_print_result_full(&mut data, return_type, &output_format, &options); |
34a816cc DM |
1922 | |
1923 | Ok(Value::Null) | |
1924 | } | |
1925 | ||
5a2df000 | 1926 | // like get, but simply ignore errors and return Null instead |
e9722f8b | 1927 | async fn try_get(repo: &BackupRepository, url: &str) -> Value { |
024f11bb | 1928 | |
a05c0c6f | 1929 | let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok(); |
d1c65727 | 1930 | let password = std::env::var(ENV_VAR_PBS_PASSWORD).ok(); |
a05c0c6f | 1931 | |
93e3581c FG |
1932 | // ticket cache, but no questions asked |
1933 | let options = HttpClientOptions::new_interactive(password, fingerprint) | |
1934 | .interactive(false); | |
d59dbeca | 1935 | |
34aa8e13 | 1936 | let client = match HttpClient::new(repo.host(), repo.port(), repo.auth_id(), options) { |
45cdce06 DM |
1937 | Ok(v) => v, |
1938 | _ => return Value::Null, | |
1939 | }; | |
b2388518 | 1940 | |
e9722f8b | 1941 | let mut resp = match client.get(url, None).await { |
b2388518 DM |
1942 | Ok(v) => v, |
1943 | _ => return Value::Null, | |
1944 | }; | |
1945 | ||
1946 | if let Some(map) = resp.as_object_mut() { | |
1947 | if let Some(data) = map.remove("data") { | |
1948 | return data; | |
1949 | } | |
1950 | } | |
1951 | Value::Null | |
1952 | } | |
1953 | ||
b2388518 | 1954 | fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
3f06d6fb | 1955 | proxmox_backup::tools::runtime::main(async { complete_backup_group_do(param).await }) |
e9722f8b WB |
1956 | } |
1957 | ||
1958 | async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> { | |
024f11bb | 1959 | |
b2388518 DM |
1960 | let mut result = vec![]; |
1961 | ||
2665cef7 | 1962 | let repo = match extract_repository_from_map(param) { |
b2388518 | 1963 | Some(v) => v, |
024f11bb DM |
1964 | _ => return result, |
1965 | }; | |
1966 | ||
b2388518 DM |
1967 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
1968 | ||
e9722f8b | 1969 | let data = try_get(&repo, &path).await; |
b2388518 DM |
1970 | |
1971 | if let Some(list) = data.as_array() { | |
024f11bb | 1972 | for item in list { |
98f0b972 DM |
1973 | if let (Some(backup_id), Some(backup_type)) = |
1974 | (item["backup-id"].as_str(), item["backup-type"].as_str()) | |
1975 | { | |
1976 | result.push(format!("{}/{}", backup_type, backup_id)); | |
024f11bb DM |
1977 | } |
1978 | } | |
1979 | } | |
1980 | ||
1981 | result | |
1982 | } | |
1983 | ||
43abba4b | 1984 | pub fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
3f06d6fb | 1985 | proxmox_backup::tools::runtime::main(async { complete_group_or_snapshot_do(arg, param).await }) |
e9722f8b WB |
1986 | } |
1987 | ||
1988 | async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
b2388518 | 1989 | |
b2388518 | 1990 | if arg.matches('/').count() < 2 { |
e9722f8b | 1991 | let groups = complete_backup_group_do(param).await; |
543a260f | 1992 | let mut result = vec![]; |
b2388518 DM |
1993 | for group in groups { |
1994 | result.push(group.to_string()); | |
1995 | result.push(format!("{}/", group)); | |
1996 | } | |
1997 | return result; | |
1998 | } | |
1999 | ||
e9722f8b | 2000 | complete_backup_snapshot_do(param).await |
543a260f | 2001 | } |
b2388518 | 2002 | |
3fb53e07 | 2003 | fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
3f06d6fb | 2004 | proxmox_backup::tools::runtime::main(async { complete_backup_snapshot_do(param).await }) |
e9722f8b WB |
2005 | } |
2006 | ||
2007 | async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> { | |
543a260f DM |
2008 | |
2009 | let mut result = vec![]; | |
2010 | ||
2011 | let repo = match extract_repository_from_map(param) { | |
2012 | Some(v) => v, | |
2013 | _ => return result, | |
2014 | }; | |
2015 | ||
2016 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); | |
b2388518 | 2017 | |
e9722f8b | 2018 | let data = try_get(&repo, &path).await; |
b2388518 DM |
2019 | |
2020 | if let Some(list) = data.as_array() { | |
2021 | for item in list { | |
2022 | if let (Some(backup_id), Some(backup_type), Some(backup_time)) = | |
2023 | (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64()) | |
2024 | { | |
e0e5b442 FG |
2025 | if let Ok(snapshot) = BackupDir::new(backup_type, backup_id, backup_time) { |
2026 | result.push(snapshot.relative_path().to_str().unwrap().to_owned()); | |
2027 | } | |
b2388518 DM |
2028 | } |
2029 | } | |
2030 | } | |
2031 | ||
2032 | result | |
2033 | } | |
2034 | ||
45db6f89 | 2035 | fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
3f06d6fb | 2036 | proxmox_backup::tools::runtime::main(async { complete_server_file_name_do(param).await }) |
e9722f8b WB |
2037 | } |
2038 | ||
2039 | async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> { | |
08dc340a DM |
2040 | |
2041 | let mut result = vec![]; | |
2042 | ||
2665cef7 | 2043 | let repo = match extract_repository_from_map(param) { |
08dc340a DM |
2044 | Some(v) => v, |
2045 | _ => return result, | |
2046 | }; | |
2047 | ||
a67f7d0a | 2048 | let snapshot: BackupDir = match param.get("snapshot") { |
08dc340a | 2049 | Some(path) => { |
a67f7d0a | 2050 | match path.parse() { |
08dc340a DM |
2051 | Ok(v) => v, |
2052 | _ => return result, | |
2053 | } | |
2054 | } | |
2055 | _ => return result, | |
2056 | }; | |
2057 | ||
2058 | let query = tools::json_object_to_query(json!({ | |
2059 | "backup-type": snapshot.group().backup_type(), | |
2060 | "backup-id": snapshot.group().backup_id(), | |
6a7be83e | 2061 | "backup-time": snapshot.backup_time(), |
08dc340a DM |
2062 | })).unwrap(); |
2063 | ||
2064 | let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query); | |
2065 | ||
e9722f8b | 2066 | let data = try_get(&repo, &path).await; |
08dc340a DM |
2067 | |
2068 | if let Some(list) = data.as_array() { | |
2069 | for item in list { | |
c4f025eb | 2070 | if let Some(filename) = item["filename"].as_str() { |
08dc340a DM |
2071 | result.push(filename.to_owned()); |
2072 | } | |
2073 | } | |
2074 | } | |
2075 | ||
45db6f89 DM |
2076 | result |
2077 | } | |
2078 | ||
2079 | fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
52c171e4 | 2080 | complete_server_file_name(arg, param) |
e9722f8b | 2081 | .iter() |
708fab30 | 2082 | .map(|v| tools::format::strip_server_file_extension(&v)) |
e9722f8b | 2083 | .collect() |
08dc340a DM |
2084 | } |
2085 | ||
43abba4b | 2086 | pub fn complete_pxar_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
0ec9e1b0 DM |
2087 | complete_server_file_name(arg, param) |
2088 | .iter() | |
2995aedf DM |
2089 | .filter_map(|name| { |
2090 | if name.ends_with(".pxar.didx") { | |
708fab30 | 2091 | Some(tools::format::strip_server_file_extension(name)) |
2995aedf DM |
2092 | } else { |
2093 | None | |
2094 | } | |
2095 | }) | |
2096 | .collect() | |
2097 | } | |
2098 | ||
2099 | pub fn complete_img_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
2100 | complete_server_file_name(arg, param) | |
2101 | .iter() | |
2102 | .filter_map(|name| { | |
2103 | if name.ends_with(".img.fidx") { | |
708fab30 | 2104 | Some(tools::format::strip_server_file_extension(name)) |
0ec9e1b0 DM |
2105 | } else { |
2106 | None | |
2107 | } | |
2108 | }) | |
2109 | .collect() | |
2110 | } | |
2111 | ||
49811347 DM |
2112 | fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
2113 | ||
2114 | let mut result = vec![]; | |
2115 | ||
2116 | let mut size = 64; | |
2117 | loop { | |
2118 | result.push(size.to_string()); | |
11377a47 | 2119 | size *= 2; |
49811347 DM |
2120 | if size > 4096 { break; } |
2121 | } | |
2122 | ||
2123 | result | |
2124 | } | |
2125 | ||
0224c3c2 FG |
2126 | fn complete_auth_id(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
2127 | proxmox_backup::tools::runtime::main(async { complete_auth_id_do(param).await }) | |
2128 | } | |
2129 | ||
2130 | async fn complete_auth_id_do(param: &HashMap<String, String>) -> Vec<String> { | |
2131 | ||
2132 | let mut result = vec![]; | |
2133 | ||
2134 | let repo = match extract_repository_from_map(param) { | |
2135 | Some(v) => v, | |
2136 | _ => return result, | |
2137 | }; | |
2138 | ||
2139 | let data = try_get(&repo, "api2/json/access/users?include_tokens=true").await; | |
2140 | ||
2141 | if let Ok(parsed) = serde_json::from_value::<Vec<UserWithTokens>>(data) { | |
2142 | for user in parsed { | |
2143 | result.push(user.userid.to_string()); | |
2144 | for token in user.tokens { | |
2145 | result.push(token.tokenid.to_string()); | |
2146 | } | |
2147 | } | |
2148 | }; | |
2149 | ||
2150 | result | |
2151 | } | |
2152 | ||
c443f58b WB |
2153 | use proxmox_backup::client::RemoteChunkReader; |
2154 | /// This is a workaround until we have cleaned up the chunk/reader/... infrastructure for better | |
2155 | /// async use! | |
2156 | /// | |
2157 | /// Ideally BufferedDynamicReader gets replaced so the LruCache maps to `BroadcastFuture<Chunk>`, | |
2158 | /// so that we can properly access it from multiple threads simultaneously while not issuing | |
2159 | /// duplicate simultaneous reads over http. | |
43abba4b | 2160 | pub struct BufferedDynamicReadAt { |
c443f58b WB |
2161 | inner: Mutex<BufferedDynamicReader<RemoteChunkReader>>, |
2162 | } | |
2163 | ||
2164 | impl BufferedDynamicReadAt { | |
2165 | fn new(inner: BufferedDynamicReader<RemoteChunkReader>) -> Self { | |
2166 | Self { | |
2167 | inner: Mutex::new(inner), | |
2168 | } | |
2169 | } | |
2170 | } | |
2171 | ||
a6f87283 WB |
2172 | impl ReadAt for BufferedDynamicReadAt { |
2173 | fn start_read_at<'a>( | |
2174 | self: Pin<&'a Self>, | |
c443f58b | 2175 | _cx: &mut Context, |
a6f87283 | 2176 | buf: &'a mut [u8], |
c443f58b | 2177 | offset: u64, |
a6f87283 | 2178 | ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> { |
a6f87283 | 2179 | MaybeReady::Ready(tokio::task::block_in_place(move || { |
c443f58b WB |
2180 | let mut reader = self.inner.lock().unwrap(); |
2181 | reader.seek(SeekFrom::Start(offset))?; | |
a6f87283 WB |
2182 | Ok(reader.read(buf)?) |
2183 | })) | |
2184 | } | |
2185 | ||
2186 | fn poll_complete<'a>( | |
2187 | self: Pin<&'a Self>, | |
2188 | _op: ReadAtOperation<'a>, | |
2189 | ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> { | |
2190 | panic!("LocalDynamicReadAt::start_read_at returned Pending"); | |
c443f58b WB |
2191 | } |
2192 | } | |
2193 | ||
f2401311 | 2194 | fn main() { |
33d64b81 | 2195 | |
255f378a | 2196 | let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP) |
49fddd98 | 2197 | .arg_param(&["backupspec"]) |
d0a03d40 | 2198 | .completion_cb("repository", complete_repository) |
49811347 | 2199 | .completion_cb("backupspec", complete_backup_source) |
6d0983db | 2200 | .completion_cb("keyfile", tools::complete_file_name) |
c0a87c12 | 2201 | .completion_cb("master-pubkey-file", tools::complete_file_name) |
49811347 | 2202 | .completion_cb("chunk-size", complete_chunk_size); |
f8838fe9 | 2203 | |
caea8d61 DM |
2204 | let benchmark_cmd_def = CliCommand::new(&API_METHOD_BENCHMARK) |
2205 | .completion_cb("repository", complete_repository) | |
2206 | .completion_cb("keyfile", tools::complete_file_name); | |
2207 | ||
255f378a | 2208 | let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS) |
d0a03d40 | 2209 | .completion_cb("repository", complete_repository); |
41c039e1 | 2210 | |
255f378a | 2211 | let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION) |
d0a03d40 | 2212 | .completion_cb("repository", complete_repository); |
8cc0d6af | 2213 | |
255f378a | 2214 | let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE) |
49fddd98 | 2215 | .arg_param(&["snapshot", "archive-name", "target"]) |
b2388518 | 2216 | .completion_cb("repository", complete_repository) |
08dc340a DM |
2217 | .completion_cb("snapshot", complete_group_or_snapshot) |
2218 | .completion_cb("archive-name", complete_archive_name) | |
2219 | .completion_cb("target", tools::complete_file_name); | |
9f912493 | 2220 | |
255f378a | 2221 | let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE) |
49fddd98 | 2222 | .arg_param(&["group"]) |
9fdc3ef4 | 2223 | .completion_cb("group", complete_backup_group) |
d0a03d40 | 2224 | .completion_cb("repository", complete_repository); |
9f912493 | 2225 | |
255f378a | 2226 | let status_cmd_def = CliCommand::new(&API_METHOD_STATUS) |
34a816cc DM |
2227 | .completion_cb("repository", complete_repository); |
2228 | ||
255f378a | 2229 | let login_cmd_def = CliCommand::new(&API_METHOD_API_LOGIN) |
e240d8be DM |
2230 | .completion_cb("repository", complete_repository); |
2231 | ||
255f378a | 2232 | let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT) |
e240d8be | 2233 | .completion_cb("repository", complete_repository); |
32efac1c | 2234 | |
e39974af TL |
2235 | let version_cmd_def = CliCommand::new(&API_METHOD_API_VERSION) |
2236 | .completion_cb("repository", complete_repository); | |
2237 | ||
344add38 DW |
2238 | let change_owner_cmd_def = CliCommand::new(&API_METHOD_CHANGE_BACKUP_OWNER) |
2239 | .arg_param(&["group", "new-owner"]) | |
2240 | .completion_cb("group", complete_backup_group) | |
0224c3c2 | 2241 | .completion_cb("new-owner", complete_auth_id) |
344add38 DW |
2242 | .completion_cb("repository", complete_repository); |
2243 | ||
41c039e1 | 2244 | let cmd_def = CliCommandMap::new() |
48ef3c33 | 2245 | .insert("backup", backup_cmd_def) |
48ef3c33 DM |
2246 | .insert("garbage-collect", garbage_collect_cmd_def) |
2247 | .insert("list", list_cmd_def) | |
2248 | .insert("login", login_cmd_def) | |
2249 | .insert("logout", logout_cmd_def) | |
2250 | .insert("prune", prune_cmd_def) | |
2251 | .insert("restore", restore_cmd_def) | |
a65e3e4b | 2252 | .insert("snapshot", snapshot_mgtm_cli()) |
48ef3c33 | 2253 | .insert("status", status_cmd_def) |
9696f519 | 2254 | .insert("key", key::cli()) |
43abba4b | 2255 | .insert("mount", mount_cmd_def()) |
45f9b32e SR |
2256 | .insert("map", map_cmd_def()) |
2257 | .insert("unmap", unmap_cmd_def()) | |
5830c205 | 2258 | .insert("catalog", catalog_mgmt_cli()) |
caea8d61 | 2259 | .insert("task", task_mgmt_cli()) |
e39974af | 2260 | .insert("version", version_cmd_def) |
344add38 | 2261 | .insert("benchmark", benchmark_cmd_def) |
731eeef2 DM |
2262 | .insert("change-owner", change_owner_cmd_def) |
2263 | ||
61205f00 | 2264 | .alias(&["files"], &["snapshot", "files"]) |
edebd523 | 2265 | .alias(&["forget"], &["snapshot", "forget"]) |
0c9209b0 | 2266 | .alias(&["upload-log"], &["snapshot", "upload-log"]) |
731eeef2 DM |
2267 | .alias(&["snapshots"], &["snapshot", "list"]) |
2268 | ; | |
48ef3c33 | 2269 | |
7b22acd0 DM |
2270 | let rpcenv = CliEnvironment::new(); |
2271 | run_cli_command(cmd_def, rpcenv, Some(|future| { | |
d08bc483 DM |
2272 | proxmox_backup::tools::runtime::main(future) |
2273 | })); | |
ff5d3707 | 2274 | } |