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