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