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