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