]>
Commit | Line | Data |
---|---|---|
ff5d3707 | 1 | use failure::*; |
70235f72 CE |
2 | use nix::unistd::{fork, ForkResult, pipe}; |
3 | use std::os::unix::io::RawFd; | |
fa5d6977 | 4 | use chrono::{Local, Utc, TimeZone}; |
e9c9409a | 5 | use std::path::{Path, PathBuf}; |
2eeaacb9 | 6 | use std::collections::{HashSet, HashMap}; |
70235f72 | 7 | use std::ffi::OsStr; |
bb19af73 | 8 | use std::io::{Write, Seek, SeekFrom}; |
2761d6a4 DM |
9 | use std::os::unix::fs::OpenOptionsExt; |
10 | ||
552c2259 | 11 | use proxmox::{sortable, identity}; |
feaa1ad3 | 12 | use proxmox::tools::fs::{file_get_contents, file_get_json, replace_file, CreateOptions, image_size}; |
a47a02ae | 13 | use proxmox::api::{ApiHandler, ApiMethod, RpcEnvironment}; |
3d482025 | 14 | use proxmox::api::schema::*; |
7eea56ca | 15 | use proxmox::api::cli::*; |
5830c205 | 16 | use proxmox::api::api; |
ff5d3707 | 17 | |
fe0e04c6 | 18 | use proxmox_backup::tools; |
bbf9e7e9 | 19 | use proxmox_backup::api2::types::*; |
151c6ce2 | 20 | use proxmox_backup::client::*; |
247cdbce | 21 | use proxmox_backup::backup::*; |
7926a3a1 | 22 | use proxmox_backup::pxar::{ self, catalog::* }; |
86eda3eb | 23 | |
fe0e04c6 DM |
24 | //use proxmox_backup::backup::image_index::*; |
25 | //use proxmox_backup::config::datastore; | |
8968258b | 26 | //use proxmox_backup::pxar::encoder::*; |
728797d0 | 27 | //use proxmox_backup::backup::datastore::*; |
23bb8780 | 28 | |
f5f13ebc | 29 | use serde_json::{json, Value}; |
1c0472e8 | 30 | //use hyper::Body; |
2761d6a4 | 31 | use std::sync::{Arc, Mutex}; |
255f378a | 32 | //use regex::Regex; |
d0a03d40 | 33 | use xdg::BaseDirectories; |
ae0be2dd | 34 | |
5a2df000 | 35 | use futures::*; |
c4ff3dce | 36 | use tokio::sync::mpsc; |
ae0be2dd | 37 | |
3d482025 | 38 | proxmox::api::const_regex! { |
255f378a | 39 | BACKUPSPEC_REGEX = r"^([a-zA-Z0-9_-]+\.(?:pxar|img|conf|log)):(.+)$"; |
ae0be2dd | 40 | } |
33d64b81 | 41 | |
255f378a DM |
42 | const REPO_URL_SCHEMA: Schema = StringSchema::new("Repository URL.") |
43 | .format(&BACKUP_REPO_URL) | |
44 | .max_length(256) | |
45 | .schema(); | |
d0a03d40 | 46 | |
a47a02ae DM |
47 | const BACKUP_SOURCE_SCHEMA: Schema = StringSchema::new( |
48 | "Backup source specification ([<label>:<path>]).") | |
49 | .format(&ApiStringFormat::Pattern(&BACKUPSPEC_REGEX)) | |
50 | .schema(); | |
51 | ||
52 | const KEYFILE_SCHEMA: Schema = StringSchema::new( | |
53 | "Path to encryption key. All data will be encrypted using this key.") | |
54 | .schema(); | |
55 | ||
56 | const CHUNK_SIZE_SCHEMA: Schema = IntegerSchema::new( | |
57 | "Chunk size in KB. Must be a power of 2.") | |
58 | .minimum(64) | |
59 | .maximum(4096) | |
60 | .default(4096) | |
61 | .schema(); | |
62 | ||
2665cef7 DM |
63 | fn get_default_repository() -> Option<String> { |
64 | std::env::var("PBS_REPOSITORY").ok() | |
65 | } | |
66 | ||
67 | fn extract_repository_from_value( | |
68 | param: &Value, | |
69 | ) -> Result<BackupRepository, Error> { | |
70 | ||
71 | let repo_url = param["repository"] | |
72 | .as_str() | |
73 | .map(String::from) | |
74 | .or_else(get_default_repository) | |
75 | .ok_or_else(|| format_err!("unable to get (default) repository"))?; | |
76 | ||
77 | let repo: BackupRepository = repo_url.parse()?; | |
78 | ||
79 | Ok(repo) | |
80 | } | |
81 | ||
82 | fn extract_repository_from_map( | |
83 | param: &HashMap<String, String>, | |
84 | ) -> Option<BackupRepository> { | |
85 | ||
86 | param.get("repository") | |
87 | .map(String::from) | |
88 | .or_else(get_default_repository) | |
89 | .and_then(|repo_url| repo_url.parse::<BackupRepository>().ok()) | |
90 | } | |
91 | ||
d0a03d40 DM |
92 | fn record_repository(repo: &BackupRepository) { |
93 | ||
94 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
95 | Ok(v) => v, | |
96 | _ => return, | |
97 | }; | |
98 | ||
99 | // usually $HOME/.cache/proxmox-backup/repo-list | |
100 | let path = match base.place_cache_file("repo-list") { | |
101 | Ok(v) => v, | |
102 | _ => return, | |
103 | }; | |
104 | ||
11377a47 | 105 | let mut data = file_get_json(&path, None).unwrap_or_else(|_| json!({})); |
d0a03d40 DM |
106 | |
107 | let repo = repo.to_string(); | |
108 | ||
109 | data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 }; | |
110 | ||
111 | let mut map = serde_json::map::Map::new(); | |
112 | ||
113 | loop { | |
114 | let mut max_used = 0; | |
115 | let mut max_repo = None; | |
116 | for (repo, count) in data.as_object().unwrap() { | |
117 | if map.contains_key(repo) { continue; } | |
118 | if let Some(count) = count.as_i64() { | |
119 | if count > max_used { | |
120 | max_used = count; | |
121 | max_repo = Some(repo); | |
122 | } | |
123 | } | |
124 | } | |
125 | if let Some(repo) = max_repo { | |
126 | map.insert(repo.to_owned(), json!(max_used)); | |
127 | } else { | |
128 | break; | |
129 | } | |
130 | if map.len() > 10 { // store max. 10 repos | |
131 | break; | |
132 | } | |
133 | } | |
134 | ||
135 | let new_data = json!(map); | |
136 | ||
feaa1ad3 | 137 | let _ = replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new()); |
d0a03d40 DM |
138 | } |
139 | ||
49811347 | 140 | fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
d0a03d40 DM |
141 | |
142 | let mut result = vec![]; | |
143 | ||
144 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
145 | Ok(v) => v, | |
146 | _ => return result, | |
147 | }; | |
148 | ||
149 | // usually $HOME/.cache/proxmox-backup/repo-list | |
150 | let path = match base.place_cache_file("repo-list") { | |
151 | Ok(v) => v, | |
152 | _ => return result, | |
153 | }; | |
154 | ||
11377a47 | 155 | let data = file_get_json(&path, None).unwrap_or_else(|_| json!({})); |
d0a03d40 DM |
156 | |
157 | if let Some(map) = data.as_object() { | |
49811347 | 158 | for (repo, _count) in map { |
d0a03d40 DM |
159 | result.push(repo.to_owned()); |
160 | } | |
161 | } | |
162 | ||
163 | result | |
164 | } | |
165 | ||
d105176f DM |
166 | async fn view_task_result( |
167 | client: HttpClient, | |
168 | result: Value, | |
169 | output_format: &str, | |
170 | ) -> Result<(), Error> { | |
171 | let data = &result["data"]; | |
172 | if output_format == "text" { | |
173 | if let Some(upid) = data.as_str() { | |
174 | display_task_log(client, upid, true).await?; | |
175 | } | |
176 | } else { | |
177 | format_and_print_result(&data, &output_format); | |
178 | } | |
179 | ||
180 | Ok(()) | |
181 | } | |
182 | ||
e9722f8b | 183 | async fn backup_directory<P: AsRef<Path>>( |
cf9271e2 | 184 | client: &BackupWriter, |
17d6979a | 185 | dir_path: P, |
247cdbce | 186 | archive_name: &str, |
36898ffc | 187 | chunk_size: Option<usize>, |
2eeaacb9 | 188 | device_set: Option<HashSet<u64>>, |
219ef0e6 | 189 | verbose: bool, |
5b72c9b4 | 190 | skip_lost_and_found: bool, |
f98ac774 | 191 | crypt_config: Option<Arc<CryptConfig>>, |
bf6e3217 | 192 | catalog: Arc<Mutex<CatalogWriter<SenderWriter>>>, |
2c3891d1 | 193 | ) -> Result<BackupStats, Error> { |
33d64b81 | 194 | |
2761d6a4 | 195 | let pxar_stream = PxarBackupStream::open(dir_path.as_ref(), device_set, verbose, skip_lost_and_found, catalog)?; |
e9722f8b | 196 | let mut chunk_stream = ChunkStream::new(pxar_stream, chunk_size); |
ff3d3100 | 197 | |
e9722f8b | 198 | let (mut tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks |
5e7a09be | 199 | |
c4ff3dce | 200 | let stream = rx |
e9722f8b | 201 | .map_err(Error::from); |
17d6979a | 202 | |
c4ff3dce | 203 | // spawn chunker inside a separate task so that it can run parallel |
e9722f8b | 204 | tokio::spawn(async move { |
db0cb9ce WB |
205 | while let Some(v) = chunk_stream.next().await { |
206 | let _ = tx.send(v).await; | |
207 | } | |
e9722f8b | 208 | }); |
17d6979a | 209 | |
e9722f8b WB |
210 | let stats = client |
211 | .upload_stream(archive_name, stream, "dynamic", None, crypt_config) | |
212 | .await?; | |
bcd879cf | 213 | |
2c3891d1 | 214 | Ok(stats) |
bcd879cf DM |
215 | } |
216 | ||
e9722f8b | 217 | async fn backup_image<P: AsRef<Path>>( |
cf9271e2 | 218 | client: &BackupWriter, |
6af905c1 DM |
219 | image_path: P, |
220 | archive_name: &str, | |
221 | image_size: u64, | |
36898ffc | 222 | chunk_size: Option<usize>, |
1c0472e8 | 223 | _verbose: bool, |
f98ac774 | 224 | crypt_config: Option<Arc<CryptConfig>>, |
2c3891d1 | 225 | ) -> Result<BackupStats, Error> { |
6af905c1 | 226 | |
6af905c1 DM |
227 | let path = image_path.as_ref().to_owned(); |
228 | ||
e9722f8b | 229 | let file = tokio::fs::File::open(path).await?; |
6af905c1 | 230 | |
db0cb9ce | 231 | let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new()) |
6af905c1 DM |
232 | .map_err(Error::from); |
233 | ||
36898ffc | 234 | let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024)); |
6af905c1 | 235 | |
e9722f8b WB |
236 | let stats = client |
237 | .upload_stream(archive_name, stream, "fixed", Some(image_size), crypt_config) | |
238 | .await?; | |
6af905c1 | 239 | |
2c3891d1 | 240 | Ok(stats) |
6af905c1 DM |
241 | } |
242 | ||
52c171e4 DM |
243 | fn strip_server_file_expenstion(name: &str) -> String { |
244 | ||
11377a47 DM |
245 | if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") { |
246 | name[..name.len()-5].to_owned() | |
52c171e4 | 247 | } else { |
11377a47 | 248 | name.to_owned() // should not happen |
8e39232a | 249 | } |
8e39232a DM |
250 | } |
251 | ||
a47a02ae DM |
252 | #[api( |
253 | input: { | |
254 | properties: { | |
255 | repository: { | |
256 | schema: REPO_URL_SCHEMA, | |
257 | optional: true, | |
258 | }, | |
259 | "output-format": { | |
260 | schema: OUTPUT_FORMAT, | |
261 | optional: true, | |
262 | }, | |
263 | } | |
264 | } | |
265 | )] | |
266 | /// List backup groups. | |
267 | async fn list_backup_groups(param: Value) -> Result<Value, Error> { | |
812c6f87 | 268 | |
2665cef7 | 269 | let repo = extract_repository_from_value(¶m)?; |
812c6f87 | 270 | |
cc2ce4a9 | 271 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
812c6f87 | 272 | |
d0a03d40 | 273 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
812c6f87 | 274 | |
8a8a4703 | 275 | let mut result = client.get(&path, None).await?; |
812c6f87 | 276 | |
d0a03d40 DM |
277 | record_repository(&repo); |
278 | ||
812c6f87 | 279 | // fixme: implement and use output formatter instead .. |
80822b95 DM |
280 | let list = result["data"].as_array_mut().unwrap(); |
281 | ||
282 | list.sort_unstable_by(|a, b| { | |
283 | let a_id = a["backup-id"].as_str().unwrap(); | |
284 | let a_backup_type = a["backup-type"].as_str().unwrap(); | |
285 | let b_id = b["backup-id"].as_str().unwrap(); | |
286 | let b_backup_type = b["backup-type"].as_str().unwrap(); | |
287 | ||
288 | let type_order = a_backup_type.cmp(b_backup_type); | |
289 | if type_order == std::cmp::Ordering::Equal { | |
290 | a_id.cmp(b_id) | |
291 | } else { | |
292 | type_order | |
293 | } | |
294 | }); | |
812c6f87 | 295 | |
34a816cc DM |
296 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); |
297 | ||
298 | let mut result = vec![]; | |
299 | ||
812c6f87 DM |
300 | for item in list { |
301 | ||
ad20d198 DM |
302 | let id = item["backup-id"].as_str().unwrap(); |
303 | let btype = item["backup-type"].as_str().unwrap(); | |
304 | let epoch = item["last-backup"].as_i64().unwrap(); | |
fa5d6977 | 305 | let last_backup = Utc.timestamp(epoch, 0); |
ad20d198 | 306 | let backup_count = item["backup-count"].as_u64().unwrap(); |
812c6f87 | 307 | |
1e9a94e5 | 308 | let group = BackupGroup::new(btype, id); |
812c6f87 DM |
309 | |
310 | let path = group.group_path().to_str().unwrap().to_owned(); | |
ad20d198 | 311 | |
52c171e4 DM |
312 | let files = item["files"].as_array().unwrap().iter() |
313 | .map(|v| strip_server_file_expenstion(v.as_str().unwrap())).collect(); | |
ad20d198 | 314 | |
34a816cc | 315 | if output_format == "text" { |
fa5d6977 DM |
316 | println!( |
317 | "{:20} | {} | {:5} | {}", | |
318 | path, | |
319 | BackupDir::backup_time_to_string(last_backup), | |
320 | backup_count, | |
321 | tools::join(&files, ' '), | |
322 | ); | |
34a816cc DM |
323 | } else { |
324 | result.push(json!({ | |
325 | "backup-type": btype, | |
326 | "backup-id": id, | |
327 | "last-backup": epoch, | |
328 | "backup-count": backup_count, | |
329 | "files": files, | |
330 | })); | |
331 | } | |
812c6f87 DM |
332 | } |
333 | ||
9aa3f682 | 334 | if output_format != "text" { format_and_print_result(&result.into(), &output_format); } |
34a816cc | 335 | |
812c6f87 DM |
336 | Ok(Value::Null) |
337 | } | |
338 | ||
a47a02ae DM |
339 | #[api( |
340 | input: { | |
341 | properties: { | |
342 | repository: { | |
343 | schema: REPO_URL_SCHEMA, | |
344 | optional: true, | |
345 | }, | |
346 | group: { | |
347 | type: String, | |
348 | description: "Backup group.", | |
349 | optional: true, | |
350 | }, | |
351 | "output-format": { | |
352 | schema: OUTPUT_FORMAT, | |
353 | optional: true, | |
354 | }, | |
355 | } | |
356 | } | |
357 | )] | |
358 | /// List backup snapshots. | |
359 | async fn list_snapshots(param: Value) -> Result<Value, Error> { | |
184f17af | 360 | |
2665cef7 | 361 | let repo = extract_repository_from_value(¶m)?; |
184f17af | 362 | |
34a816cc DM |
363 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); |
364 | ||
cc2ce4a9 | 365 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
184f17af | 366 | |
9e391bb7 | 367 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
184f17af | 368 | |
15c847f1 DM |
369 | let mut args = json!({}); |
370 | if let Some(path) = param["group"].as_str() { | |
371 | let group = BackupGroup::parse(path)?; | |
372 | args["backup-type"] = group.backup_type().into(); | |
373 | args["backup-id"] = group.backup_id().into(); | |
374 | } | |
375 | ||
af9d4afc | 376 | let mut result = client.get(&path, Some(args)).await?; |
184f17af | 377 | |
d0a03d40 DM |
378 | record_repository(&repo); |
379 | ||
af9d4afc DM |
380 | if output_format != "text" { |
381 | format_and_print_result(&result["data"], &output_format); | |
382 | return Ok(Value::Null); | |
383 | } | |
184f17af | 384 | |
af9d4afc DM |
385 | let mut list: Vec<SnapshotListItem> = serde_json::from_value(result["data"].take())?; |
386 | list.sort_unstable_by(|a, b| a.backup_time.cmp(&b.backup_time)); | |
34a816cc | 387 | |
184f17af DM |
388 | for item in list { |
389 | ||
af9d4afc | 390 | let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time); |
184f17af DM |
391 | |
392 | let path = snapshot.relative_path().to_str().unwrap().to_owned(); | |
393 | ||
af9d4afc DM |
394 | let files = item.files.iter() |
395 | .map(|v| strip_server_file_expenstion(&v)) | |
396 | .collect(); | |
184f17af | 397 | |
af9d4afc DM |
398 | let size_str = if let Some(size) = item.size { |
399 | size.to_string() | |
34a816cc | 400 | } else { |
af9d4afc DM |
401 | String::from("-") |
402 | }; | |
403 | println!("{} | {} | {}", path, size_str, tools::join(&files, ' ')); | |
184f17af DM |
404 | } |
405 | ||
406 | Ok(Value::Null) | |
407 | } | |
408 | ||
a47a02ae DM |
409 | #[api( |
410 | input: { | |
411 | properties: { | |
412 | repository: { | |
413 | schema: REPO_URL_SCHEMA, | |
414 | optional: true, | |
415 | }, | |
416 | snapshot: { | |
417 | type: String, | |
418 | description: "Snapshot path.", | |
419 | }, | |
420 | } | |
421 | } | |
422 | )] | |
423 | /// Forget (remove) backup snapshots. | |
424 | async fn forget_snapshots(param: Value) -> Result<Value, Error> { | |
6f62c924 | 425 | |
2665cef7 | 426 | let repo = extract_repository_from_value(¶m)?; |
6f62c924 DM |
427 | |
428 | let path = tools::required_string_param(¶m, "snapshot")?; | |
429 | let snapshot = BackupDir::parse(path)?; | |
430 | ||
cc2ce4a9 | 431 | let mut client = HttpClient::new(repo.host(), repo.user(), None)?; |
6f62c924 | 432 | |
9e391bb7 | 433 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
6f62c924 | 434 | |
8a8a4703 DM |
435 | let result = client.delete(&path, Some(json!({ |
436 | "backup-type": snapshot.group().backup_type(), | |
437 | "backup-id": snapshot.group().backup_id(), | |
438 | "backup-time": snapshot.backup_time().timestamp(), | |
439 | }))).await?; | |
6f62c924 | 440 | |
d0a03d40 DM |
441 | record_repository(&repo); |
442 | ||
6f62c924 DM |
443 | Ok(result) |
444 | } | |
445 | ||
a47a02ae DM |
446 | #[api( |
447 | input: { | |
448 | properties: { | |
449 | repository: { | |
450 | schema: REPO_URL_SCHEMA, | |
451 | optional: true, | |
452 | }, | |
453 | } | |
454 | } | |
455 | )] | |
456 | /// Try to login. If successful, store ticket. | |
457 | async fn api_login(param: Value) -> Result<Value, Error> { | |
e240d8be DM |
458 | |
459 | let repo = extract_repository_from_value(¶m)?; | |
460 | ||
cc2ce4a9 | 461 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
8a8a4703 | 462 | client.login().await?; |
e240d8be DM |
463 | |
464 | record_repository(&repo); | |
465 | ||
466 | Ok(Value::Null) | |
467 | } | |
468 | ||
a47a02ae DM |
469 | #[api( |
470 | input: { | |
471 | properties: { | |
472 | repository: { | |
473 | schema: REPO_URL_SCHEMA, | |
474 | optional: true, | |
475 | }, | |
476 | } | |
477 | } | |
478 | )] | |
479 | /// Logout (delete stored ticket). | |
480 | fn api_logout(param: Value) -> Result<Value, Error> { | |
e240d8be DM |
481 | |
482 | let repo = extract_repository_from_value(¶m)?; | |
483 | ||
484 | delete_ticket_info(repo.host(), repo.user())?; | |
485 | ||
486 | Ok(Value::Null) | |
487 | } | |
488 | ||
a47a02ae DM |
489 | #[api( |
490 | input: { | |
491 | properties: { | |
492 | repository: { | |
493 | schema: REPO_URL_SCHEMA, | |
494 | optional: true, | |
495 | }, | |
496 | snapshot: { | |
497 | type: String, | |
498 | description: "Snapshot path.", | |
499 | }, | |
500 | } | |
501 | } | |
502 | )] | |
503 | /// Dump catalog. | |
504 | async fn dump_catalog(param: Value) -> Result<Value, Error> { | |
9049a8cf DM |
505 | |
506 | let repo = extract_repository_from_value(¶m)?; | |
507 | ||
508 | let path = tools::required_string_param(¶m, "snapshot")?; | |
509 | let snapshot = BackupDir::parse(path)?; | |
510 | ||
11377a47 | 511 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); |
9049a8cf DM |
512 | |
513 | let crypt_config = match keyfile { | |
514 | None => None, | |
515 | Some(path) => { | |
a8f10f84 | 516 | let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
9025312a | 517 | Some(Arc::new(CryptConfig::new(key)?)) |
9049a8cf DM |
518 | } |
519 | }; | |
520 | ||
cc2ce4a9 | 521 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
9049a8cf | 522 | |
8a8a4703 DM |
523 | let client = BackupReader::start( |
524 | client, | |
525 | crypt_config.clone(), | |
526 | repo.store(), | |
527 | &snapshot.group().backup_type(), | |
528 | &snapshot.group().backup_id(), | |
529 | snapshot.backup_time(), | |
530 | true, | |
531 | ).await?; | |
9049a8cf | 532 | |
8a8a4703 | 533 | let manifest = client.download_manifest().await?; |
d2267b11 | 534 | |
8a8a4703 | 535 | let index = client.download_dynamic_index(&manifest, CATALOG_NAME).await?; |
bf6e3217 | 536 | |
8a8a4703 | 537 | let most_used = index.find_most_used_chunks(8); |
bf6e3217 | 538 | |
8a8a4703 | 539 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); |
bf6e3217 | 540 | |
8a8a4703 | 541 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); |
9049a8cf | 542 | |
8a8a4703 DM |
543 | let mut catalogfile = std::fs::OpenOptions::new() |
544 | .write(true) | |
545 | .read(true) | |
546 | .custom_flags(libc::O_TMPFILE) | |
547 | .open("/tmp")?; | |
d2267b11 | 548 | |
8a8a4703 DM |
549 | std::io::copy(&mut reader, &mut catalogfile) |
550 | .map_err(|err| format_err!("unable to download catalog - {}", err))?; | |
a84ef4c2 | 551 | |
8a8a4703 | 552 | catalogfile.seek(SeekFrom::Start(0))?; |
9049a8cf | 553 | |
8a8a4703 | 554 | let mut catalog_reader = CatalogReader::new(catalogfile); |
9049a8cf | 555 | |
8a8a4703 | 556 | catalog_reader.dump()?; |
e9722f8b | 557 | |
8a8a4703 | 558 | record_repository(&repo); |
9049a8cf DM |
559 | |
560 | Ok(Value::Null) | |
561 | } | |
562 | ||
a47a02ae DM |
563 | #[api( |
564 | input: { | |
565 | properties: { | |
566 | repository: { | |
567 | schema: REPO_URL_SCHEMA, | |
568 | optional: true, | |
569 | }, | |
570 | snapshot: { | |
571 | type: String, | |
572 | description: "Snapshot path.", | |
573 | }, | |
574 | "output-format": { | |
575 | schema: OUTPUT_FORMAT, | |
576 | optional: true, | |
577 | }, | |
578 | } | |
579 | } | |
580 | )] | |
581 | /// List snapshot files. | |
582 | async fn list_snapshot_files(param: Value) -> Result<Value, Error> { | |
52c171e4 DM |
583 | |
584 | let repo = extract_repository_from_value(¶m)?; | |
585 | ||
586 | let path = tools::required_string_param(¶m, "snapshot")?; | |
587 | let snapshot = BackupDir::parse(path)?; | |
588 | ||
589 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); | |
590 | ||
cc2ce4a9 | 591 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
52c171e4 DM |
592 | |
593 | let path = format!("api2/json/admin/datastore/{}/files", repo.store()); | |
594 | ||
8a8a4703 DM |
595 | let mut result = client.get(&path, Some(json!({ |
596 | "backup-type": snapshot.group().backup_type(), | |
597 | "backup-id": snapshot.group().backup_id(), | |
598 | "backup-time": snapshot.backup_time().timestamp(), | |
599 | }))).await?; | |
52c171e4 DM |
600 | |
601 | record_repository(&repo); | |
602 | ||
8c70e3eb | 603 | let list: Value = result["data"].take(); |
52c171e4 DM |
604 | |
605 | if output_format == "text" { | |
8c70e3eb DM |
606 | for item in list.as_array().unwrap().iter() { |
607 | println!( | |
608 | "{} {}", | |
609 | strip_server_file_expenstion(item["filename"].as_str().unwrap()), | |
610 | item["size"].as_u64().unwrap_or(0), | |
611 | ); | |
52c171e4 DM |
612 | } |
613 | } else { | |
8c70e3eb | 614 | format_and_print_result(&list, &output_format); |
52c171e4 DM |
615 | } |
616 | ||
617 | Ok(Value::Null) | |
618 | } | |
619 | ||
a47a02ae | 620 | #[api( |
94913f35 | 621 | input: { |
a47a02ae DM |
622 | properties: { |
623 | repository: { | |
624 | schema: REPO_URL_SCHEMA, | |
625 | optional: true, | |
626 | }, | |
94913f35 DM |
627 | "output-format": { |
628 | schema: OUTPUT_FORMAT, | |
629 | optional: true, | |
630 | }, | |
631 | }, | |
632 | }, | |
a47a02ae DM |
633 | )] |
634 | /// Start garbage collection for a specific repository. | |
635 | async fn start_garbage_collection(param: Value) -> Result<Value, Error> { | |
8cc0d6af | 636 | |
2665cef7 | 637 | let repo = extract_repository_from_value(¶m)?; |
e5f7def4 | 638 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); |
8cc0d6af | 639 | |
cc2ce4a9 | 640 | let mut client = HttpClient::new(repo.host(), repo.user(), None)?; |
8cc0d6af | 641 | |
d0a03d40 | 642 | let path = format!("api2/json/admin/datastore/{}/gc", repo.store()); |
8cc0d6af | 643 | |
8a8a4703 | 644 | let result = client.post(&path, None).await?; |
8cc0d6af | 645 | |
8a8a4703 | 646 | record_repository(&repo); |
d0a03d40 | 647 | |
8a8a4703 | 648 | view_task_result(client, result, &output_format).await?; |
e5f7def4 | 649 | |
e5f7def4 | 650 | Ok(Value::Null) |
8cc0d6af | 651 | } |
33d64b81 | 652 | |
ae0be2dd DM |
653 | fn parse_backupspec(value: &str) -> Result<(&str, &str), Error> { |
654 | ||
255f378a | 655 | if let Some(caps) = (BACKUPSPEC_REGEX.regex_obj)().captures(value) { |
ae0be2dd DM |
656 | return Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str())); |
657 | } | |
658 | bail!("unable to parse directory specification '{}'", value); | |
659 | } | |
660 | ||
bf6e3217 DM |
661 | fn spawn_catalog_upload( |
662 | client: Arc<BackupWriter>, | |
663 | crypt_config: Option<Arc<CryptConfig>>, | |
664 | ) -> Result< | |
665 | ( | |
666 | Arc<Mutex<CatalogWriter<SenderWriter>>>, | |
667 | tokio::sync::oneshot::Receiver<Result<BackupStats, Error>> | |
668 | ), Error> | |
669 | { | |
670 | let (catalog_tx, catalog_rx) = mpsc::channel(10); // allow to buffer 10 writes | |
671 | let catalog_stream = catalog_rx.map_err(Error::from); | |
672 | let catalog_chunk_size = 512*1024; | |
673 | let catalog_chunk_stream = ChunkStream::new(catalog_stream, Some(catalog_chunk_size)); | |
674 | ||
675 | let catalog = Arc::new(Mutex::new(CatalogWriter::new(SenderWriter::new(catalog_tx))?)); | |
676 | ||
677 | let (catalog_result_tx, catalog_result_rx) = tokio::sync::oneshot::channel(); | |
678 | ||
679 | tokio::spawn(async move { | |
680 | let catalog_upload_result = client | |
681 | .upload_stream(CATALOG_NAME, catalog_chunk_stream, "dynamic", None, crypt_config) | |
682 | .await; | |
683 | ||
684 | if let Err(ref err) = catalog_upload_result { | |
685 | eprintln!("catalog upload error - {}", err); | |
686 | client.cancel(); | |
687 | } | |
688 | ||
689 | let _ = catalog_result_tx.send(catalog_upload_result); | |
690 | }); | |
691 | ||
692 | Ok((catalog, catalog_result_rx)) | |
693 | } | |
694 | ||
a47a02ae DM |
695 | #[api( |
696 | input: { | |
697 | properties: { | |
698 | backupspec: { | |
699 | type: Array, | |
700 | description: "List of backup source specifications ([<label.ext>:<path>] ...)", | |
701 | items: { | |
702 | schema: BACKUP_SOURCE_SCHEMA, | |
703 | } | |
704 | }, | |
705 | repository: { | |
706 | schema: REPO_URL_SCHEMA, | |
707 | optional: true, | |
708 | }, | |
709 | "include-dev": { | |
710 | description: "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.", | |
711 | optional: true, | |
712 | items: { | |
713 | type: String, | |
714 | description: "Path to file.", | |
715 | } | |
716 | }, | |
717 | keyfile: { | |
718 | schema: KEYFILE_SCHEMA, | |
719 | optional: true, | |
720 | }, | |
721 | "skip-lost-and-found": { | |
722 | type: Boolean, | |
723 | description: "Skip lost+found directory.", | |
724 | optional: true, | |
725 | }, | |
726 | "backup-type": { | |
727 | schema: BACKUP_TYPE_SCHEMA, | |
728 | optional: true, | |
729 | }, | |
730 | "backup-id": { | |
731 | schema: BACKUP_ID_SCHEMA, | |
732 | optional: true, | |
733 | }, | |
734 | "backup-time": { | |
735 | schema: BACKUP_TIME_SCHEMA, | |
736 | optional: true, | |
737 | }, | |
738 | "chunk-size": { | |
739 | schema: CHUNK_SIZE_SCHEMA, | |
740 | optional: true, | |
741 | }, | |
742 | } | |
743 | } | |
744 | )] | |
745 | /// Create (host) backup. | |
746 | async fn create_backup( | |
6049b71f DM |
747 | param: Value, |
748 | _info: &ApiMethod, | |
dd5495d6 | 749 | _rpcenv: &mut dyn RpcEnvironment, |
6049b71f | 750 | ) -> Result<Value, Error> { |
ff5d3707 | 751 | |
2665cef7 | 752 | let repo = extract_repository_from_value(¶m)?; |
ae0be2dd DM |
753 | |
754 | let backupspec_list = tools::required_array_param(¶m, "backupspec")?; | |
a914a774 | 755 | |
eed6db39 DM |
756 | let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false); |
757 | ||
5b72c9b4 DM |
758 | let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false); |
759 | ||
219ef0e6 DM |
760 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
761 | ||
ca5d0b61 DM |
762 | let backup_time_opt = param["backup-time"].as_i64(); |
763 | ||
36898ffc | 764 | let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize); |
2d9d143a | 765 | |
247cdbce DM |
766 | if let Some(size) = chunk_size_opt { |
767 | verify_chunk_size(size)?; | |
2d9d143a DM |
768 | } |
769 | ||
11377a47 | 770 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); |
6d0983db | 771 | |
f69adc81 | 772 | let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename()); |
fba30411 | 773 | |
bbf9e7e9 | 774 | let backup_type = param["backup-type"].as_str().unwrap_or("host"); |
ca5d0b61 | 775 | |
2eeaacb9 DM |
776 | let include_dev = param["include-dev"].as_array(); |
777 | ||
778 | let mut devices = if all_file_systems { None } else { Some(HashSet::new()) }; | |
779 | ||
780 | if let Some(include_dev) = include_dev { | |
781 | if all_file_systems { | |
782 | bail!("option 'all-file-systems' conflicts with option 'include-dev'"); | |
783 | } | |
784 | ||
785 | let mut set = HashSet::new(); | |
786 | for path in include_dev { | |
787 | let path = path.as_str().unwrap(); | |
788 | let stat = nix::sys::stat::stat(path) | |
789 | .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?; | |
790 | set.insert(stat.st_dev); | |
791 | } | |
792 | devices = Some(set); | |
793 | } | |
794 | ||
ae0be2dd | 795 | let mut upload_list = vec![]; |
a914a774 | 796 | |
79679c2d | 797 | enum BackupType { PXAR, IMAGE, CONFIG, LOGFILE }; |
6af905c1 | 798 | |
bf6e3217 DM |
799 | let mut upload_catalog = false; |
800 | ||
ae0be2dd DM |
801 | for backupspec in backupspec_list { |
802 | let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?; | |
bcd879cf | 803 | |
eb1804c5 DM |
804 | use std::os::unix::fs::FileTypeExt; |
805 | ||
3fa71727 CE |
806 | let metadata = std::fs::metadata(filename) |
807 | .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?; | |
eb1804c5 | 808 | let file_type = metadata.file_type(); |
23bb8780 | 809 | |
4af0ee05 | 810 | let extension = target.rsplit('.').next() |
11377a47 | 811 | .ok_or_else(|| format_err!("missing target file extenion '{}'", target))?; |
bcd879cf | 812 | |
ec8a9bb9 DM |
813 | match extension { |
814 | "pxar" => { | |
815 | if !file_type.is_dir() { | |
816 | bail!("got unexpected file type (expected directory)"); | |
817 | } | |
4af0ee05 | 818 | upload_list.push((BackupType::PXAR, filename.to_owned(), format!("{}.didx", target), 0)); |
bf6e3217 | 819 | upload_catalog = true; |
ec8a9bb9 DM |
820 | } |
821 | "img" => { | |
eb1804c5 | 822 | |
ec8a9bb9 DM |
823 | if !(file_type.is_file() || file_type.is_block_device()) { |
824 | bail!("got unexpected file type (expected file or block device)"); | |
825 | } | |
eb1804c5 | 826 | |
e18a6c9e | 827 | let size = image_size(&PathBuf::from(filename))?; |
23bb8780 | 828 | |
ec8a9bb9 | 829 | if size == 0 { bail!("got zero-sized file '{}'", filename); } |
ae0be2dd | 830 | |
4af0ee05 | 831 | upload_list.push((BackupType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size)); |
ec8a9bb9 DM |
832 | } |
833 | "conf" => { | |
834 | if !file_type.is_file() { | |
835 | bail!("got unexpected file type (expected regular file)"); | |
836 | } | |
4af0ee05 | 837 | upload_list.push((BackupType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len())); |
ec8a9bb9 | 838 | } |
79679c2d DM |
839 | "log" => { |
840 | if !file_type.is_file() { | |
841 | bail!("got unexpected file type (expected regular file)"); | |
842 | } | |
4af0ee05 | 843 | upload_list.push((BackupType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len())); |
79679c2d | 844 | } |
ec8a9bb9 DM |
845 | _ => { |
846 | bail!("got unknown archive extension '{}'", extension); | |
847 | } | |
ae0be2dd DM |
848 | } |
849 | } | |
850 | ||
11377a47 | 851 | let backup_time = Utc.timestamp(backup_time_opt.unwrap_or_else(|| Utc::now().timestamp()), 0); |
ae0be2dd | 852 | |
cc2ce4a9 | 853 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
d0a03d40 DM |
854 | record_repository(&repo); |
855 | ||
ca5d0b61 DM |
856 | println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time)); |
857 | ||
f69adc81 | 858 | println!("Client name: {}", proxmox::tools::nodename()); |
ca5d0b61 DM |
859 | |
860 | let start_time = Local::now(); | |
861 | ||
7a6cfbd9 | 862 | println!("Starting protocol: {}", start_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false)); |
51144821 | 863 | |
bb823140 DM |
864 | let (crypt_config, rsa_encrypted_key) = match keyfile { |
865 | None => (None, None), | |
6d0983db | 866 | Some(path) => { |
a8f10f84 | 867 | let (key, created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
bb823140 DM |
868 | |
869 | let crypt_config = CryptConfig::new(key)?; | |
870 | ||
871 | let path = master_pubkey_path()?; | |
872 | if path.exists() { | |
e18a6c9e | 873 | let pem_data = file_get_contents(&path)?; |
bb823140 DM |
874 | let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?; |
875 | let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?; | |
876 | (Some(Arc::new(crypt_config)), Some(enc_key)) | |
877 | } else { | |
878 | (Some(Arc::new(crypt_config)), None) | |
879 | } | |
6d0983db DM |
880 | } |
881 | }; | |
f98ac774 | 882 | |
8a8a4703 DM |
883 | let client = BackupWriter::start( |
884 | client, | |
885 | repo.store(), | |
886 | backup_type, | |
887 | &backup_id, | |
888 | backup_time, | |
889 | verbose, | |
890 | ).await?; | |
891 | ||
892 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time.timestamp()); | |
893 | let mut manifest = BackupManifest::new(snapshot); | |
894 | ||
895 | let (catalog, catalog_result_rx) = spawn_catalog_upload(client.clone(), crypt_config.clone())?; | |
896 | ||
897 | for (backup_type, filename, target, size) in upload_list { | |
898 | match backup_type { | |
899 | BackupType::CONFIG => { | |
900 | println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target); | |
901 | let stats = client | |
902 | .upload_blob_from_file(&filename, &target, crypt_config.clone(), true) | |
903 | .await?; | |
1e8da0a7 | 904 | manifest.add_file(target, stats.size, stats.csum)?; |
8a8a4703 DM |
905 | } |
906 | BackupType::LOGFILE => { // fixme: remove - not needed anymore ? | |
907 | println!("Upload log file '{}' to '{:?}' as {}", filename, repo, target); | |
908 | let stats = client | |
909 | .upload_blob_from_file(&filename, &target, crypt_config.clone(), true) | |
910 | .await?; | |
1e8da0a7 | 911 | manifest.add_file(target, stats.size, stats.csum)?; |
8a8a4703 DM |
912 | } |
913 | BackupType::PXAR => { | |
914 | println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target); | |
915 | catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?; | |
916 | let stats = backup_directory( | |
917 | &client, | |
918 | &filename, | |
919 | &target, | |
920 | chunk_size_opt, | |
921 | devices.clone(), | |
922 | verbose, | |
923 | skip_lost_and_found, | |
924 | crypt_config.clone(), | |
925 | catalog.clone(), | |
926 | ).await?; | |
1e8da0a7 | 927 | manifest.add_file(target, stats.size, stats.csum)?; |
8a8a4703 DM |
928 | catalog.lock().unwrap().end_directory()?; |
929 | } | |
930 | BackupType::IMAGE => { | |
931 | println!("Upload image '{}' to '{:?}' as {}", filename, repo, target); | |
932 | let stats = backup_image( | |
933 | &client, | |
934 | &filename, | |
935 | &target, | |
936 | size, | |
937 | chunk_size_opt, | |
938 | verbose, | |
939 | crypt_config.clone(), | |
940 | ).await?; | |
1e8da0a7 | 941 | manifest.add_file(target, stats.size, stats.csum)?; |
6af905c1 DM |
942 | } |
943 | } | |
8a8a4703 | 944 | } |
4818c8b6 | 945 | |
8a8a4703 DM |
946 | // finalize and upload catalog |
947 | if upload_catalog { | |
948 | let mutex = Arc::try_unwrap(catalog) | |
949 | .map_err(|_| format_err!("unable to get catalog (still used)"))?; | |
950 | let mut catalog = mutex.into_inner().unwrap(); | |
bf6e3217 | 951 | |
8a8a4703 | 952 | catalog.finish()?; |
2761d6a4 | 953 | |
8a8a4703 | 954 | drop(catalog); // close upload stream |
2761d6a4 | 955 | |
8a8a4703 | 956 | let stats = catalog_result_rx.await??; |
9d135fe6 | 957 | |
1e8da0a7 | 958 | manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum)?; |
8a8a4703 | 959 | } |
2761d6a4 | 960 | |
8a8a4703 DM |
961 | if let Some(rsa_encrypted_key) = rsa_encrypted_key { |
962 | let target = "rsa-encrypted.key"; | |
963 | println!("Upload RSA encoded key to '{:?}' as {}", repo, target); | |
964 | let stats = client | |
965 | .upload_blob_from_data(rsa_encrypted_key, target, None, false, false) | |
966 | .await?; | |
1e8da0a7 | 967 | manifest.add_file(format!("{}.blob", target), stats.size, stats.csum)?; |
8a8a4703 DM |
968 | |
969 | // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t | |
970 | /* | |
971 | let mut buffer2 = vec![0u8; rsa.size() as usize]; | |
972 | let pem_data = file_get_contents("master-private.pem")?; | |
973 | let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?; | |
974 | let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?; | |
975 | println!("TEST {} {:?}", len, buffer2); | |
976 | */ | |
977 | } | |
9f46c7de | 978 | |
8a8a4703 DM |
979 | // create manifest (index.json) |
980 | let manifest = manifest.into_json(); | |
2c3891d1 | 981 | |
8a8a4703 DM |
982 | println!("Upload index.json to '{:?}'", repo); |
983 | let manifest = serde_json::to_string_pretty(&manifest)?.into(); | |
984 | client | |
985 | .upload_blob_from_data(manifest, MANIFEST_BLOB_NAME, crypt_config.clone(), true, true) | |
986 | .await?; | |
2c3891d1 | 987 | |
8a8a4703 | 988 | client.finish().await?; |
c4ff3dce | 989 | |
8a8a4703 DM |
990 | let end_time = Local::now(); |
991 | let elapsed = end_time.signed_duration_since(start_time); | |
992 | println!("Duration: {}", elapsed); | |
3ec3ec3f | 993 | |
8a8a4703 | 994 | println!("End Time: {}", end_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false)); |
3d5c11e5 | 995 | |
8a8a4703 | 996 | Ok(Value::Null) |
f98ea63d DM |
997 | } |
998 | ||
d0a03d40 | 999 | fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
f98ea63d DM |
1000 | |
1001 | let mut result = vec![]; | |
1002 | ||
1003 | let data: Vec<&str> = arg.splitn(2, ':').collect(); | |
1004 | ||
bff11030 | 1005 | if data.len() != 2 { |
8968258b DM |
1006 | result.push(String::from("root.pxar:/")); |
1007 | result.push(String::from("etc.pxar:/etc")); | |
bff11030 DM |
1008 | return result; |
1009 | } | |
f98ea63d | 1010 | |
496a6784 | 1011 | let files = tools::complete_file_name(data[1], param); |
f98ea63d DM |
1012 | |
1013 | for file in files { | |
1014 | result.push(format!("{}:{}", data[0], file)); | |
1015 | } | |
1016 | ||
1017 | result | |
ff5d3707 | 1018 | } |
1019 | ||
88892ea8 DM |
1020 | fn dump_image<W: Write>( |
1021 | client: Arc<BackupReader>, | |
1022 | crypt_config: Option<Arc<CryptConfig>>, | |
1023 | index: FixedIndexReader, | |
1024 | mut writer: W, | |
fd04ca7a | 1025 | verbose: bool, |
88892ea8 DM |
1026 | ) -> Result<(), Error> { |
1027 | ||
1028 | let most_used = index.find_most_used_chunks(8); | |
1029 | ||
1030 | let mut chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
1031 | ||
1032 | // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy | |
1033 | // and thus slows down reading. Instead, directly use RemoteChunkReader | |
fd04ca7a DM |
1034 | let mut per = 0; |
1035 | let mut bytes = 0; | |
1036 | let start_time = std::time::Instant::now(); | |
1037 | ||
88892ea8 DM |
1038 | for pos in 0..index.index_count() { |
1039 | let digest = index.index_digest(pos).unwrap(); | |
1040 | let raw_data = chunk_reader.read_chunk(&digest)?; | |
1041 | writer.write_all(&raw_data)?; | |
fd04ca7a DM |
1042 | bytes += raw_data.len(); |
1043 | if verbose { | |
1044 | let next_per = ((pos+1)*100)/index.index_count(); | |
1045 | if per != next_per { | |
1046 | eprintln!("progress {}% (read {} bytes, duration {} sec)", | |
1047 | next_per, bytes, start_time.elapsed().as_secs()); | |
1048 | per = next_per; | |
1049 | } | |
1050 | } | |
88892ea8 DM |
1051 | } |
1052 | ||
fd04ca7a DM |
1053 | let end_time = std::time::Instant::now(); |
1054 | let elapsed = end_time.duration_since(start_time); | |
1055 | eprintln!("restore image complete (bytes={}, duration={:.2}s, speed={:.2}MB/s)", | |
1056 | bytes, | |
1057 | elapsed.as_secs_f64(), | |
1058 | bytes as f64/(1024.0*1024.0*elapsed.as_secs_f64()) | |
1059 | ); | |
1060 | ||
1061 | ||
88892ea8 DM |
1062 | Ok(()) |
1063 | } | |
1064 | ||
a47a02ae DM |
1065 | #[api( |
1066 | input: { | |
1067 | properties: { | |
1068 | repository: { | |
1069 | schema: REPO_URL_SCHEMA, | |
1070 | optional: true, | |
1071 | }, | |
1072 | snapshot: { | |
1073 | type: String, | |
1074 | description: "Group/Snapshot path.", | |
1075 | }, | |
1076 | "archive-name": { | |
1077 | description: "Backup archive name.", | |
1078 | type: String, | |
1079 | }, | |
1080 | target: { | |
1081 | type: String, | |
1082 | description: r###"Target directory path. Use '-' to write to stdandard output. | |
8a8a4703 | 1083 | |
a47a02ae | 1084 | We do not extraxt '.pxar' archives when writing to stdandard output. |
8a8a4703 | 1085 | |
a47a02ae DM |
1086 | "### |
1087 | }, | |
1088 | "allow-existing-dirs": { | |
1089 | type: Boolean, | |
1090 | description: "Do not fail if directories already exists.", | |
1091 | optional: true, | |
1092 | }, | |
1093 | keyfile: { | |
1094 | schema: KEYFILE_SCHEMA, | |
1095 | optional: true, | |
1096 | }, | |
1097 | } | |
1098 | } | |
1099 | )] | |
1100 | /// Restore backup repository. | |
1101 | async fn restore(param: Value) -> Result<Value, Error> { | |
2665cef7 | 1102 | let repo = extract_repository_from_value(¶m)?; |
9f912493 | 1103 | |
86eda3eb DM |
1104 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
1105 | ||
46d5aa0a DM |
1106 | let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false); |
1107 | ||
d5c34d98 DM |
1108 | let archive_name = tools::required_string_param(¶m, "archive-name")?; |
1109 | ||
cc2ce4a9 | 1110 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
d0a03d40 | 1111 | |
d0a03d40 | 1112 | record_repository(&repo); |
d5c34d98 | 1113 | |
9f912493 | 1114 | let path = tools::required_string_param(¶m, "snapshot")?; |
9f912493 | 1115 | |
86eda3eb | 1116 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { |
d5c34d98 | 1117 | let group = BackupGroup::parse(path)?; |
9f912493 | 1118 | |
9e391bb7 | 1119 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
af9d4afc | 1120 | let mut result = client.get(&path, Some(json!({ |
d5c34d98 DM |
1121 | "backup-type": group.backup_type(), |
1122 | "backup-id": group.backup_id(), | |
e9722f8b | 1123 | }))).await?; |
9f912493 | 1124 | |
af9d4afc | 1125 | let mut list: Vec<SnapshotListItem> = serde_json::from_value(result["data"].take())?; |
11377a47 | 1126 | if list.is_empty() { |
d5c34d98 DM |
1127 | bail!("backup group '{}' does not contain any snapshots:", path); |
1128 | } | |
af9d4afc DM |
1129 | list.sort_unstable_by(|a, b| b.backup_time.cmp(&a.backup_time)); |
1130 | ||
1131 | let backup_time = Utc.timestamp(list[0].backup_time, 0); | |
9f912493 | 1132 | |
86eda3eb | 1133 | (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time) |
d5c34d98 DM |
1134 | } else { |
1135 | let snapshot = BackupDir::parse(path)?; | |
86eda3eb DM |
1136 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) |
1137 | }; | |
9f912493 | 1138 | |
d5c34d98 | 1139 | let target = tools::required_string_param(¶m, "target")?; |
bf125261 | 1140 | let target = if target == "-" { None } else { Some(target) }; |
2ae7d196 | 1141 | |
11377a47 | 1142 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); |
2ae7d196 | 1143 | |
86eda3eb DM |
1144 | let crypt_config = match keyfile { |
1145 | None => None, | |
1146 | Some(path) => { | |
a8f10f84 | 1147 | let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
86eda3eb DM |
1148 | Some(Arc::new(CryptConfig::new(key)?)) |
1149 | } | |
1150 | }; | |
d5c34d98 | 1151 | |
afb4cd28 DM |
1152 | let server_archive_name = if archive_name.ends_with(".pxar") { |
1153 | format!("{}.didx", archive_name) | |
1154 | } else if archive_name.ends_with(".img") { | |
1155 | format!("{}.fidx", archive_name) | |
1156 | } else { | |
f8100e96 | 1157 | format!("{}.blob", archive_name) |
afb4cd28 | 1158 | }; |
9f912493 | 1159 | |
296c50ba DM |
1160 | let client = BackupReader::start( |
1161 | client, | |
1162 | crypt_config.clone(), | |
1163 | repo.store(), | |
1164 | &backup_type, | |
1165 | &backup_id, | |
1166 | backup_time, | |
1167 | true, | |
1168 | ).await?; | |
86eda3eb | 1169 | |
f06b820a | 1170 | let manifest = client.download_manifest().await?; |
02fcf372 | 1171 | |
ad6e5a6f | 1172 | if server_archive_name == MANIFEST_BLOB_NAME { |
f06b820a | 1173 | let backup_index_data = manifest.into_json().to_string(); |
02fcf372 | 1174 | if let Some(target) = target { |
feaa1ad3 | 1175 | replace_file(target, backup_index_data.as_bytes(), CreateOptions::new())?; |
02fcf372 DM |
1176 | } else { |
1177 | let stdout = std::io::stdout(); | |
1178 | let mut writer = stdout.lock(); | |
296c50ba | 1179 | writer.write_all(backup_index_data.as_bytes()) |
02fcf372 DM |
1180 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1181 | } | |
1182 | ||
1183 | } else if server_archive_name.ends_with(".blob") { | |
d2267b11 | 1184 | |
bb19af73 | 1185 | let mut reader = client.download_blob(&manifest, &server_archive_name).await?; |
f8100e96 | 1186 | |
bf125261 | 1187 | if let Some(target) = target { |
0d986280 DM |
1188 | let mut writer = std::fs::OpenOptions::new() |
1189 | .write(true) | |
1190 | .create(true) | |
1191 | .create_new(true) | |
1192 | .open(target) | |
1193 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?; | |
1194 | std::io::copy(&mut reader, &mut writer)?; | |
bf125261 DM |
1195 | } else { |
1196 | let stdout = std::io::stdout(); | |
1197 | let mut writer = stdout.lock(); | |
0d986280 | 1198 | std::io::copy(&mut reader, &mut writer) |
bf125261 DM |
1199 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1200 | } | |
f8100e96 DM |
1201 | |
1202 | } else if server_archive_name.ends_with(".didx") { | |
86eda3eb | 1203 | |
c3d84a22 | 1204 | let index = client.download_dynamic_index(&manifest, &server_archive_name).await?; |
df65bd3d | 1205 | |
f4bf7dfc DM |
1206 | let most_used = index.find_most_used_chunks(8); |
1207 | ||
1208 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
1209 | ||
afb4cd28 | 1210 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); |
86eda3eb | 1211 | |
bf125261 | 1212 | if let Some(target) = target { |
86eda3eb | 1213 | |
47651f95 | 1214 | let feature_flags = pxar::flags::DEFAULT; |
f701d033 DM |
1215 | let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags); |
1216 | decoder.set_callback(move |path| { | |
bf125261 | 1217 | if verbose { |
fd04ca7a | 1218 | eprintln!("{:?}", path); |
bf125261 DM |
1219 | } |
1220 | Ok(()) | |
1221 | }); | |
6a879109 CE |
1222 | decoder.set_allow_existing_dirs(allow_existing_dirs); |
1223 | ||
fa7e957c | 1224 | decoder.restore(Path::new(target), &Vec::new())?; |
bf125261 | 1225 | } else { |
88892ea8 DM |
1226 | let mut writer = std::fs::OpenOptions::new() |
1227 | .write(true) | |
1228 | .open("/dev/stdout") | |
1229 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?; | |
afb4cd28 | 1230 | |
bf125261 DM |
1231 | std::io::copy(&mut reader, &mut writer) |
1232 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
1233 | } | |
afb4cd28 | 1234 | } else if server_archive_name.ends_with(".fidx") { |
afb4cd28 | 1235 | |
72050500 | 1236 | let index = client.download_fixed_index(&manifest, &server_archive_name).await?; |
df65bd3d | 1237 | |
88892ea8 DM |
1238 | let mut writer = if let Some(target) = target { |
1239 | std::fs::OpenOptions::new() | |
bf125261 DM |
1240 | .write(true) |
1241 | .create(true) | |
1242 | .create_new(true) | |
1243 | .open(target) | |
88892ea8 | 1244 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))? |
bf125261 | 1245 | } else { |
88892ea8 DM |
1246 | std::fs::OpenOptions::new() |
1247 | .write(true) | |
1248 | .open("/dev/stdout") | |
1249 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))? | |
1250 | }; | |
afb4cd28 | 1251 | |
fd04ca7a | 1252 | dump_image(client.clone(), crypt_config.clone(), index, &mut writer, verbose)?; |
88892ea8 DM |
1253 | |
1254 | } else { | |
f8100e96 | 1255 | bail!("unknown archive file extension (expected .pxar of .img)"); |
3031e44c | 1256 | } |
fef44d4f DM |
1257 | |
1258 | Ok(Value::Null) | |
45db6f89 DM |
1259 | } |
1260 | ||
a47a02ae DM |
1261 | #[api( |
1262 | input: { | |
1263 | properties: { | |
1264 | repository: { | |
1265 | schema: REPO_URL_SCHEMA, | |
1266 | optional: true, | |
1267 | }, | |
1268 | snapshot: { | |
1269 | type: String, | |
1270 | description: "Group/Snapshot path.", | |
1271 | }, | |
1272 | logfile: { | |
1273 | type: String, | |
1274 | description: "The path to the log file you want to upload.", | |
1275 | }, | |
1276 | keyfile: { | |
1277 | schema: KEYFILE_SCHEMA, | |
1278 | optional: true, | |
1279 | }, | |
1280 | } | |
1281 | } | |
1282 | )] | |
1283 | /// Upload backup log file. | |
1284 | async fn upload_log(param: Value) -> Result<Value, Error> { | |
ec34f7eb DM |
1285 | |
1286 | let logfile = tools::required_string_param(¶m, "logfile")?; | |
1287 | let repo = extract_repository_from_value(¶m)?; | |
1288 | ||
1289 | let snapshot = tools::required_string_param(¶m, "snapshot")?; | |
1290 | let snapshot = BackupDir::parse(snapshot)?; | |
1291 | ||
cc2ce4a9 | 1292 | let mut client = HttpClient::new(repo.host(), repo.user(), None)?; |
ec34f7eb | 1293 | |
11377a47 | 1294 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); |
ec34f7eb DM |
1295 | |
1296 | let crypt_config = match keyfile { | |
1297 | None => None, | |
1298 | Some(path) => { | |
a8f10f84 | 1299 | let (key, _created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
ec34f7eb | 1300 | let crypt_config = CryptConfig::new(key)?; |
9025312a | 1301 | Some(Arc::new(crypt_config)) |
ec34f7eb DM |
1302 | } |
1303 | }; | |
1304 | ||
e18a6c9e | 1305 | let data = file_get_contents(logfile)?; |
ec34f7eb | 1306 | |
7123ff7d | 1307 | let blob = DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?; |
ec34f7eb DM |
1308 | |
1309 | let raw_data = blob.into_inner(); | |
1310 | ||
1311 | let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store()); | |
1312 | ||
1313 | let args = json!({ | |
1314 | "backup-type": snapshot.group().backup_type(), | |
1315 | "backup-id": snapshot.group().backup_id(), | |
1316 | "backup-time": snapshot.backup_time().timestamp(), | |
1317 | }); | |
1318 | ||
1319 | let body = hyper::Body::from(raw_data); | |
1320 | ||
8a8a4703 | 1321 | client.upload("application/octet-stream", body, &path, Some(args)).await |
ec34f7eb DM |
1322 | } |
1323 | ||
a47a02ae DM |
1324 | #[api( |
1325 | input: { | |
1326 | properties: { | |
1327 | repository: { | |
1328 | schema: REPO_URL_SCHEMA, | |
1329 | optional: true, | |
1330 | }, | |
1331 | group: { | |
1332 | type: String, | |
1333 | description: "Backup group.", | |
1334 | }, | |
1335 | "output-format": { | |
1336 | schema: OUTPUT_FORMAT, | |
1337 | optional: true, | |
1338 | }, | |
1339 | "dry-run": { | |
1340 | type: Boolean, | |
1341 | description: "Just show what prune would do, but do not delete anything.", | |
1342 | optional: true, | |
1343 | }, | |
1344 | } | |
1345 | } | |
1346 | )] | |
1347 | /// Prune a backup repository. | |
1348 | async fn prune(mut param: Value) -> Result<Value, Error> { | |
83b7db02 | 1349 | |
2665cef7 | 1350 | let repo = extract_repository_from_value(¶m)?; |
83b7db02 | 1351 | |
cc2ce4a9 | 1352 | let mut client = HttpClient::new(repo.host(), repo.user(), None)?; |
83b7db02 | 1353 | |
d0a03d40 | 1354 | let path = format!("api2/json/admin/datastore/{}/prune", repo.store()); |
83b7db02 | 1355 | |
9fdc3ef4 DM |
1356 | let group = tools::required_string_param(¶m, "group")?; |
1357 | let group = BackupGroup::parse(group)?; | |
163e9bbe | 1358 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); |
9fdc3ef4 | 1359 | |
ea7a7ef2 DM |
1360 | param.as_object_mut().unwrap().remove("repository"); |
1361 | param.as_object_mut().unwrap().remove("group"); | |
163e9bbe | 1362 | param.as_object_mut().unwrap().remove("output-format"); |
ea7a7ef2 DM |
1363 | |
1364 | param["backup-type"] = group.backup_type().into(); | |
1365 | param["backup-id"] = group.backup_id().into(); | |
83b7db02 | 1366 | |
87c42375 | 1367 | let result = client.post(&path, Some(param)).await?; |
74fa81b8 | 1368 | |
87c42375 | 1369 | record_repository(&repo); |
3b03abfe | 1370 | |
87c42375 | 1371 | view_task_result(client, result, &output_format).await?; |
d0a03d40 | 1372 | |
43a406fd | 1373 | Ok(Value::Null) |
83b7db02 DM |
1374 | } |
1375 | ||
a47a02ae DM |
1376 | #[api( |
1377 | input: { | |
1378 | properties: { | |
1379 | repository: { | |
1380 | schema: REPO_URL_SCHEMA, | |
1381 | optional: true, | |
1382 | }, | |
1383 | "output-format": { | |
1384 | schema: OUTPUT_FORMAT, | |
1385 | optional: true, | |
1386 | }, | |
1387 | } | |
1388 | } | |
1389 | )] | |
1390 | /// Get repository status. | |
1391 | async fn status(param: Value) -> Result<Value, Error> { | |
34a816cc DM |
1392 | |
1393 | let repo = extract_repository_from_value(¶m)?; | |
1394 | ||
1395 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); | |
1396 | ||
cc2ce4a9 | 1397 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
34a816cc DM |
1398 | |
1399 | let path = format!("api2/json/admin/datastore/{}/status", repo.store()); | |
1400 | ||
87c42375 | 1401 | let result = client.get(&path, None).await?; |
34a816cc DM |
1402 | let data = &result["data"]; |
1403 | ||
1404 | record_repository(&repo); | |
1405 | ||
1406 | if output_format == "text" { | |
1407 | let total = data["total"].as_u64().unwrap(); | |
1408 | let used = data["used"].as_u64().unwrap(); | |
1409 | let avail = data["avail"].as_u64().unwrap(); | |
1410 | let roundup = total/200; | |
1411 | ||
1412 | println!( | |
1413 | "total: {} used: {} ({} %) available: {}", | |
1414 | total, | |
1415 | used, | |
1416 | ((used+roundup)*100)/total, | |
1417 | avail, | |
1418 | ); | |
1419 | } else { | |
f6ede796 | 1420 | format_and_print_result(data, &output_format); |
34a816cc DM |
1421 | } |
1422 | ||
1423 | Ok(Value::Null) | |
1424 | } | |
1425 | ||
5a2df000 | 1426 | // like get, but simply ignore errors and return Null instead |
e9722f8b | 1427 | async fn try_get(repo: &BackupRepository, url: &str) -> Value { |
024f11bb | 1428 | |
cc2ce4a9 | 1429 | let client = match HttpClient::new(repo.host(), repo.user(), None) { |
45cdce06 DM |
1430 | Ok(v) => v, |
1431 | _ => return Value::Null, | |
1432 | }; | |
b2388518 | 1433 | |
e9722f8b | 1434 | let mut resp = match client.get(url, None).await { |
b2388518 DM |
1435 | Ok(v) => v, |
1436 | _ => return Value::Null, | |
1437 | }; | |
1438 | ||
1439 | if let Some(map) = resp.as_object_mut() { | |
1440 | if let Some(data) = map.remove("data") { | |
1441 | return data; | |
1442 | } | |
1443 | } | |
1444 | Value::Null | |
1445 | } | |
1446 | ||
b2388518 | 1447 | fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
e9722f8b WB |
1448 | async_main(async { complete_backup_group_do(param).await }) |
1449 | } | |
1450 | ||
1451 | async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> { | |
024f11bb | 1452 | |
b2388518 DM |
1453 | let mut result = vec![]; |
1454 | ||
2665cef7 | 1455 | let repo = match extract_repository_from_map(param) { |
b2388518 | 1456 | Some(v) => v, |
024f11bb DM |
1457 | _ => return result, |
1458 | }; | |
1459 | ||
b2388518 DM |
1460 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
1461 | ||
e9722f8b | 1462 | let data = try_get(&repo, &path).await; |
b2388518 DM |
1463 | |
1464 | if let Some(list) = data.as_array() { | |
024f11bb | 1465 | for item in list { |
98f0b972 DM |
1466 | if let (Some(backup_id), Some(backup_type)) = |
1467 | (item["backup-id"].as_str(), item["backup-type"].as_str()) | |
1468 | { | |
1469 | result.push(format!("{}/{}", backup_type, backup_id)); | |
024f11bb DM |
1470 | } |
1471 | } | |
1472 | } | |
1473 | ||
1474 | result | |
1475 | } | |
1476 | ||
b2388518 | 1477 | fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
e9722f8b WB |
1478 | async_main(async { complete_group_or_snapshot_do(arg, param).await }) |
1479 | } | |
1480 | ||
1481 | async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
b2388518 | 1482 | |
b2388518 | 1483 | if arg.matches('/').count() < 2 { |
e9722f8b | 1484 | let groups = complete_backup_group_do(param).await; |
543a260f | 1485 | let mut result = vec![]; |
b2388518 DM |
1486 | for group in groups { |
1487 | result.push(group.to_string()); | |
1488 | result.push(format!("{}/", group)); | |
1489 | } | |
1490 | return result; | |
1491 | } | |
1492 | ||
e9722f8b | 1493 | complete_backup_snapshot_do(param).await |
543a260f | 1494 | } |
b2388518 | 1495 | |
3fb53e07 | 1496 | fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
e9722f8b WB |
1497 | async_main(async { complete_backup_snapshot_do(param).await }) |
1498 | } | |
1499 | ||
1500 | async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> { | |
543a260f DM |
1501 | |
1502 | let mut result = vec![]; | |
1503 | ||
1504 | let repo = match extract_repository_from_map(param) { | |
1505 | Some(v) => v, | |
1506 | _ => return result, | |
1507 | }; | |
1508 | ||
1509 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); | |
b2388518 | 1510 | |
e9722f8b | 1511 | let data = try_get(&repo, &path).await; |
b2388518 DM |
1512 | |
1513 | if let Some(list) = data.as_array() { | |
1514 | for item in list { | |
1515 | if let (Some(backup_id), Some(backup_type), Some(backup_time)) = | |
1516 | (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64()) | |
1517 | { | |
1518 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time); | |
1519 | result.push(snapshot.relative_path().to_str().unwrap().to_owned()); | |
1520 | } | |
1521 | } | |
1522 | } | |
1523 | ||
1524 | result | |
1525 | } | |
1526 | ||
45db6f89 | 1527 | fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
e9722f8b WB |
1528 | async_main(async { complete_server_file_name_do(param).await }) |
1529 | } | |
1530 | ||
1531 | async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> { | |
08dc340a DM |
1532 | |
1533 | let mut result = vec![]; | |
1534 | ||
2665cef7 | 1535 | let repo = match extract_repository_from_map(param) { |
08dc340a DM |
1536 | Some(v) => v, |
1537 | _ => return result, | |
1538 | }; | |
1539 | ||
1540 | let snapshot = match param.get("snapshot") { | |
1541 | Some(path) => { | |
1542 | match BackupDir::parse(path) { | |
1543 | Ok(v) => v, | |
1544 | _ => return result, | |
1545 | } | |
1546 | } | |
1547 | _ => return result, | |
1548 | }; | |
1549 | ||
1550 | let query = tools::json_object_to_query(json!({ | |
1551 | "backup-type": snapshot.group().backup_type(), | |
1552 | "backup-id": snapshot.group().backup_id(), | |
1553 | "backup-time": snapshot.backup_time().timestamp(), | |
1554 | })).unwrap(); | |
1555 | ||
1556 | let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query); | |
1557 | ||
e9722f8b | 1558 | let data = try_get(&repo, &path).await; |
08dc340a DM |
1559 | |
1560 | if let Some(list) = data.as_array() { | |
1561 | for item in list { | |
c4f025eb | 1562 | if let Some(filename) = item["filename"].as_str() { |
08dc340a DM |
1563 | result.push(filename.to_owned()); |
1564 | } | |
1565 | } | |
1566 | } | |
1567 | ||
45db6f89 DM |
1568 | result |
1569 | } | |
1570 | ||
1571 | fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
52c171e4 | 1572 | complete_server_file_name(arg, param) |
e9722f8b WB |
1573 | .iter() |
1574 | .map(|v| strip_server_file_expenstion(&v)) | |
1575 | .collect() | |
08dc340a DM |
1576 | } |
1577 | ||
0ec9e1b0 DM |
1578 | fn complete_pxar_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
1579 | complete_server_file_name(arg, param) | |
1580 | .iter() | |
1581 | .filter_map(|v| { | |
1582 | let name = strip_server_file_expenstion(&v); | |
1583 | if name.ends_with(".pxar") { | |
1584 | Some(name) | |
1585 | } else { | |
1586 | None | |
1587 | } | |
1588 | }) | |
1589 | .collect() | |
1590 | } | |
1591 | ||
49811347 DM |
1592 | fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
1593 | ||
1594 | let mut result = vec![]; | |
1595 | ||
1596 | let mut size = 64; | |
1597 | loop { | |
1598 | result.push(size.to_string()); | |
11377a47 | 1599 | size *= 2; |
49811347 DM |
1600 | if size > 4096 { break; } |
1601 | } | |
1602 | ||
1603 | result | |
1604 | } | |
1605 | ||
826f309b | 1606 | fn get_encryption_key_password() -> Result<Vec<u8>, Error> { |
ff5d3707 | 1607 | |
f2401311 DM |
1608 | // fixme: implement other input methods |
1609 | ||
1610 | use std::env::VarError::*; | |
1611 | match std::env::var("PBS_ENCRYPTION_PASSWORD") { | |
826f309b | 1612 | Ok(p) => return Ok(p.as_bytes().to_vec()), |
f2401311 DM |
1613 | Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"), |
1614 | Err(NotPresent) => { | |
1615 | // Try another method | |
1616 | } | |
1617 | } | |
1618 | ||
1619 | // If we're on a TTY, query the user for a password | |
1620 | if crate::tools::tty::stdin_isatty() { | |
826f309b | 1621 | return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?); |
f2401311 DM |
1622 | } |
1623 | ||
1624 | bail!("no password input mechanism available"); | |
1625 | } | |
1626 | ||
ac716234 DM |
1627 | fn key_create( |
1628 | param: Value, | |
1629 | _info: &ApiMethod, | |
1630 | _rpcenv: &mut dyn RpcEnvironment, | |
1631 | ) -> Result<Value, Error> { | |
1632 | ||
9b06db45 DM |
1633 | let path = tools::required_string_param(¶m, "path")?; |
1634 | let path = PathBuf::from(path); | |
ac716234 | 1635 | |
181f097a | 1636 | let kdf = param["kdf"].as_str().unwrap_or("scrypt"); |
ac716234 DM |
1637 | |
1638 | let key = proxmox::sys::linux::random_data(32)?; | |
1639 | ||
181f097a DM |
1640 | if kdf == "scrypt" { |
1641 | // always read passphrase from tty | |
1642 | if !crate::tools::tty::stdin_isatty() { | |
1643 | bail!("unable to read passphrase - no tty"); | |
1644 | } | |
ac716234 | 1645 | |
181f097a DM |
1646 | let password = crate::tools::tty::read_password("Encryption Key Password: ")?; |
1647 | ||
ab44acff | 1648 | let key_config = encrypt_key_with_passphrase(&key, &password)?; |
37c5a175 | 1649 | |
ab44acff | 1650 | store_key_config(&path, false, key_config)?; |
181f097a DM |
1651 | |
1652 | Ok(Value::Null) | |
1653 | } else if kdf == "none" { | |
1654 | let created = Local.timestamp(Local::now().timestamp(), 0); | |
1655 | ||
1656 | store_key_config(&path, false, KeyConfig { | |
1657 | kdf: None, | |
1658 | created, | |
ab44acff | 1659 | modified: created, |
181f097a DM |
1660 | data: key, |
1661 | })?; | |
1662 | ||
1663 | Ok(Value::Null) | |
1664 | } else { | |
1665 | unreachable!(); | |
1666 | } | |
ac716234 DM |
1667 | } |
1668 | ||
9f46c7de DM |
1669 | fn master_pubkey_path() -> Result<PathBuf, Error> { |
1670 | let base = BaseDirectories::with_prefix("proxmox-backup")?; | |
1671 | ||
1672 | // usually $HOME/.config/proxmox-backup/master-public.pem | |
1673 | let path = base.place_config_file("master-public.pem")?; | |
1674 | ||
1675 | Ok(path) | |
1676 | } | |
1677 | ||
3ea8bfc9 DM |
1678 | fn key_import_master_pubkey( |
1679 | param: Value, | |
1680 | _info: &ApiMethod, | |
1681 | _rpcenv: &mut dyn RpcEnvironment, | |
1682 | ) -> Result<Value, Error> { | |
1683 | ||
1684 | let path = tools::required_string_param(¶m, "path")?; | |
1685 | let path = PathBuf::from(path); | |
1686 | ||
e18a6c9e | 1687 | let pem_data = file_get_contents(&path)?; |
3ea8bfc9 DM |
1688 | |
1689 | if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) { | |
1690 | bail!("Unable to decode PEM data - {}", err); | |
1691 | } | |
1692 | ||
9f46c7de | 1693 | let target_path = master_pubkey_path()?; |
3ea8bfc9 | 1694 | |
feaa1ad3 | 1695 | replace_file(&target_path, &pem_data, CreateOptions::new())?; |
3ea8bfc9 DM |
1696 | |
1697 | println!("Imported public master key to {:?}", target_path); | |
1698 | ||
1699 | Ok(Value::Null) | |
1700 | } | |
1701 | ||
37c5a175 DM |
1702 | fn key_create_master_key( |
1703 | _param: Value, | |
1704 | _info: &ApiMethod, | |
1705 | _rpcenv: &mut dyn RpcEnvironment, | |
1706 | ) -> Result<Value, Error> { | |
1707 | ||
1708 | // we need a TTY to query the new password | |
1709 | if !crate::tools::tty::stdin_isatty() { | |
1710 | bail!("unable to create master key - no tty"); | |
1711 | } | |
1712 | ||
1713 | let rsa = openssl::rsa::Rsa::generate(4096)?; | |
1714 | let pkey = openssl::pkey::PKey::from_rsa(rsa)?; | |
1715 | ||
1716 | let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?; | |
1717 | let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?; | |
1718 | ||
1719 | if new_pw != verify_pw { | |
1720 | bail!("Password verification fail!"); | |
1721 | } | |
1722 | ||
1723 | if new_pw.len() < 5 { | |
1724 | bail!("Password is too short!"); | |
1725 | } | |
1726 | ||
1727 | let pub_key: Vec<u8> = pkey.public_key_to_pem()?; | |
1728 | let filename_pub = "master-public.pem"; | |
1729 | println!("Writing public master key to {}", filename_pub); | |
feaa1ad3 | 1730 | replace_file(filename_pub, pub_key.as_slice(), CreateOptions::new())?; |
37c5a175 DM |
1731 | |
1732 | let cipher = openssl::symm::Cipher::aes_256_cbc(); | |
1733 | let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?; | |
1734 | ||
1735 | let filename_priv = "master-private.pem"; | |
1736 | println!("Writing private master key to {}", filename_priv); | |
feaa1ad3 | 1737 | replace_file(filename_priv, priv_key.as_slice(), CreateOptions::new())?; |
37c5a175 DM |
1738 | |
1739 | Ok(Value::Null) | |
1740 | } | |
ac716234 DM |
1741 | |
1742 | fn key_change_passphrase( | |
1743 | param: Value, | |
1744 | _info: &ApiMethod, | |
1745 | _rpcenv: &mut dyn RpcEnvironment, | |
1746 | ) -> Result<Value, Error> { | |
1747 | ||
9b06db45 DM |
1748 | let path = tools::required_string_param(¶m, "path")?; |
1749 | let path = PathBuf::from(path); | |
ac716234 | 1750 | |
181f097a DM |
1751 | let kdf = param["kdf"].as_str().unwrap_or("scrypt"); |
1752 | ||
ac716234 DM |
1753 | // we need a TTY to query the new password |
1754 | if !crate::tools::tty::stdin_isatty() { | |
1755 | bail!("unable to change passphrase - no tty"); | |
1756 | } | |
1757 | ||
a8f10f84 | 1758 | let (key, created) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
ac716234 | 1759 | |
181f097a | 1760 | if kdf == "scrypt" { |
ac716234 | 1761 | |
181f097a DM |
1762 | let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?; |
1763 | let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?; | |
ac716234 | 1764 | |
181f097a DM |
1765 | if new_pw != verify_pw { |
1766 | bail!("Password verification fail!"); | |
1767 | } | |
1768 | ||
1769 | if new_pw.len() < 5 { | |
1770 | bail!("Password is too short!"); | |
1771 | } | |
ac716234 | 1772 | |
ab44acff DM |
1773 | let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?; |
1774 | new_key_config.created = created; // keep original value | |
1775 | ||
1776 | store_key_config(&path, true, new_key_config)?; | |
ac716234 | 1777 | |
181f097a DM |
1778 | Ok(Value::Null) |
1779 | } else if kdf == "none" { | |
ab44acff | 1780 | let modified = Local.timestamp(Local::now().timestamp(), 0); |
181f097a DM |
1781 | |
1782 | store_key_config(&path, true, KeyConfig { | |
1783 | kdf: None, | |
ab44acff DM |
1784 | created, // keep original value |
1785 | modified, | |
6d0983db | 1786 | data: key.to_vec(), |
181f097a DM |
1787 | })?; |
1788 | ||
1789 | Ok(Value::Null) | |
1790 | } else { | |
1791 | unreachable!(); | |
1792 | } | |
f2401311 DM |
1793 | } |
1794 | ||
1795 | fn key_mgmt_cli() -> CliCommandMap { | |
1796 | ||
255f378a | 1797 | const KDF_SCHEMA: Schema = |
181f097a | 1798 | StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.") |
255f378a DM |
1799 | .format(&ApiStringFormat::Enum(&["scrypt", "none"])) |
1800 | .default("scrypt") | |
1801 | .schema(); | |
1802 | ||
552c2259 | 1803 | #[sortable] |
255f378a DM |
1804 | const API_METHOD_KEY_CREATE: ApiMethod = ApiMethod::new( |
1805 | &ApiHandler::Sync(&key_create), | |
1806 | &ObjectSchema::new( | |
1807 | "Create a new encryption key.", | |
552c2259 | 1808 | &sorted!([ |
255f378a DM |
1809 | ("path", false, &StringSchema::new("File system path.").schema()), |
1810 | ("kdf", true, &KDF_SCHEMA), | |
552c2259 | 1811 | ]), |
255f378a | 1812 | ) |
181f097a | 1813 | ); |
7074a0b3 | 1814 | |
255f378a | 1815 | let key_create_cmd_def = CliCommand::new(&API_METHOD_KEY_CREATE) |
49fddd98 | 1816 | .arg_param(&["path"]) |
9b06db45 | 1817 | .completion_cb("path", tools::complete_file_name); |
f2401311 | 1818 | |
552c2259 | 1819 | #[sortable] |
255f378a DM |
1820 | const API_METHOD_KEY_CHANGE_PASSPHRASE: ApiMethod = ApiMethod::new( |
1821 | &ApiHandler::Sync(&key_change_passphrase), | |
1822 | &ObjectSchema::new( | |
1823 | "Change the passphrase required to decrypt the key.", | |
552c2259 | 1824 | &sorted!([ |
255f378a DM |
1825 | ("path", false, &StringSchema::new("File system path.").schema()), |
1826 | ("kdf", true, &KDF_SCHEMA), | |
552c2259 | 1827 | ]), |
255f378a DM |
1828 | ) |
1829 | ); | |
7074a0b3 | 1830 | |
255f378a | 1831 | let key_change_passphrase_cmd_def = CliCommand::new(&API_METHOD_KEY_CHANGE_PASSPHRASE) |
49fddd98 | 1832 | .arg_param(&["path"]) |
9b06db45 | 1833 | .completion_cb("path", tools::complete_file_name); |
ac716234 | 1834 | |
255f378a DM |
1835 | const API_METHOD_KEY_CREATE_MASTER_KEY: ApiMethod = ApiMethod::new( |
1836 | &ApiHandler::Sync(&key_create_master_key), | |
1837 | &ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.", &[]) | |
1838 | ); | |
7074a0b3 | 1839 | |
255f378a DM |
1840 | let key_create_master_key_cmd_def = CliCommand::new(&API_METHOD_KEY_CREATE_MASTER_KEY); |
1841 | ||
552c2259 | 1842 | #[sortable] |
255f378a DM |
1843 | const API_METHOD_KEY_IMPORT_MASTER_PUBKEY: ApiMethod = ApiMethod::new( |
1844 | &ApiHandler::Sync(&key_import_master_pubkey), | |
1845 | &ObjectSchema::new( | |
1846 | "Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.", | |
552c2259 | 1847 | &sorted!([ ("path", false, &StringSchema::new("File system path.").schema()) ]), |
255f378a DM |
1848 | ) |
1849 | ); | |
7074a0b3 | 1850 | |
255f378a | 1851 | let key_import_master_pubkey_cmd_def = CliCommand::new(&API_METHOD_KEY_IMPORT_MASTER_PUBKEY) |
49fddd98 | 1852 | .arg_param(&["path"]) |
3ea8bfc9 DM |
1853 | .completion_cb("path", tools::complete_file_name); |
1854 | ||
11377a47 | 1855 | CliCommandMap::new() |
48ef3c33 DM |
1856 | .insert("create", key_create_cmd_def) |
1857 | .insert("create-master-key", key_create_master_key_cmd_def) | |
1858 | .insert("import-master-pubkey", key_import_master_pubkey_cmd_def) | |
1859 | .insert("change-passphrase", key_change_passphrase_cmd_def) | |
f2401311 DM |
1860 | } |
1861 | ||
70235f72 CE |
1862 | fn mount( |
1863 | param: Value, | |
1864 | _info: &ApiMethod, | |
1865 | _rpcenv: &mut dyn RpcEnvironment, | |
1866 | ) -> Result<Value, Error> { | |
1867 | let verbose = param["verbose"].as_bool().unwrap_or(false); | |
1868 | if verbose { | |
1869 | // This will stay in foreground with debug output enabled as None is | |
1870 | // passed for the RawFd. | |
1871 | return async_main(mount_do(param, None)); | |
1872 | } | |
1873 | ||
1874 | // Process should be deamonized. | |
1875 | // Make sure to fork before the async runtime is instantiated to avoid troubles. | |
1876 | let pipe = pipe()?; | |
1877 | match fork() { | |
11377a47 | 1878 | Ok(ForkResult::Parent { .. }) => { |
70235f72 CE |
1879 | nix::unistd::close(pipe.1).unwrap(); |
1880 | // Blocks the parent process until we are ready to go in the child | |
1881 | let _res = nix::unistd::read(pipe.0, &mut [0]).unwrap(); | |
1882 | Ok(Value::Null) | |
1883 | } | |
1884 | Ok(ForkResult::Child) => { | |
1885 | nix::unistd::close(pipe.0).unwrap(); | |
1886 | nix::unistd::setsid().unwrap(); | |
1887 | async_main(mount_do(param, Some(pipe.1))) | |
1888 | } | |
1889 | Err(_) => bail!("failed to daemonize process"), | |
1890 | } | |
1891 | } | |
1892 | ||
1893 | async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> { | |
1894 | let repo = extract_repository_from_value(¶m)?; | |
1895 | let archive_name = tools::required_string_param(¶m, "archive-name")?; | |
1896 | let target = tools::required_string_param(¶m, "target")?; | |
1897 | let client = HttpClient::new(repo.host(), repo.user(), None)?; | |
1898 | ||
1899 | record_repository(&repo); | |
1900 | ||
1901 | let path = tools::required_string_param(¶m, "snapshot")?; | |
1902 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { | |
1903 | let group = BackupGroup::parse(path)?; | |
1904 | ||
1905 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); | |
1906 | let result = client.get(&path, Some(json!({ | |
1907 | "backup-type": group.backup_type(), | |
1908 | "backup-id": group.backup_id(), | |
1909 | }))).await?; | |
1910 | ||
1911 | let list = result["data"].as_array().unwrap(); | |
11377a47 | 1912 | if list.is_empty() { |
70235f72 CE |
1913 | bail!("backup group '{}' does not contain any snapshots:", path); |
1914 | } | |
1915 | ||
1916 | let epoch = list[0]["backup-time"].as_i64().unwrap(); | |
1917 | let backup_time = Utc.timestamp(epoch, 0); | |
1918 | (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time) | |
1919 | } else { | |
1920 | let snapshot = BackupDir::parse(path)?; | |
1921 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) | |
1922 | }; | |
1923 | ||
11377a47 | 1924 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); |
70235f72 CE |
1925 | let crypt_config = match keyfile { |
1926 | None => None, | |
1927 | Some(path) => { | |
a8f10f84 | 1928 | let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; |
70235f72 CE |
1929 | Some(Arc::new(CryptConfig::new(key)?)) |
1930 | } | |
1931 | }; | |
1932 | ||
1933 | let server_archive_name = if archive_name.ends_with(".pxar") { | |
1934 | format!("{}.didx", archive_name) | |
1935 | } else { | |
1936 | bail!("Can only mount pxar archives."); | |
1937 | }; | |
1938 | ||
296c50ba DM |
1939 | let client = BackupReader::start( |
1940 | client, | |
1941 | crypt_config.clone(), | |
1942 | repo.store(), | |
1943 | &backup_type, | |
1944 | &backup_id, | |
1945 | backup_time, | |
1946 | true, | |
1947 | ).await?; | |
70235f72 | 1948 | |
f06b820a | 1949 | let manifest = client.download_manifest().await?; |
296c50ba | 1950 | |
70235f72 | 1951 | if server_archive_name.ends_with(".didx") { |
c3d84a22 | 1952 | let index = client.download_dynamic_index(&manifest, &server_archive_name).await?; |
70235f72 CE |
1953 | let most_used = index.find_most_used_chunks(8); |
1954 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
1955 | let reader = BufferedDynamicReader::new(index, chunk_reader); | |
f701d033 | 1956 | let decoder = pxar::Decoder::new(reader)?; |
70235f72 | 1957 | let options = OsStr::new("ro,default_permissions"); |
2a111910 | 1958 | let mut session = pxar::fuse::Session::new(decoder, &options, pipe.is_none()) |
70235f72 CE |
1959 | .map_err(|err| format_err!("pxar mount failed: {}", err))?; |
1960 | ||
1961 | // Mount the session but not call fuse deamonize as this will cause | |
1962 | // issues with the runtime after the fork | |
1963 | let deamonize = false; | |
1964 | session.mount(&Path::new(target), deamonize)?; | |
1965 | ||
1966 | if let Some(pipe) = pipe { | |
1967 | nix::unistd::chdir(Path::new("/")).unwrap(); | |
1968 | // Finish creation of deamon by redirecting filedescriptors. | |
1969 | let nullfd = nix::fcntl::open( | |
1970 | "/dev/null", | |
1971 | nix::fcntl::OFlag::O_RDWR, | |
1972 | nix::sys::stat::Mode::empty(), | |
1973 | ).unwrap(); | |
1974 | nix::unistd::dup2(nullfd, 0).unwrap(); | |
1975 | nix::unistd::dup2(nullfd, 1).unwrap(); | |
1976 | nix::unistd::dup2(nullfd, 2).unwrap(); | |
1977 | if nullfd > 2 { | |
1978 | nix::unistd::close(nullfd).unwrap(); | |
1979 | } | |
1980 | // Signal the parent process that we are done with the setup and it can | |
1981 | // terminate. | |
11377a47 | 1982 | nix::unistd::write(pipe, &[0u8])?; |
70235f72 CE |
1983 | nix::unistd::close(pipe).unwrap(); |
1984 | } | |
1985 | ||
1986 | let multithreaded = true; | |
1987 | session.run_loop(multithreaded)?; | |
1988 | } else { | |
1989 | bail!("unknown archive file extension (expected .pxar)"); | |
1990 | } | |
1991 | ||
1992 | Ok(Value::Null) | |
1993 | } | |
1994 | ||
78d54360 WB |
1995 | #[api( |
1996 | input: { | |
1997 | properties: { | |
1998 | "snapshot": { | |
1999 | type: String, | |
2000 | description: "Group/Snapshot path.", | |
2001 | }, | |
2002 | "archive-name": { | |
2003 | type: String, | |
2004 | description: "Backup archive name.", | |
2005 | }, | |
2006 | "repository": { | |
2007 | optional: true, | |
2008 | schema: REPO_URL_SCHEMA, | |
2009 | }, | |
2010 | "keyfile": { | |
2011 | optional: true, | |
2012 | type: String, | |
2013 | description: "Path to encryption key.", | |
2014 | }, | |
2015 | }, | |
2016 | }, | |
2017 | )] | |
2018 | /// Shell to interactively inspect and restore snapshots. | |
2019 | async fn catalog_shell(param: Value) -> Result<(), Error> { | |
3cf73c4e CE |
2020 | let repo = extract_repository_from_value(¶m)?; |
2021 | let client = HttpClient::new(repo.host(), repo.user(), None)?; | |
2022 | let path = tools::required_string_param(¶m, "snapshot")?; | |
2023 | let archive_name = tools::required_string_param(¶m, "archive-name")?; | |
2024 | ||
2025 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { | |
2026 | let group = BackupGroup::parse(path)?; | |
2027 | ||
2028 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); | |
af9d4afc | 2029 | let mut result = client.get(&path, Some(json!({ |
3cf73c4e CE |
2030 | "backup-type": group.backup_type(), |
2031 | "backup-id": group.backup_id(), | |
2032 | }))).await?; | |
2033 | ||
af9d4afc | 2034 | let mut list: Vec<SnapshotListItem> = serde_json::from_value(result["data"].take())?; |
314bb358 | 2035 | if list.is_empty() { |
3cf73c4e CE |
2036 | bail!("backup group '{}' does not contain any snapshots:", path); |
2037 | } | |
2038 | ||
af9d4afc DM |
2039 | list.sort_unstable_by(|a, b| b.backup_time.cmp(&a.backup_time)); |
2040 | ||
2041 | let backup_time = Utc.timestamp(list[0].backup_time, 0); | |
2042 | ||
3cf73c4e CE |
2043 | (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time) |
2044 | } else { | |
2045 | let snapshot = BackupDir::parse(path)?; | |
2046 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) | |
2047 | }; | |
2048 | ||
2049 | let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p)); | |
2050 | let crypt_config = match keyfile { | |
2051 | None => None, | |
2052 | Some(path) => { | |
2053 | let (key, _) = load_and_decrtypt_key(&path, &get_encryption_key_password)?; | |
2054 | Some(Arc::new(CryptConfig::new(key)?)) | |
2055 | } | |
2056 | }; | |
2057 | ||
2058 | let server_archive_name = if archive_name.ends_with(".pxar") { | |
2059 | format!("{}.didx", archive_name) | |
2060 | } else { | |
2061 | bail!("Can only mount pxar archives."); | |
2062 | }; | |
2063 | ||
2064 | let client = BackupReader::start( | |
2065 | client, | |
2066 | crypt_config.clone(), | |
2067 | repo.store(), | |
2068 | &backup_type, | |
2069 | &backup_id, | |
2070 | backup_time, | |
2071 | true, | |
2072 | ).await?; | |
2073 | ||
2074 | let tmpfile = std::fs::OpenOptions::new() | |
2075 | .write(true) | |
2076 | .read(true) | |
2077 | .custom_flags(libc::O_TMPFILE) | |
2078 | .open("/tmp")?; | |
2079 | ||
2080 | let manifest = client.download_manifest().await?; | |
2081 | ||
2082 | let index = client.download_dynamic_index(&manifest, &server_archive_name).await?; | |
2083 | let most_used = index.find_most_used_chunks(8); | |
2084 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config.clone(), most_used); | |
2085 | let reader = BufferedDynamicReader::new(index, chunk_reader); | |
f701d033 DM |
2086 | let mut decoder = pxar::Decoder::new(reader)?; |
2087 | decoder.set_callback(|path| { | |
2088 | println!("{:?}", path); | |
2089 | Ok(()) | |
2090 | }); | |
3cf73c4e CE |
2091 | |
2092 | let tmpfile = client.download(CATALOG_NAME, tmpfile).await?; | |
2093 | let index = DynamicIndexReader::new(tmpfile) | |
2094 | .map_err(|err| format_err!("unable to read catalog index - {}", err))?; | |
2095 | ||
2096 | // Note: do not use values stored in index (not trusted) - instead, computed them again | |
2097 | let (csum, size) = index.compute_csum(); | |
2098 | manifest.verify_file(CATALOG_NAME, &csum, size)?; | |
2099 | ||
2100 | let most_used = index.find_most_used_chunks(8); | |
2101 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
2102 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); | |
2103 | let mut catalogfile = std::fs::OpenOptions::new() | |
2104 | .write(true) | |
2105 | .read(true) | |
2106 | .custom_flags(libc::O_TMPFILE) | |
2107 | .open("/tmp")?; | |
2108 | ||
2109 | std::io::copy(&mut reader, &mut catalogfile) | |
2110 | .map_err(|err| format_err!("unable to download catalog - {}", err))?; | |
2111 | ||
2112 | catalogfile.seek(SeekFrom::Start(0))?; | |
2113 | let catalog_reader = CatalogReader::new(catalogfile); | |
2114 | let state = Shell::new( | |
2115 | catalog_reader, | |
2116 | &server_archive_name, | |
2117 | decoder, | |
2118 | )?; | |
2119 | ||
2120 | println!("Starting interactive shell"); | |
2121 | state.shell()?; | |
2122 | ||
2123 | record_repository(&repo); | |
2124 | ||
78d54360 | 2125 | Ok(()) |
3cf73c4e CE |
2126 | } |
2127 | ||
1c6ad6ef | 2128 | fn catalog_mgmt_cli() -> CliCommandMap { |
78d54360 | 2129 | let catalog_shell_cmd_def = CliCommand::new(&API_METHOD_CATALOG_SHELL) |
1c6ad6ef DM |
2130 | .arg_param(&["snapshot", "archive-name"]) |
2131 | .completion_cb("repository", complete_repository) | |
0ec9e1b0 | 2132 | .completion_cb("archive-name", complete_pxar_archive_name) |
1c6ad6ef DM |
2133 | .completion_cb("snapshot", complete_group_or_snapshot); |
2134 | ||
1c6ad6ef DM |
2135 | let catalog_dump_cmd_def = CliCommand::new(&API_METHOD_DUMP_CATALOG) |
2136 | .arg_param(&["snapshot"]) | |
2137 | .completion_cb("repository", complete_repository) | |
2138 | .completion_cb("snapshot", complete_backup_snapshot); | |
2139 | ||
2140 | CliCommandMap::new() | |
48ef3c33 DM |
2141 | .insert("dump", catalog_dump_cmd_def) |
2142 | .insert("shell", catalog_shell_cmd_def) | |
1c6ad6ef DM |
2143 | } |
2144 | ||
5830c205 DM |
2145 | #[api( |
2146 | input: { | |
2147 | properties: { | |
2148 | repository: { | |
2149 | schema: REPO_URL_SCHEMA, | |
2150 | optional: true, | |
2151 | }, | |
2152 | limit: { | |
2153 | description: "The maximal number of tasks to list.", | |
2154 | type: Integer, | |
2155 | optional: true, | |
2156 | minimum: 1, | |
2157 | maximum: 1000, | |
2158 | default: 50, | |
2159 | }, | |
2160 | "output-format": { | |
2161 | schema: OUTPUT_FORMAT, | |
2162 | optional: true, | |
2163 | }, | |
2164 | } | |
2165 | } | |
2166 | )] | |
2167 | /// List running server tasks for this repo user | |
d6c4a119 | 2168 | async fn task_list(param: Value) -> Result<Value, Error> { |
5830c205 | 2169 | |
d6c4a119 DM |
2170 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); |
2171 | let repo = extract_repository_from_value(¶m)?; | |
2172 | let client = HttpClient::new(repo.host(), repo.user(), None)?; | |
5830c205 | 2173 | |
d6c4a119 | 2174 | let limit = param["limit"].as_u64().unwrap_or(50) as usize; |
5830c205 | 2175 | |
d6c4a119 DM |
2176 | let args = json!({ |
2177 | "running": true, | |
2178 | "start": 0, | |
2179 | "limit": limit, | |
2180 | "userfilter": repo.user(), | |
2181 | "store": repo.store(), | |
2182 | }); | |
2183 | let result = client.get("api2/json/nodes/localhost/tasks", Some(args)).await?; | |
5830c205 | 2184 | |
d6c4a119 | 2185 | let data = &result["data"]; |
5830c205 | 2186 | |
d6c4a119 DM |
2187 | if output_format == "text" { |
2188 | for item in data.as_array().unwrap() { | |
2189 | println!( | |
2190 | "{} {}", | |
2191 | item["upid"].as_str().unwrap(), | |
2192 | item["status"].as_str().unwrap_or("running"), | |
2193 | ); | |
5830c205 | 2194 | } |
d6c4a119 DM |
2195 | } else { |
2196 | format_and_print_result(data, &output_format); | |
2197 | } | |
5830c205 DM |
2198 | |
2199 | Ok(Value::Null) | |
2200 | } | |
2201 | ||
2202 | #[api( | |
2203 | input: { | |
2204 | properties: { | |
2205 | repository: { | |
2206 | schema: REPO_URL_SCHEMA, | |
2207 | optional: true, | |
2208 | }, | |
2209 | upid: { | |
2210 | schema: UPID_SCHEMA, | |
2211 | }, | |
2212 | } | |
2213 | } | |
2214 | )] | |
2215 | /// Display the task log. | |
d6c4a119 | 2216 | async fn task_log(param: Value) -> Result<Value, Error> { |
5830c205 | 2217 | |
d6c4a119 DM |
2218 | let repo = extract_repository_from_value(¶m)?; |
2219 | let upid = tools::required_string_param(¶m, "upid")?; | |
5830c205 | 2220 | |
d6c4a119 | 2221 | let client = HttpClient::new(repo.host(), repo.user(), None)?; |
5830c205 | 2222 | |
d6c4a119 | 2223 | display_task_log(client, upid, true).await?; |
5830c205 DM |
2224 | |
2225 | Ok(Value::Null) | |
2226 | } | |
2227 | ||
3f1020b7 DM |
2228 | #[api( |
2229 | input: { | |
2230 | properties: { | |
2231 | repository: { | |
2232 | schema: REPO_URL_SCHEMA, | |
2233 | optional: true, | |
2234 | }, | |
2235 | upid: { | |
2236 | schema: UPID_SCHEMA, | |
2237 | }, | |
2238 | } | |
2239 | } | |
2240 | )] | |
2241 | /// Try to stop a specific task. | |
d6c4a119 | 2242 | async fn task_stop(param: Value) -> Result<Value, Error> { |
3f1020b7 | 2243 | |
d6c4a119 DM |
2244 | let repo = extract_repository_from_value(¶m)?; |
2245 | let upid_str = tools::required_string_param(¶m, "upid")?; | |
3f1020b7 | 2246 | |
d6c4a119 | 2247 | let mut client = HttpClient::new(repo.host(), repo.user(), None)?; |
3f1020b7 | 2248 | |
d6c4a119 DM |
2249 | let path = format!("api2/json/nodes/localhost/tasks/{}", upid_str); |
2250 | let _ = client.delete(&path, None).await?; | |
3f1020b7 DM |
2251 | |
2252 | Ok(Value::Null) | |
2253 | } | |
2254 | ||
5830c205 DM |
2255 | fn task_mgmt_cli() -> CliCommandMap { |
2256 | ||
2257 | let task_list_cmd_def = CliCommand::new(&API_METHOD_TASK_LIST) | |
2258 | .completion_cb("repository", complete_repository); | |
2259 | ||
2260 | let task_log_cmd_def = CliCommand::new(&API_METHOD_TASK_LOG) | |
2261 | .arg_param(&["upid"]); | |
2262 | ||
3f1020b7 DM |
2263 | let task_stop_cmd_def = CliCommand::new(&API_METHOD_TASK_STOP) |
2264 | .arg_param(&["upid"]); | |
2265 | ||
5830c205 DM |
2266 | CliCommandMap::new() |
2267 | .insert("log", task_log_cmd_def) | |
2268 | .insert("list", task_list_cmd_def) | |
3f1020b7 | 2269 | .insert("stop", task_stop_cmd_def) |
5830c205 | 2270 | } |
1c6ad6ef | 2271 | |
f2401311 | 2272 | fn main() { |
33d64b81 | 2273 | |
255f378a | 2274 | let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP) |
49fddd98 | 2275 | .arg_param(&["backupspec"]) |
d0a03d40 | 2276 | .completion_cb("repository", complete_repository) |
49811347 | 2277 | .completion_cb("backupspec", complete_backup_source) |
6d0983db | 2278 | .completion_cb("keyfile", tools::complete_file_name) |
49811347 | 2279 | .completion_cb("chunk-size", complete_chunk_size); |
f8838fe9 | 2280 | |
255f378a | 2281 | let upload_log_cmd_def = CliCommand::new(&API_METHOD_UPLOAD_LOG) |
49fddd98 | 2282 | .arg_param(&["snapshot", "logfile"]) |
543a260f | 2283 | .completion_cb("snapshot", complete_backup_snapshot) |
ec34f7eb DM |
2284 | .completion_cb("logfile", tools::complete_file_name) |
2285 | .completion_cb("keyfile", tools::complete_file_name) | |
2286 | .completion_cb("repository", complete_repository); | |
2287 | ||
255f378a | 2288 | let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS) |
d0a03d40 | 2289 | .completion_cb("repository", complete_repository); |
41c039e1 | 2290 | |
255f378a | 2291 | let snapshots_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOTS) |
49fddd98 | 2292 | .arg_param(&["group"]) |
024f11bb | 2293 | .completion_cb("group", complete_backup_group) |
d0a03d40 | 2294 | .completion_cb("repository", complete_repository); |
184f17af | 2295 | |
255f378a | 2296 | let forget_cmd_def = CliCommand::new(&API_METHOD_FORGET_SNAPSHOTS) |
49fddd98 | 2297 | .arg_param(&["snapshot"]) |
b2388518 | 2298 | .completion_cb("repository", complete_repository) |
543a260f | 2299 | .completion_cb("snapshot", complete_backup_snapshot); |
6f62c924 | 2300 | |
255f378a | 2301 | let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION) |
d0a03d40 | 2302 | .completion_cb("repository", complete_repository); |
8cc0d6af | 2303 | |
255f378a | 2304 | let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE) |
49fddd98 | 2305 | .arg_param(&["snapshot", "archive-name", "target"]) |
b2388518 | 2306 | .completion_cb("repository", complete_repository) |
08dc340a DM |
2307 | .completion_cb("snapshot", complete_group_or_snapshot) |
2308 | .completion_cb("archive-name", complete_archive_name) | |
2309 | .completion_cb("target", tools::complete_file_name); | |
9f912493 | 2310 | |
255f378a | 2311 | let files_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOT_FILES) |
49fddd98 | 2312 | .arg_param(&["snapshot"]) |
52c171e4 | 2313 | .completion_cb("repository", complete_repository) |
543a260f | 2314 | .completion_cb("snapshot", complete_backup_snapshot); |
52c171e4 | 2315 | |
255f378a | 2316 | let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE) |
49fddd98 | 2317 | .arg_param(&["group"]) |
9fdc3ef4 | 2318 | .completion_cb("group", complete_backup_group) |
d0a03d40 | 2319 | .completion_cb("repository", complete_repository); |
9f912493 | 2320 | |
255f378a | 2321 | let status_cmd_def = CliCommand::new(&API_METHOD_STATUS) |
34a816cc DM |
2322 | .completion_cb("repository", complete_repository); |
2323 | ||
255f378a | 2324 | let login_cmd_def = CliCommand::new(&API_METHOD_API_LOGIN) |
e240d8be DM |
2325 | .completion_cb("repository", complete_repository); |
2326 | ||
255f378a | 2327 | let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT) |
e240d8be | 2328 | .completion_cb("repository", complete_repository); |
32efac1c | 2329 | |
552c2259 | 2330 | #[sortable] |
255f378a DM |
2331 | const API_METHOD_MOUNT: ApiMethod = ApiMethod::new( |
2332 | &ApiHandler::Sync(&mount), | |
2333 | &ObjectSchema::new( | |
2334 | "Mount pxar archive.", | |
552c2259 | 2335 | &sorted!([ |
255f378a DM |
2336 | ("snapshot", false, &StringSchema::new("Group/Snapshot path.").schema()), |
2337 | ("archive-name", false, &StringSchema::new("Backup archive name.").schema()), | |
2338 | ("target", false, &StringSchema::new("Target directory path.").schema()), | |
2339 | ("repository", true, &REPO_URL_SCHEMA), | |
2340 | ("keyfile", true, &StringSchema::new("Path to encryption key.").schema()), | |
2341 | ("verbose", true, &BooleanSchema::new("Verbose output.").default(false).schema()), | |
552c2259 | 2342 | ]), |
255f378a DM |
2343 | ) |
2344 | ); | |
7074a0b3 | 2345 | |
255f378a | 2346 | let mount_cmd_def = CliCommand::new(&API_METHOD_MOUNT) |
49fddd98 | 2347 | .arg_param(&["snapshot", "archive-name", "target"]) |
70235f72 CE |
2348 | .completion_cb("repository", complete_repository) |
2349 | .completion_cb("snapshot", complete_group_or_snapshot) | |
0ec9e1b0 | 2350 | .completion_cb("archive-name", complete_pxar_archive_name) |
70235f72 | 2351 | .completion_cb("target", tools::complete_file_name); |
e240d8be | 2352 | |
3cf73c4e | 2353 | |
41c039e1 | 2354 | let cmd_def = CliCommandMap::new() |
48ef3c33 DM |
2355 | .insert("backup", backup_cmd_def) |
2356 | .insert("upload-log", upload_log_cmd_def) | |
2357 | .insert("forget", forget_cmd_def) | |
2358 | .insert("garbage-collect", garbage_collect_cmd_def) | |
2359 | .insert("list", list_cmd_def) | |
2360 | .insert("login", login_cmd_def) | |
2361 | .insert("logout", logout_cmd_def) | |
2362 | .insert("prune", prune_cmd_def) | |
2363 | .insert("restore", restore_cmd_def) | |
2364 | .insert("snapshots", snapshots_cmd_def) | |
2365 | .insert("files", files_cmd_def) | |
2366 | .insert("status", status_cmd_def) | |
2367 | .insert("key", key_mgmt_cli()) | |
2368 | .insert("mount", mount_cmd_def) | |
5830c205 DM |
2369 | .insert("catalog", catalog_mgmt_cli()) |
2370 | .insert("task", task_mgmt_cli()); | |
48ef3c33 DM |
2371 | |
2372 | run_cli_command(cmd_def); | |
e9722f8b | 2373 | } |
496a6784 | 2374 | |
e9722f8b | 2375 | fn async_main<F: Future>(fut: F) -> <F as Future>::Output { |
db0cb9ce | 2376 | let mut rt = tokio::runtime::Runtime::new().unwrap(); |
e9722f8b | 2377 | let ret = rt.block_on(fut); |
db0cb9ce WB |
2378 | // This does not exist anymore. We need to actually stop our runaways instead... |
2379 | // rt.shutdown_now(); | |
e9722f8b | 2380 | ret |
ff5d3707 | 2381 | } |