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