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