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