]>
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 | |
f5f13ebc | 25 | use serde_json::{json, Value}; |
1c0472e8 | 26 | //use hyper::Body; |
2761d6a4 | 27 | use std::sync::{Arc, Mutex}; |
255f378a | 28 | //use regex::Regex; |
d0a03d40 | 29 | use xdg::BaseDirectories; |
ae0be2dd | 30 | |
5a2df000 | 31 | use futures::*; |
c4ff3dce | 32 | use tokio::sync::mpsc; |
ae0be2dd | 33 | |
a05c0c6f | 34 | const ENV_VAR_PBS_FINGERPRINT: &str = "PBS_FINGERPRINT"; |
d1c65727 | 35 | const ENV_VAR_PBS_PASSWORD: &str = "PBS_PASSWORD"; |
a05c0c6f | 36 | |
33d64b81 | 37 | |
255f378a DM |
38 | const REPO_URL_SCHEMA: Schema = StringSchema::new("Repository URL.") |
39 | .format(&BACKUP_REPO_URL) | |
40 | .max_length(256) | |
41 | .schema(); | |
d0a03d40 | 42 | |
a47a02ae DM |
43 | const KEYFILE_SCHEMA: Schema = StringSchema::new( |
44 | "Path to encryption key. All data will be encrypted using this key.") | |
45 | .schema(); | |
46 | ||
47 | const CHUNK_SIZE_SCHEMA: Schema = IntegerSchema::new( | |
48 | "Chunk size in KB. Must be a power of 2.") | |
49 | .minimum(64) | |
50 | .maximum(4096) | |
51 | .default(4096) | |
52 | .schema(); | |
53 | ||
2665cef7 DM |
54 | fn get_default_repository() -> Option<String> { |
55 | std::env::var("PBS_REPOSITORY").ok() | |
56 | } | |
57 | ||
58 | fn extract_repository_from_value( | |
59 | param: &Value, | |
60 | ) -> Result<BackupRepository, Error> { | |
61 | ||
62 | let repo_url = param["repository"] | |
63 | .as_str() | |
64 | .map(String::from) | |
65 | .or_else(get_default_repository) | |
66 | .ok_or_else(|| format_err!("unable to get (default) repository"))?; | |
67 | ||
68 | let repo: BackupRepository = repo_url.parse()?; | |
69 | ||
70 | Ok(repo) | |
71 | } | |
72 | ||
73 | fn extract_repository_from_map( | |
74 | param: &HashMap<String, String>, | |
75 | ) -> Option<BackupRepository> { | |
76 | ||
77 | param.get("repository") | |
78 | .map(String::from) | |
79 | .or_else(get_default_repository) | |
80 | .and_then(|repo_url| repo_url.parse::<BackupRepository>().ok()) | |
81 | } | |
82 | ||
d0a03d40 DM |
83 | fn record_repository(repo: &BackupRepository) { |
84 | ||
85 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
86 | Ok(v) => v, | |
87 | _ => return, | |
88 | }; | |
89 | ||
90 | // usually $HOME/.cache/proxmox-backup/repo-list | |
91 | let path = match base.place_cache_file("repo-list") { | |
92 | Ok(v) => v, | |
93 | _ => return, | |
94 | }; | |
95 | ||
11377a47 | 96 | let mut data = file_get_json(&path, None).unwrap_or_else(|_| json!({})); |
d0a03d40 DM |
97 | |
98 | let repo = repo.to_string(); | |
99 | ||
100 | data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 }; | |
101 | ||
102 | let mut map = serde_json::map::Map::new(); | |
103 | ||
104 | loop { | |
105 | let mut max_used = 0; | |
106 | let mut max_repo = None; | |
107 | for (repo, count) in data.as_object().unwrap() { | |
108 | if map.contains_key(repo) { continue; } | |
109 | if let Some(count) = count.as_i64() { | |
110 | if count > max_used { | |
111 | max_used = count; | |
112 | max_repo = Some(repo); | |
113 | } | |
114 | } | |
115 | } | |
116 | if let Some(repo) = max_repo { | |
117 | map.insert(repo.to_owned(), json!(max_used)); | |
118 | } else { | |
119 | break; | |
120 | } | |
121 | if map.len() > 10 { // store max. 10 repos | |
122 | break; | |
123 | } | |
124 | } | |
125 | ||
126 | let new_data = json!(map); | |
127 | ||
feaa1ad3 | 128 | let _ = replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new()); |
d0a03d40 DM |
129 | } |
130 | ||
49811347 | 131 | fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
d0a03d40 DM |
132 | |
133 | let mut result = vec![]; | |
134 | ||
135 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
136 | Ok(v) => v, | |
137 | _ => return result, | |
138 | }; | |
139 | ||
140 | // usually $HOME/.cache/proxmox-backup/repo-list | |
141 | let path = match base.place_cache_file("repo-list") { | |
142 | Ok(v) => v, | |
143 | _ => return result, | |
144 | }; | |
145 | ||
11377a47 | 146 | let data = file_get_json(&path, None).unwrap_or_else(|_| json!({})); |
d0a03d40 DM |
147 | |
148 | if let Some(map) = data.as_object() { | |
49811347 | 149 | for (repo, _count) in map { |
d0a03d40 DM |
150 | result.push(repo.to_owned()); |
151 | } | |
152 | } | |
153 | ||
154 | result | |
155 | } | |
156 | ||
d59dbeca DM |
157 | fn connect(server: &str, userid: &str) -> Result<HttpClient, Error> { |
158 | ||
a05c0c6f DM |
159 | let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok(); |
160 | ||
d1c65727 DM |
161 | use std::env::VarError::*; |
162 | let password = match std::env::var(ENV_VAR_PBS_PASSWORD) { | |
163 | Ok(p) => Some(p), | |
164 | Err(NotUnicode(_)) => bail!(format!("{} contains bad characters", ENV_VAR_PBS_PASSWORD)), | |
165 | Err(NotPresent) => None, | |
166 | }; | |
167 | ||
d59dbeca | 168 | let options = HttpClientOptions::new() |
5030b7ce | 169 | .prefix(Some("proxmox-backup".to_string())) |
d1c65727 | 170 | .password(password) |
d59dbeca | 171 | .interactive(true) |
a05c0c6f | 172 | .fingerprint(fingerprint) |
5a74756c | 173 | .fingerprint_cache(true) |
d59dbeca DM |
174 | .ticket_cache(true); |
175 | ||
176 | HttpClient::new(server, userid, options) | |
177 | } | |
178 | ||
d105176f DM |
179 | async fn view_task_result( |
180 | client: HttpClient, | |
181 | result: Value, | |
182 | output_format: &str, | |
183 | ) -> Result<(), Error> { | |
184 | let data = &result["data"]; | |
185 | if output_format == "text" { | |
186 | if let Some(upid) = data.as_str() { | |
187 | display_task_log(client, upid, true).await?; | |
188 | } | |
189 | } else { | |
190 | format_and_print_result(&data, &output_format); | |
191 | } | |
192 | ||
193 | Ok(()) | |
194 | } | |
195 | ||
42af4b8f DM |
196 | async fn api_datastore_list_snapshots( |
197 | client: &HttpClient, | |
198 | store: &str, | |
199 | group: Option<BackupGroup>, | |
f24fc116 | 200 | ) -> Result<Value, Error> { |
42af4b8f DM |
201 | |
202 | let path = format!("api2/json/admin/datastore/{}/snapshots", store); | |
203 | ||
204 | let mut args = json!({}); | |
205 | if let Some(group) = group { | |
206 | args["backup-type"] = group.backup_type().into(); | |
207 | args["backup-id"] = group.backup_id().into(); | |
208 | } | |
209 | ||
210 | let mut result = client.get(&path, Some(args)).await?; | |
211 | ||
f24fc116 | 212 | Ok(result["data"].take()) |
42af4b8f DM |
213 | } |
214 | ||
27c9affb DM |
215 | async fn api_datastore_latest_snapshot( |
216 | client: &HttpClient, | |
217 | store: &str, | |
218 | group: BackupGroup, | |
219 | ) -> Result<(String, String, DateTime<Utc>), Error> { | |
220 | ||
f24fc116 DM |
221 | let list = api_datastore_list_snapshots(client, store, Some(group.clone())).await?; |
222 | let mut list: Vec<SnapshotListItem> = serde_json::from_value(list)?; | |
27c9affb DM |
223 | |
224 | if list.is_empty() { | |
225 | bail!("backup group {:?} does not contain any snapshots.", group.group_path()); | |
226 | } | |
227 | ||
228 | list.sort_unstable_by(|a, b| b.backup_time.cmp(&a.backup_time)); | |
229 | ||
230 | let backup_time = Utc.timestamp(list[0].backup_time, 0); | |
231 | ||
232 | Ok((group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time)) | |
233 | } | |
234 | ||
235 | ||
e9722f8b | 236 | async fn backup_directory<P: AsRef<Path>>( |
cf9271e2 | 237 | client: &BackupWriter, |
17d6979a | 238 | dir_path: P, |
247cdbce | 239 | archive_name: &str, |
36898ffc | 240 | chunk_size: Option<usize>, |
2eeaacb9 | 241 | device_set: Option<HashSet<u64>>, |
219ef0e6 | 242 | verbose: bool, |
5b72c9b4 | 243 | skip_lost_and_found: bool, |
f98ac774 | 244 | crypt_config: Option<Arc<CryptConfig>>, |
f1d99e3f | 245 | catalog: Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>, |
189996cf | 246 | exclude_pattern: Vec<pxar::MatchPattern>, |
6fc053ed | 247 | entries_max: usize, |
2c3891d1 | 248 | ) -> Result<BackupStats, Error> { |
33d64b81 | 249 | |
6fc053ed CE |
250 | let pxar_stream = PxarBackupStream::open( |
251 | dir_path.as_ref(), | |
252 | device_set, | |
253 | verbose, | |
254 | skip_lost_and_found, | |
255 | catalog, | |
189996cf | 256 | exclude_pattern, |
6fc053ed CE |
257 | entries_max, |
258 | )?; | |
e9722f8b | 259 | let mut chunk_stream = ChunkStream::new(pxar_stream, chunk_size); |
ff3d3100 | 260 | |
e9722f8b | 261 | let (mut tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks |
5e7a09be | 262 | |
c4ff3dce | 263 | let stream = rx |
e9722f8b | 264 | .map_err(Error::from); |
17d6979a | 265 | |
c4ff3dce | 266 | // spawn chunker inside a separate task so that it can run parallel |
e9722f8b | 267 | tokio::spawn(async move { |
db0cb9ce WB |
268 | while let Some(v) = chunk_stream.next().await { |
269 | let _ = tx.send(v).await; | |
270 | } | |
e9722f8b | 271 | }); |
17d6979a | 272 | |
e9722f8b WB |
273 | let stats = client |
274 | .upload_stream(archive_name, stream, "dynamic", None, crypt_config) | |
275 | .await?; | |
bcd879cf | 276 | |
2c3891d1 | 277 | Ok(stats) |
bcd879cf DM |
278 | } |
279 | ||
e9722f8b | 280 | async fn backup_image<P: AsRef<Path>>( |
cf9271e2 | 281 | client: &BackupWriter, |
6af905c1 DM |
282 | image_path: P, |
283 | archive_name: &str, | |
284 | image_size: u64, | |
36898ffc | 285 | chunk_size: Option<usize>, |
1c0472e8 | 286 | _verbose: bool, |
f98ac774 | 287 | crypt_config: Option<Arc<CryptConfig>>, |
2c3891d1 | 288 | ) -> Result<BackupStats, Error> { |
6af905c1 | 289 | |
6af905c1 DM |
290 | let path = image_path.as_ref().to_owned(); |
291 | ||
e9722f8b | 292 | let file = tokio::fs::File::open(path).await?; |
6af905c1 | 293 | |
db0cb9ce | 294 | let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new()) |
6af905c1 DM |
295 | .map_err(Error::from); |
296 | ||
36898ffc | 297 | let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024)); |
6af905c1 | 298 | |
e9722f8b WB |
299 | let stats = client |
300 | .upload_stream(archive_name, stream, "fixed", Some(image_size), crypt_config) | |
301 | .await?; | |
6af905c1 | 302 | |
2c3891d1 | 303 | Ok(stats) |
6af905c1 DM |
304 | } |
305 | ||
a47a02ae DM |
306 | #[api( |
307 | input: { | |
308 | properties: { | |
309 | repository: { | |
310 | schema: REPO_URL_SCHEMA, | |
311 | optional: true, | |
312 | }, | |
313 | "output-format": { | |
314 | schema: OUTPUT_FORMAT, | |
315 | optional: true, | |
316 | }, | |
317 | } | |
318 | } | |
319 | )] | |
320 | /// List backup groups. | |
321 | async fn list_backup_groups(param: Value) -> Result<Value, Error> { | |
812c6f87 | 322 | |
c81b2b7c DM |
323 | let output_format = get_output_format(¶m); |
324 | ||
2665cef7 | 325 | let repo = extract_repository_from_value(¶m)?; |
812c6f87 | 326 | |
d59dbeca | 327 | let client = connect(repo.host(), repo.user())?; |
812c6f87 | 328 | |
d0a03d40 | 329 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
812c6f87 | 330 | |
8a8a4703 | 331 | let mut result = client.get(&path, None).await?; |
812c6f87 | 332 | |
d0a03d40 DM |
333 | record_repository(&repo); |
334 | ||
c81b2b7c DM |
335 | let render_group_path = |_v: &Value, record: &Value| -> Result<String, Error> { |
336 | let item: GroupListItem = serde_json::from_value(record.to_owned())?; | |
337 | let group = BackupGroup::new(item.backup_type, item.backup_id); | |
338 | Ok(group.group_path().to_str().unwrap().to_owned()) | |
339 | }; | |
812c6f87 | 340 | |
18deda40 DM |
341 | let render_last_backup = |_v: &Value, record: &Value| -> Result<String, Error> { |
342 | let item: GroupListItem = serde_json::from_value(record.to_owned())?; | |
343 | let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.last_backup); | |
344 | Ok(snapshot.relative_path().to_str().unwrap().to_owned()) | |
c81b2b7c | 345 | }; |
812c6f87 | 346 | |
c81b2b7c DM |
347 | let render_files = |_v: &Value, record: &Value| -> Result<String, Error> { |
348 | let item: GroupListItem = serde_json::from_value(record.to_owned())?; | |
4939255f | 349 | Ok(tools::format::render_backup_file_list(&item.files)) |
c81b2b7c | 350 | }; |
812c6f87 | 351 | |
c81b2b7c DM |
352 | let options = default_table_format_options() |
353 | .sortby("backup-type", false) | |
354 | .sortby("backup-id", false) | |
355 | .column(ColumnConfig::new("backup-id").renderer(render_group_path).header("group")) | |
18deda40 DM |
356 | .column( |
357 | ColumnConfig::new("last-backup") | |
358 | .renderer(render_last_backup) | |
359 | .header("last snapshot") | |
360 | .right_align(false) | |
361 | ) | |
c81b2b7c DM |
362 | .column(ColumnConfig::new("backup-count")) |
363 | .column(ColumnConfig::new("files").renderer(render_files)); | |
ad20d198 | 364 | |
c81b2b7c | 365 | let mut data: Value = result["data"].take(); |
ad20d198 | 366 | |
c81b2b7c | 367 | let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_GROUPS; |
812c6f87 | 368 | |
c81b2b7c | 369 | format_and_print_result_full(&mut data, info, &output_format, &options); |
34a816cc | 370 | |
812c6f87 DM |
371 | Ok(Value::Null) |
372 | } | |
373 | ||
a47a02ae DM |
374 | #[api( |
375 | input: { | |
376 | properties: { | |
377 | repository: { | |
378 | schema: REPO_URL_SCHEMA, | |
379 | optional: true, | |
380 | }, | |
381 | group: { | |
382 | type: String, | |
383 | description: "Backup group.", | |
384 | optional: true, | |
385 | }, | |
386 | "output-format": { | |
387 | schema: OUTPUT_FORMAT, | |
388 | optional: true, | |
389 | }, | |
390 | } | |
391 | } | |
392 | )] | |
393 | /// List backup snapshots. | |
394 | async fn list_snapshots(param: Value) -> Result<Value, Error> { | |
184f17af | 395 | |
2665cef7 | 396 | let repo = extract_repository_from_value(¶m)?; |
184f17af | 397 | |
c2043614 | 398 | let output_format = get_output_format(¶m); |
34a816cc | 399 | |
d59dbeca | 400 | let client = connect(repo.host(), repo.user())?; |
184f17af | 401 | |
42af4b8f DM |
402 | let group = if let Some(path) = param["group"].as_str() { |
403 | Some(BackupGroup::parse(path)?) | |
404 | } else { | |
405 | None | |
406 | }; | |
184f17af | 407 | |
f24fc116 | 408 | let mut data = api_datastore_list_snapshots(&client, repo.store(), group).await?; |
184f17af | 409 | |
d0a03d40 DM |
410 | record_repository(&repo); |
411 | ||
f24fc116 DM |
412 | let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> { |
413 | let item: SnapshotListItem = serde_json::from_value(record.to_owned())?; | |
af9d4afc | 414 | let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time); |
f24fc116 DM |
415 | Ok(snapshot.relative_path().to_str().unwrap().to_owned()) |
416 | }; | |
184f17af | 417 | |
f24fc116 DM |
418 | let render_files = |_v: &Value, record: &Value| -> Result<String, Error> { |
419 | let item: SnapshotListItem = serde_json::from_value(record.to_owned())?; | |
4939255f | 420 | Ok(tools::format::render_backup_file_list(&item.files)) |
f24fc116 DM |
421 | }; |
422 | ||
c2043614 | 423 | let options = default_table_format_options() |
f24fc116 DM |
424 | .sortby("backup-type", false) |
425 | .sortby("backup-id", false) | |
426 | .sortby("backup-time", false) | |
427 | .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot")) | |
428 | .column(ColumnConfig::new("size")) | |
429 | .column(ColumnConfig::new("files").renderer(render_files)) | |
430 | ; | |
431 | ||
432 | let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOTS; | |
433 | ||
434 | format_and_print_result_full(&mut data, info, &output_format, &options); | |
184f17af DM |
435 | |
436 | Ok(Value::Null) | |
437 | } | |
438 | ||
a47a02ae DM |
439 | #[api( |
440 | input: { | |
441 | properties: { | |
442 | repository: { | |
443 | schema: REPO_URL_SCHEMA, | |
444 | optional: true, | |
445 | }, | |
446 | snapshot: { | |
447 | type: String, | |
448 | description: "Snapshot path.", | |
449 | }, | |
450 | } | |
451 | } | |
452 | )] | |
453 | /// Forget (remove) backup snapshots. | |
454 | async fn forget_snapshots(param: Value) -> Result<Value, Error> { | |
6f62c924 | 455 | |
2665cef7 | 456 | let repo = extract_repository_from_value(¶m)?; |
6f62c924 DM |
457 | |
458 | let path = tools::required_string_param(¶m, "snapshot")?; | |
459 | let snapshot = BackupDir::parse(path)?; | |
460 | ||
d59dbeca | 461 | let mut client = connect(repo.host(), repo.user())?; |
6f62c924 | 462 | |
9e391bb7 | 463 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
6f62c924 | 464 | |
8a8a4703 DM |
465 | let result = client.delete(&path, Some(json!({ |
466 | "backup-type": snapshot.group().backup_type(), | |
467 | "backup-id": snapshot.group().backup_id(), | |
468 | "backup-time": snapshot.backup_time().timestamp(), | |
469 | }))).await?; | |
6f62c924 | 470 | |
d0a03d40 DM |
471 | record_repository(&repo); |
472 | ||
6f62c924 DM |
473 | Ok(result) |
474 | } | |
475 | ||
a47a02ae DM |
476 | #[api( |
477 | input: { | |
478 | properties: { | |
479 | repository: { | |
480 | schema: REPO_URL_SCHEMA, | |
481 | optional: true, | |
482 | }, | |
483 | } | |
484 | } | |
485 | )] | |
486 | /// Try to login. If successful, store ticket. | |
487 | async fn api_login(param: Value) -> Result<Value, Error> { | |
e240d8be DM |
488 | |
489 | let repo = extract_repository_from_value(¶m)?; | |
490 | ||
d59dbeca | 491 | let client = connect(repo.host(), repo.user())?; |
8a8a4703 | 492 | client.login().await?; |
e240d8be DM |
493 | |
494 | record_repository(&repo); | |
495 | ||
496 | Ok(Value::Null) | |
497 | } | |
498 | ||
a47a02ae DM |
499 | #[api( |
500 | input: { | |
501 | properties: { | |
502 | repository: { | |
503 | schema: REPO_URL_SCHEMA, | |
504 | optional: true, | |
505 | }, | |
506 | } | |
507 | } | |
508 | )] | |
509 | /// Logout (delete stored ticket). | |
510 | fn api_logout(param: Value) -> Result<Value, Error> { | |
e240d8be DM |
511 | |
512 | let repo = extract_repository_from_value(¶m)?; | |
513 | ||
5030b7ce | 514 | delete_ticket_info("proxmox-backup", repo.host(), repo.user())?; |
e240d8be DM |
515 | |
516 | Ok(Value::Null) | |
517 | } | |
518 | ||
a47a02ae DM |
519 | #[api( |
520 | input: { | |
521 | properties: { | |
522 | repository: { | |
523 | schema: REPO_URL_SCHEMA, | |
524 | optional: true, | |
525 | }, | |
526 | snapshot: { | |
527 | type: String, | |
528 | description: "Snapshot path.", | |
529 | }, | |
530 | } | |
531 | } | |
532 | )] | |
533 | /// Dump catalog. | |
534 | async fn dump_catalog(param: Value) -> Result<Value, Error> { | |
9049a8cf DM |
535 | |
536 | let repo = extract_repository_from_value(¶m)?; | |
537 | ||
538 | let path = tools::required_string_param(¶m, "snapshot")?; | |
539 | let snapshot = BackupDir::parse(path)?; | |
540 | ||
11377a47 | 541 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); |
9049a8cf DM |
542 | |
543 | let crypt_config = match keyfile { | |
544 | None => None, | |
545 | Some(path) => { | |
6d20a29d | 546 | let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?; |
9025312a | 547 | Some(Arc::new(CryptConfig::new(key)?)) |
9049a8cf DM |
548 | } |
549 | }; | |
550 | ||
d59dbeca | 551 | let client = connect(repo.host(), repo.user())?; |
9049a8cf | 552 | |
8a8a4703 DM |
553 | let client = BackupReader::start( |
554 | client, | |
555 | crypt_config.clone(), | |
556 | repo.store(), | |
557 | &snapshot.group().backup_type(), | |
558 | &snapshot.group().backup_id(), | |
559 | snapshot.backup_time(), | |
560 | true, | |
561 | ).await?; | |
9049a8cf | 562 | |
8a8a4703 | 563 | let manifest = client.download_manifest().await?; |
d2267b11 | 564 | |
8a8a4703 | 565 | let index = client.download_dynamic_index(&manifest, CATALOG_NAME).await?; |
bf6e3217 | 566 | |
8a8a4703 | 567 | let most_used = index.find_most_used_chunks(8); |
bf6e3217 | 568 | |
8a8a4703 | 569 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); |
bf6e3217 | 570 | |
8a8a4703 | 571 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); |
9049a8cf | 572 | |
8a8a4703 DM |
573 | let mut catalogfile = std::fs::OpenOptions::new() |
574 | .write(true) | |
575 | .read(true) | |
576 | .custom_flags(libc::O_TMPFILE) | |
577 | .open("/tmp")?; | |
d2267b11 | 578 | |
8a8a4703 DM |
579 | std::io::copy(&mut reader, &mut catalogfile) |
580 | .map_err(|err| format_err!("unable to download catalog - {}", err))?; | |
a84ef4c2 | 581 | |
8a8a4703 | 582 | catalogfile.seek(SeekFrom::Start(0))?; |
9049a8cf | 583 | |
8a8a4703 | 584 | let mut catalog_reader = CatalogReader::new(catalogfile); |
9049a8cf | 585 | |
8a8a4703 | 586 | catalog_reader.dump()?; |
e9722f8b | 587 | |
8a8a4703 | 588 | record_repository(&repo); |
9049a8cf DM |
589 | |
590 | Ok(Value::Null) | |
591 | } | |
592 | ||
a47a02ae DM |
593 | #[api( |
594 | input: { | |
595 | properties: { | |
596 | repository: { | |
597 | schema: REPO_URL_SCHEMA, | |
598 | optional: true, | |
599 | }, | |
600 | snapshot: { | |
601 | type: String, | |
602 | description: "Snapshot path.", | |
603 | }, | |
604 | "output-format": { | |
605 | schema: OUTPUT_FORMAT, | |
606 | optional: true, | |
607 | }, | |
608 | } | |
609 | } | |
610 | )] | |
611 | /// List snapshot files. | |
612 | async fn list_snapshot_files(param: Value) -> Result<Value, Error> { | |
52c171e4 DM |
613 | |
614 | let repo = extract_repository_from_value(¶m)?; | |
615 | ||
616 | let path = tools::required_string_param(¶m, "snapshot")?; | |
617 | let snapshot = BackupDir::parse(path)?; | |
618 | ||
c2043614 | 619 | let output_format = get_output_format(¶m); |
52c171e4 | 620 | |
d59dbeca | 621 | let client = connect(repo.host(), repo.user())?; |
52c171e4 DM |
622 | |
623 | let path = format!("api2/json/admin/datastore/{}/files", repo.store()); | |
624 | ||
8a8a4703 DM |
625 | let mut result = client.get(&path, Some(json!({ |
626 | "backup-type": snapshot.group().backup_type(), | |
627 | "backup-id": snapshot.group().backup_id(), | |
628 | "backup-time": snapshot.backup_time().timestamp(), | |
629 | }))).await?; | |
52c171e4 DM |
630 | |
631 | record_repository(&repo); | |
632 | ||
ea5f547f | 633 | let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOT_FILES; |
52c171e4 | 634 | |
ea5f547f DM |
635 | let mut data: Value = result["data"].take(); |
636 | ||
c2043614 | 637 | let options = default_table_format_options(); |
ea5f547f DM |
638 | |
639 | format_and_print_result_full(&mut data, info, &output_format, &options); | |
52c171e4 DM |
640 | |
641 | Ok(Value::Null) | |
642 | } | |
643 | ||
a47a02ae | 644 | #[api( |
94913f35 | 645 | input: { |
a47a02ae DM |
646 | properties: { |
647 | repository: { | |
648 | schema: REPO_URL_SCHEMA, | |
649 | optional: true, | |
650 | }, | |
94913f35 DM |
651 | "output-format": { |
652 | schema: OUTPUT_FORMAT, | |
653 | optional: true, | |
654 | }, | |
655 | }, | |
656 | }, | |
a47a02ae DM |
657 | )] |
658 | /// Start garbage collection for a specific repository. | |
659 | async fn start_garbage_collection(param: Value) -> Result<Value, Error> { | |
8cc0d6af | 660 | |
2665cef7 | 661 | let repo = extract_repository_from_value(¶m)?; |
c2043614 DM |
662 | |
663 | let output_format = get_output_format(¶m); | |
8cc0d6af | 664 | |
d59dbeca | 665 | let mut client = connect(repo.host(), repo.user())?; |
8cc0d6af | 666 | |
d0a03d40 | 667 | let path = format!("api2/json/admin/datastore/{}/gc", repo.store()); |
8cc0d6af | 668 | |
8a8a4703 | 669 | let result = client.post(&path, None).await?; |
8cc0d6af | 670 | |
8a8a4703 | 671 | record_repository(&repo); |
d0a03d40 | 672 | |
8a8a4703 | 673 | view_task_result(client, result, &output_format).await?; |
e5f7def4 | 674 | |
e5f7def4 | 675 | Ok(Value::Null) |
8cc0d6af | 676 | } |
33d64b81 | 677 | |
bf6e3217 DM |
678 | fn spawn_catalog_upload( |
679 | client: Arc<BackupWriter>, | |
680 | crypt_config: Option<Arc<CryptConfig>>, | |
681 | ) -> Result< | |
682 | ( | |
f1d99e3f | 683 | Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>, |
bf6e3217 DM |
684 | tokio::sync::oneshot::Receiver<Result<BackupStats, Error>> |
685 | ), Error> | |
686 | { | |
f1d99e3f DM |
687 | let (catalog_tx, catalog_rx) = std::sync::mpsc::sync_channel(10); // allow to buffer 10 writes |
688 | let catalog_stream = crate::tools::StdChannelStream(catalog_rx); | |
bf6e3217 DM |
689 | let catalog_chunk_size = 512*1024; |
690 | let catalog_chunk_stream = ChunkStream::new(catalog_stream, Some(catalog_chunk_size)); | |
691 | ||
f1d99e3f | 692 | let catalog = Arc::new(Mutex::new(CatalogWriter::new(crate::tools::StdChannelWriter::new(catalog_tx))?)); |
bf6e3217 DM |
693 | |
694 | let (catalog_result_tx, catalog_result_rx) = tokio::sync::oneshot::channel(); | |
695 | ||
696 | tokio::spawn(async move { | |
697 | let catalog_upload_result = client | |
698 | .upload_stream(CATALOG_NAME, catalog_chunk_stream, "dynamic", None, crypt_config) | |
699 | .await; | |
700 | ||
701 | if let Err(ref err) = catalog_upload_result { | |
702 | eprintln!("catalog upload error - {}", err); | |
703 | client.cancel(); | |
704 | } | |
705 | ||
706 | let _ = catalog_result_tx.send(catalog_upload_result); | |
707 | }); | |
708 | ||
709 | Ok((catalog, catalog_result_rx)) | |
710 | } | |
711 | ||
a47a02ae DM |
712 | #[api( |
713 | input: { | |
714 | properties: { | |
715 | backupspec: { | |
716 | type: Array, | |
717 | description: "List of backup source specifications ([<label.ext>:<path>] ...)", | |
718 | items: { | |
719 | schema: BACKUP_SOURCE_SCHEMA, | |
720 | } | |
721 | }, | |
722 | repository: { | |
723 | schema: REPO_URL_SCHEMA, | |
724 | optional: true, | |
725 | }, | |
726 | "include-dev": { | |
727 | description: "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.", | |
728 | optional: true, | |
729 | items: { | |
730 | type: String, | |
731 | description: "Path to file.", | |
732 | } | |
733 | }, | |
734 | keyfile: { | |
735 | schema: KEYFILE_SCHEMA, | |
736 | optional: true, | |
737 | }, | |
738 | "skip-lost-and-found": { | |
739 | type: Boolean, | |
740 | description: "Skip lost+found directory.", | |
741 | optional: true, | |
742 | }, | |
743 | "backup-type": { | |
744 | schema: BACKUP_TYPE_SCHEMA, | |
745 | optional: true, | |
746 | }, | |
747 | "backup-id": { | |
748 | schema: BACKUP_ID_SCHEMA, | |
749 | optional: true, | |
750 | }, | |
751 | "backup-time": { | |
752 | schema: BACKUP_TIME_SCHEMA, | |
753 | optional: true, | |
754 | }, | |
755 | "chunk-size": { | |
756 | schema: CHUNK_SIZE_SCHEMA, | |
757 | optional: true, | |
758 | }, | |
189996cf CE |
759 | "exclude": { |
760 | type: Array, | |
761 | description: "List of paths or patterns for matching files to exclude.", | |
762 | optional: true, | |
763 | items: { | |
764 | type: String, | |
765 | description: "Path or match pattern.", | |
766 | } | |
767 | }, | |
6fc053ed CE |
768 | "entries-max": { |
769 | type: Integer, | |
770 | description: "Max number of entries to hold in memory.", | |
771 | optional: true, | |
772 | default: pxar::ENCODER_MAX_ENTRIES as isize, | |
773 | }, | |
e02c3d46 DM |
774 | "verbose": { |
775 | type: Boolean, | |
776 | description: "Verbose output.", | |
777 | optional: true, | |
778 | }, | |
a47a02ae DM |
779 | } |
780 | } | |
781 | )] | |
782 | /// Create (host) backup. | |
783 | async fn create_backup( | |
6049b71f DM |
784 | param: Value, |
785 | _info: &ApiMethod, | |
dd5495d6 | 786 | _rpcenv: &mut dyn RpcEnvironment, |
6049b71f | 787 | ) -> Result<Value, Error> { |
ff5d3707 | 788 | |
2665cef7 | 789 | let repo = extract_repository_from_value(¶m)?; |
ae0be2dd DM |
790 | |
791 | let backupspec_list = tools::required_array_param(¶m, "backupspec")?; | |
a914a774 | 792 | |
eed6db39 DM |
793 | let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false); |
794 | ||
5b72c9b4 DM |
795 | let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false); |
796 | ||
219ef0e6 DM |
797 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
798 | ||
ca5d0b61 DM |
799 | let backup_time_opt = param["backup-time"].as_i64(); |
800 | ||
36898ffc | 801 | let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize); |
2d9d143a | 802 | |
247cdbce DM |
803 | if let Some(size) = chunk_size_opt { |
804 | verify_chunk_size(size)?; | |
2d9d143a DM |
805 | } |
806 | ||
11377a47 | 807 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); |
6d0983db | 808 | |
f69adc81 | 809 | let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename()); |
fba30411 | 810 | |
bbf9e7e9 | 811 | let backup_type = param["backup-type"].as_str().unwrap_or("host"); |
ca5d0b61 | 812 | |
2eeaacb9 DM |
813 | let include_dev = param["include-dev"].as_array(); |
814 | ||
6fc053ed CE |
815 | let entries_max = param["entries-max"].as_u64().unwrap_or(pxar::ENCODER_MAX_ENTRIES as u64); |
816 | ||
189996cf CE |
817 | let empty = Vec::new(); |
818 | let arg_pattern = param["exclude"].as_array().unwrap_or(&empty); | |
819 | ||
820 | let mut pattern_list = Vec::with_capacity(arg_pattern.len()); | |
821 | for s in arg_pattern { | |
822 | let l = s.as_str().ok_or_else(|| format_err!("Invalid pattern string slice"))?; | |
823 | let p = pxar::MatchPattern::from_line(l.as_bytes())? | |
824 | .ok_or_else(|| format_err!("Invalid match pattern in arguments"))?; | |
825 | pattern_list.push(p); | |
826 | } | |
827 | ||
2eeaacb9 DM |
828 | let mut devices = if all_file_systems { None } else { Some(HashSet::new()) }; |
829 | ||
830 | if let Some(include_dev) = include_dev { | |
831 | if all_file_systems { | |
832 | bail!("option 'all-file-systems' conflicts with option 'include-dev'"); | |
833 | } | |
834 | ||
835 | let mut set = HashSet::new(); | |
836 | for path in include_dev { | |
837 | let path = path.as_str().unwrap(); | |
838 | let stat = nix::sys::stat::stat(path) | |
839 | .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?; | |
840 | set.insert(stat.st_dev); | |
841 | } | |
842 | devices = Some(set); | |
843 | } | |
844 | ||
ae0be2dd | 845 | let mut upload_list = vec![]; |
a914a774 | 846 | |
bf6e3217 DM |
847 | let mut upload_catalog = false; |
848 | ||
ae0be2dd | 849 | for backupspec in backupspec_list { |
7cc3473a DM |
850 | let spec = parse_backup_specification(backupspec.as_str().unwrap())?; |
851 | let filename = &spec.config_string; | |
852 | let target = &spec.archive_name; | |
bcd879cf | 853 | |
eb1804c5 DM |
854 | use std::os::unix::fs::FileTypeExt; |
855 | ||
3fa71727 CE |
856 | let metadata = std::fs::metadata(filename) |
857 | .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?; | |
eb1804c5 | 858 | let file_type = metadata.file_type(); |
23bb8780 | 859 | |
7cc3473a DM |
860 | match spec.spec_type { |
861 | BackupSpecificationType::PXAR => { | |
ec8a9bb9 DM |
862 | if !file_type.is_dir() { |
863 | bail!("got unexpected file type (expected directory)"); | |
864 | } | |
7cc3473a | 865 | upload_list.push((BackupSpecificationType::PXAR, filename.to_owned(), format!("{}.didx", target), 0)); |
bf6e3217 | 866 | upload_catalog = true; |
ec8a9bb9 | 867 | } |
7cc3473a | 868 | BackupSpecificationType::IMAGE => { |
ec8a9bb9 DM |
869 | if !(file_type.is_file() || file_type.is_block_device()) { |
870 | bail!("got unexpected file type (expected file or block device)"); | |
871 | } | |
eb1804c5 | 872 | |
e18a6c9e | 873 | let size = image_size(&PathBuf::from(filename))?; |
23bb8780 | 874 | |
ec8a9bb9 | 875 | if size == 0 { bail!("got zero-sized file '{}'", filename); } |
ae0be2dd | 876 | |
7cc3473a | 877 | upload_list.push((BackupSpecificationType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size)); |
ec8a9bb9 | 878 | } |
7cc3473a | 879 | BackupSpecificationType::CONFIG => { |
ec8a9bb9 DM |
880 | if !file_type.is_file() { |
881 | bail!("got unexpected file type (expected regular file)"); | |
882 | } | |
7cc3473a | 883 | upload_list.push((BackupSpecificationType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len())); |
ec8a9bb9 | 884 | } |
7cc3473a | 885 | BackupSpecificationType::LOGFILE => { |
79679c2d DM |
886 | if !file_type.is_file() { |
887 | bail!("got unexpected file type (expected regular file)"); | |
888 | } | |
7cc3473a | 889 | upload_list.push((BackupSpecificationType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len())); |
ec8a9bb9 | 890 | } |
ae0be2dd DM |
891 | } |
892 | } | |
893 | ||
11377a47 | 894 | let backup_time = Utc.timestamp(backup_time_opt.unwrap_or_else(|| Utc::now().timestamp()), 0); |
ae0be2dd | 895 | |
d59dbeca | 896 | let client = connect(repo.host(), repo.user())?; |
d0a03d40 DM |
897 | record_repository(&repo); |
898 | ||
ca5d0b61 DM |
899 | println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time)); |
900 | ||
f69adc81 | 901 | println!("Client name: {}", proxmox::tools::nodename()); |
ca5d0b61 DM |
902 | |
903 | let start_time = Local::now(); | |
904 | ||
7a6cfbd9 | 905 | println!("Starting protocol: {}", start_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false)); |
51144821 | 906 | |
bb823140 DM |
907 | let (crypt_config, rsa_encrypted_key) = match keyfile { |
908 | None => (None, None), | |
6d0983db | 909 | Some(path) => { |
6d20a29d | 910 | let (key, created) = load_and_decrypt_key(&path, &get_encryption_key_password)?; |
bb823140 DM |
911 | |
912 | let crypt_config = CryptConfig::new(key)?; | |
913 | ||
914 | let path = master_pubkey_path()?; | |
915 | if path.exists() { | |
e18a6c9e | 916 | let pem_data = file_get_contents(&path)?; |
bb823140 DM |
917 | let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?; |
918 | let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?; | |
919 | (Some(Arc::new(crypt_config)), Some(enc_key)) | |
920 | } else { | |
921 | (Some(Arc::new(crypt_config)), None) | |
922 | } | |
6d0983db DM |
923 | } |
924 | }; | |
f98ac774 | 925 | |
8a8a4703 DM |
926 | let client = BackupWriter::start( |
927 | client, | |
928 | repo.store(), | |
929 | backup_type, | |
930 | &backup_id, | |
931 | backup_time, | |
932 | verbose, | |
933 | ).await?; | |
934 | ||
935 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time.timestamp()); | |
936 | let mut manifest = BackupManifest::new(snapshot); | |
937 | ||
938 | let (catalog, catalog_result_rx) = spawn_catalog_upload(client.clone(), crypt_config.clone())?; | |
939 | ||
940 | for (backup_type, filename, target, size) in upload_list { | |
941 | match backup_type { | |
7cc3473a | 942 | BackupSpecificationType::CONFIG => { |
8a8a4703 DM |
943 | println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target); |
944 | let stats = client | |
945 | .upload_blob_from_file(&filename, &target, crypt_config.clone(), true) | |
946 | .await?; | |
1e8da0a7 | 947 | manifest.add_file(target, stats.size, stats.csum)?; |
8a8a4703 | 948 | } |
7cc3473a | 949 | BackupSpecificationType::LOGFILE => { // fixme: remove - not needed anymore ? |
8a8a4703 DM |
950 | println!("Upload log file '{}' to '{:?}' as {}", filename, repo, target); |
951 | let stats = client | |
952 | .upload_blob_from_file(&filename, &target, crypt_config.clone(), true) | |
953 | .await?; | |
1e8da0a7 | 954 | manifest.add_file(target, stats.size, stats.csum)?; |
8a8a4703 | 955 | } |
7cc3473a | 956 | BackupSpecificationType::PXAR => { |
8a8a4703 DM |
957 | println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target); |
958 | catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?; | |
959 | let stats = backup_directory( | |
960 | &client, | |
961 | &filename, | |
962 | &target, | |
963 | chunk_size_opt, | |
964 | devices.clone(), | |
965 | verbose, | |
966 | skip_lost_and_found, | |
967 | crypt_config.clone(), | |
968 | catalog.clone(), | |
189996cf | 969 | pattern_list.clone(), |
6fc053ed | 970 | entries_max as usize, |
8a8a4703 | 971 | ).await?; |
1e8da0a7 | 972 | manifest.add_file(target, stats.size, stats.csum)?; |
8a8a4703 DM |
973 | catalog.lock().unwrap().end_directory()?; |
974 | } | |
7cc3473a | 975 | BackupSpecificationType::IMAGE => { |
8a8a4703 DM |
976 | println!("Upload image '{}' to '{:?}' as {}", filename, repo, target); |
977 | let stats = backup_image( | |
978 | &client, | |
979 | &filename, | |
980 | &target, | |
981 | size, | |
982 | chunk_size_opt, | |
983 | verbose, | |
984 | crypt_config.clone(), | |
985 | ).await?; | |
1e8da0a7 | 986 | manifest.add_file(target, stats.size, stats.csum)?; |
6af905c1 DM |
987 | } |
988 | } | |
8a8a4703 | 989 | } |
4818c8b6 | 990 | |
8a8a4703 DM |
991 | // finalize and upload catalog |
992 | if upload_catalog { | |
993 | let mutex = Arc::try_unwrap(catalog) | |
994 | .map_err(|_| format_err!("unable to get catalog (still used)"))?; | |
995 | let mut catalog = mutex.into_inner().unwrap(); | |
bf6e3217 | 996 | |
8a8a4703 | 997 | catalog.finish()?; |
2761d6a4 | 998 | |
8a8a4703 | 999 | drop(catalog); // close upload stream |
2761d6a4 | 1000 | |
8a8a4703 | 1001 | let stats = catalog_result_rx.await??; |
9d135fe6 | 1002 | |
1e8da0a7 | 1003 | manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum)?; |
8a8a4703 | 1004 | } |
2761d6a4 | 1005 | |
8a8a4703 DM |
1006 | if let Some(rsa_encrypted_key) = rsa_encrypted_key { |
1007 | let target = "rsa-encrypted.key"; | |
1008 | println!("Upload RSA encoded key to '{:?}' as {}", repo, target); | |
1009 | let stats = client | |
1010 | .upload_blob_from_data(rsa_encrypted_key, target, None, false, false) | |
1011 | .await?; | |
1e8da0a7 | 1012 | manifest.add_file(format!("{}.blob", target), stats.size, stats.csum)?; |
8a8a4703 DM |
1013 | |
1014 | // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t | |
1015 | /* | |
1016 | let mut buffer2 = vec![0u8; rsa.size() as usize]; | |
1017 | let pem_data = file_get_contents("master-private.pem")?; | |
1018 | let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?; | |
1019 | let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?; | |
1020 | println!("TEST {} {:?}", len, buffer2); | |
1021 | */ | |
1022 | } | |
9f46c7de | 1023 | |
8a8a4703 DM |
1024 | // create manifest (index.json) |
1025 | let manifest = manifest.into_json(); | |
2c3891d1 | 1026 | |
8a8a4703 DM |
1027 | println!("Upload index.json to '{:?}'", repo); |
1028 | let manifest = serde_json::to_string_pretty(&manifest)?.into(); | |
1029 | client | |
1030 | .upload_blob_from_data(manifest, MANIFEST_BLOB_NAME, crypt_config.clone(), true, true) | |
1031 | .await?; | |
2c3891d1 | 1032 | |
8a8a4703 | 1033 | client.finish().await?; |
c4ff3dce | 1034 | |
8a8a4703 DM |
1035 | let end_time = Local::now(); |
1036 | let elapsed = end_time.signed_duration_since(start_time); | |
1037 | println!("Duration: {}", elapsed); | |
3ec3ec3f | 1038 | |
8a8a4703 | 1039 | println!("End Time: {}", end_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false)); |
3d5c11e5 | 1040 | |
8a8a4703 | 1041 | Ok(Value::Null) |
f98ea63d DM |
1042 | } |
1043 | ||
d0a03d40 | 1044 | fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
f98ea63d DM |
1045 | |
1046 | let mut result = vec![]; | |
1047 | ||
1048 | let data: Vec<&str> = arg.splitn(2, ':').collect(); | |
1049 | ||
bff11030 | 1050 | if data.len() != 2 { |
8968258b DM |
1051 | result.push(String::from("root.pxar:/")); |
1052 | result.push(String::from("etc.pxar:/etc")); | |
bff11030 DM |
1053 | return result; |
1054 | } | |
f98ea63d | 1055 | |
496a6784 | 1056 | let files = tools::complete_file_name(data[1], param); |
f98ea63d DM |
1057 | |
1058 | for file in files { | |
1059 | result.push(format!("{}:{}", data[0], file)); | |
1060 | } | |
1061 | ||
1062 | result | |
ff5d3707 | 1063 | } |
1064 | ||
88892ea8 DM |
1065 | fn dump_image<W: Write>( |
1066 | client: Arc<BackupReader>, | |
1067 | crypt_config: Option<Arc<CryptConfig>>, | |
1068 | index: FixedIndexReader, | |
1069 | mut writer: W, | |
fd04ca7a | 1070 | verbose: bool, |
88892ea8 DM |
1071 | ) -> Result<(), Error> { |
1072 | ||
1073 | let most_used = index.find_most_used_chunks(8); | |
1074 | ||
1075 | let mut chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
1076 | ||
1077 | // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy | |
1078 | // and thus slows down reading. Instead, directly use RemoteChunkReader | |
fd04ca7a DM |
1079 | let mut per = 0; |
1080 | let mut bytes = 0; | |
1081 | let start_time = std::time::Instant::now(); | |
1082 | ||
88892ea8 DM |
1083 | for pos in 0..index.index_count() { |
1084 | let digest = index.index_digest(pos).unwrap(); | |
1085 | let raw_data = chunk_reader.read_chunk(&digest)?; | |
1086 | writer.write_all(&raw_data)?; | |
fd04ca7a DM |
1087 | bytes += raw_data.len(); |
1088 | if verbose { | |
1089 | let next_per = ((pos+1)*100)/index.index_count(); | |
1090 | if per != next_per { | |
1091 | eprintln!("progress {}% (read {} bytes, duration {} sec)", | |
1092 | next_per, bytes, start_time.elapsed().as_secs()); | |
1093 | per = next_per; | |
1094 | } | |
1095 | } | |
88892ea8 DM |
1096 | } |
1097 | ||
fd04ca7a DM |
1098 | let end_time = std::time::Instant::now(); |
1099 | let elapsed = end_time.duration_since(start_time); | |
1100 | eprintln!("restore image complete (bytes={}, duration={:.2}s, speed={:.2}MB/s)", | |
1101 | bytes, | |
1102 | elapsed.as_secs_f64(), | |
1103 | bytes as f64/(1024.0*1024.0*elapsed.as_secs_f64()) | |
1104 | ); | |
1105 | ||
1106 | ||
88892ea8 DM |
1107 | Ok(()) |
1108 | } | |
1109 | ||
dc155e9b | 1110 | fn parse_archive_type(name: &str) -> (String, ArchiveType) { |
2d32fe2c TL |
1111 | if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") { |
1112 | (name.into(), archive_type(name).unwrap()) | |
1113 | } else if name.ends_with(".pxar") { | |
dc155e9b TL |
1114 | (format!("{}.didx", name), ArchiveType::DynamicIndex) |
1115 | } else if name.ends_with(".img") { | |
1116 | (format!("{}.fidx", name), ArchiveType::FixedIndex) | |
1117 | } else { | |
1118 | (format!("{}.blob", name), ArchiveType::Blob) | |
1119 | } | |
1120 | } | |
1121 | ||
a47a02ae DM |
1122 | #[api( |
1123 | input: { | |
1124 | properties: { | |
1125 | repository: { | |
1126 | schema: REPO_URL_SCHEMA, | |
1127 | optional: true, | |
1128 | }, | |
1129 | snapshot: { | |
1130 | type: String, | |
1131 | description: "Group/Snapshot path.", | |
1132 | }, | |
1133 | "archive-name": { | |
1134 | description: "Backup archive name.", | |
1135 | type: String, | |
1136 | }, | |
1137 | target: { | |
1138 | type: String, | |
90c815bf | 1139 | description: r###"Target directory path. Use '-' to write to standard output. |
8a8a4703 | 1140 | |
5eee6d89 | 1141 | We do not extraxt '.pxar' archives when writing to standard output. |
8a8a4703 | 1142 | |
a47a02ae DM |
1143 | "### |
1144 | }, | |
1145 | "allow-existing-dirs": { | |
1146 | type: Boolean, | |
1147 | description: "Do not fail if directories already exists.", | |
1148 | optional: true, | |
1149 | }, | |
1150 | keyfile: { | |
1151 | schema: KEYFILE_SCHEMA, | |
1152 | optional: true, | |
1153 | }, | |
1154 | } | |
1155 | } | |
1156 | )] | |
1157 | /// Restore backup repository. | |
1158 | async fn restore(param: Value) -> Result<Value, Error> { | |
2665cef7 | 1159 | let repo = extract_repository_from_value(¶m)?; |
9f912493 | 1160 | |
86eda3eb DM |
1161 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
1162 | ||
46d5aa0a DM |
1163 | let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false); |
1164 | ||
d5c34d98 DM |
1165 | let archive_name = tools::required_string_param(¶m, "archive-name")?; |
1166 | ||
d59dbeca | 1167 | let client = connect(repo.host(), repo.user())?; |
d0a03d40 | 1168 | |
d0a03d40 | 1169 | record_repository(&repo); |
d5c34d98 | 1170 | |
9f912493 | 1171 | let path = tools::required_string_param(¶m, "snapshot")?; |
9f912493 | 1172 | |
86eda3eb | 1173 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { |
d5c34d98 | 1174 | let group = BackupGroup::parse(path)?; |
27c9affb | 1175 | api_datastore_latest_snapshot(&client, repo.store(), group).await? |
d5c34d98 DM |
1176 | } else { |
1177 | let snapshot = BackupDir::parse(path)?; | |
86eda3eb DM |
1178 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) |
1179 | }; | |
9f912493 | 1180 | |
d5c34d98 | 1181 | let target = tools::required_string_param(¶m, "target")?; |
bf125261 | 1182 | let target = if target == "-" { None } else { Some(target) }; |
2ae7d196 | 1183 | |
11377a47 | 1184 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); |
2ae7d196 | 1185 | |
86eda3eb DM |
1186 | let crypt_config = match keyfile { |
1187 | None => None, | |
1188 | Some(path) => { | |
6d20a29d | 1189 | let (key, _) = load_and_decrypt_key(&path, &get_encryption_key_password)?; |
86eda3eb DM |
1190 | Some(Arc::new(CryptConfig::new(key)?)) |
1191 | } | |
1192 | }; | |
d5c34d98 | 1193 | |
296c50ba DM |
1194 | let client = BackupReader::start( |
1195 | client, | |
1196 | crypt_config.clone(), | |
1197 | repo.store(), | |
1198 | &backup_type, | |
1199 | &backup_id, | |
1200 | backup_time, | |
1201 | true, | |
1202 | ).await?; | |
86eda3eb | 1203 | |
f06b820a | 1204 | let manifest = client.download_manifest().await?; |
02fcf372 | 1205 | |
dc155e9b TL |
1206 | let (archive_name, archive_type) = parse_archive_type(archive_name); |
1207 | ||
1208 | if archive_name == MANIFEST_BLOB_NAME { | |
f06b820a | 1209 | let backup_index_data = manifest.into_json().to_string(); |
02fcf372 | 1210 | if let Some(target) = target { |
feaa1ad3 | 1211 | replace_file(target, backup_index_data.as_bytes(), CreateOptions::new())?; |
02fcf372 DM |
1212 | } else { |
1213 | let stdout = std::io::stdout(); | |
1214 | let mut writer = stdout.lock(); | |
296c50ba | 1215 | writer.write_all(backup_index_data.as_bytes()) |
02fcf372 DM |
1216 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1217 | } | |
1218 | ||
dc155e9b | 1219 | } else if archive_type == ArchiveType::Blob { |
d2267b11 | 1220 | |
dc155e9b | 1221 | let mut reader = client.download_blob(&manifest, &archive_name).await?; |
f8100e96 | 1222 | |
bf125261 | 1223 | if let Some(target) = target { |
0d986280 DM |
1224 | let mut writer = std::fs::OpenOptions::new() |
1225 | .write(true) | |
1226 | .create(true) | |
1227 | .create_new(true) | |
1228 | .open(target) | |
1229 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?; | |
1230 | std::io::copy(&mut reader, &mut writer)?; | |
bf125261 DM |
1231 | } else { |
1232 | let stdout = std::io::stdout(); | |
1233 | let mut writer = stdout.lock(); | |
0d986280 | 1234 | std::io::copy(&mut reader, &mut writer) |
bf125261 DM |
1235 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1236 | } | |
f8100e96 | 1237 | |
dc155e9b | 1238 | } else if archive_type == ArchiveType::DynamicIndex { |
86eda3eb | 1239 | |
dc155e9b | 1240 | let index = client.download_dynamic_index(&manifest, &archive_name).await?; |
df65bd3d | 1241 | |
f4bf7dfc DM |
1242 | let most_used = index.find_most_used_chunks(8); |
1243 | ||
1244 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
1245 | ||
afb4cd28 | 1246 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); |
86eda3eb | 1247 | |
bf125261 | 1248 | if let Some(target) = target { |
86eda3eb | 1249 | |
47651f95 | 1250 | let feature_flags = pxar::flags::DEFAULT; |
f701d033 DM |
1251 | let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags); |
1252 | decoder.set_callback(move |path| { | |
bf125261 | 1253 | if verbose { |
fd04ca7a | 1254 | eprintln!("{:?}", path); |
bf125261 DM |
1255 | } |
1256 | Ok(()) | |
1257 | }); | |
6a879109 CE |
1258 | decoder.set_allow_existing_dirs(allow_existing_dirs); |
1259 | ||
fa7e957c | 1260 | decoder.restore(Path::new(target), &Vec::new())?; |
bf125261 | 1261 | } else { |
88892ea8 DM |
1262 | let mut writer = std::fs::OpenOptions::new() |
1263 | .write(true) | |
1264 | .open("/dev/stdout") | |
1265 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?; | |
afb4cd28 | 1266 | |
bf125261 DM |
1267 | std::io::copy(&mut reader, &mut writer) |
1268 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
1269 | } | |
dc155e9b | 1270 | } else if archive_type == ArchiveType::FixedIndex { |
afb4cd28 | 1271 | |
dc155e9b | 1272 | let index = client.download_fixed_index(&manifest, &archive_name).await?; |
df65bd3d | 1273 | |
88892ea8 DM |
1274 | let mut writer = if let Some(target) = target { |
1275 | std::fs::OpenOptions::new() | |
bf125261 DM |
1276 | .write(true) |
1277 | .create(true) | |
1278 | .create_new(true) | |
1279 | .open(target) | |
88892ea8 | 1280 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))? |
bf125261 | 1281 | } else { |
88892ea8 DM |
1282 | std::fs::OpenOptions::new() |
1283 | .write(true) | |
1284 | .open("/dev/stdout") | |
1285 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))? | |
1286 | }; | |
afb4cd28 | 1287 | |
fd04ca7a | 1288 | dump_image(client.clone(), crypt_config.clone(), index, &mut writer, verbose)?; |
3031e44c | 1289 | } |
fef44d4f DM |
1290 | |
1291 | Ok(Value::Null) | |
45db6f89 DM |
1292 | } |
1293 | ||
a47a02ae DM |
1294 | #[api( |
1295 | input: { | |
1296 | properties: { | |
1297 | repository: { | |
1298 | schema: REPO_URL_SCHEMA, | |
1299 | optional: true, | |
1300 | }, | |
1301 | snapshot: { | |
1302 | type: String, | |
1303 | description: "Group/Snapshot path.", | |
1304 | }, | |
1305 | logfile: { | |
1306 | type: String, | |
1307 | description: "The path to the log file you want to upload.", | |
1308 | }, | |
1309 | keyfile: { | |
1310 | schema: KEYFILE_SCHEMA, | |
1311 | optional: true, | |
1312 | }, | |
1313 | } | |
1314 | } | |
1315 | )] | |
1316 | /// Upload backup log file. | |
1317 | async fn upload_log(param: Value) -> Result<Value, Error> { | |
ec34f7eb DM |
1318 | |
1319 | let logfile = tools::required_string_param(¶m, "logfile")?; | |
1320 | let repo = extract_repository_from_value(¶m)?; | |
1321 | ||
1322 | let snapshot = tools::required_string_param(¶m, "snapshot")?; | |
1323 | let snapshot = BackupDir::parse(snapshot)?; | |
1324 | ||
d59dbeca | 1325 | let mut client = connect(repo.host(), repo.user())?; |
ec34f7eb | 1326 | |
11377a47 | 1327 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); |
ec34f7eb DM |
1328 | |
1329 | let crypt_config = match keyfile { | |
1330 | None => None, | |
1331 | Some(path) => { | |
6d20a29d | 1332 | let (key, _created) = load_and_decrypt_key(&path, &get_encryption_key_password)?; |
ec34f7eb | 1333 | let crypt_config = CryptConfig::new(key)?; |
9025312a | 1334 | Some(Arc::new(crypt_config)) |
ec34f7eb DM |
1335 | } |
1336 | }; | |
1337 | ||
e18a6c9e | 1338 | let data = file_get_contents(logfile)?; |
ec34f7eb | 1339 | |
7123ff7d | 1340 | let blob = DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?; |
ec34f7eb DM |
1341 | |
1342 | let raw_data = blob.into_inner(); | |
1343 | ||
1344 | let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store()); | |
1345 | ||
1346 | let args = json!({ | |
1347 | "backup-type": snapshot.group().backup_type(), | |
1348 | "backup-id": snapshot.group().backup_id(), | |
1349 | "backup-time": snapshot.backup_time().timestamp(), | |
1350 | }); | |
1351 | ||
1352 | let body = hyper::Body::from(raw_data); | |
1353 | ||
8a8a4703 | 1354 | client.upload("application/octet-stream", body, &path, Some(args)).await |
ec34f7eb DM |
1355 | } |
1356 | ||
032d3ad8 DM |
1357 | const API_METHOD_PRUNE: ApiMethod = ApiMethod::new( |
1358 | &ApiHandler::Async(&prune), | |
1359 | &ObjectSchema::new( | |
1360 | "Prune a backup repository.", | |
1361 | &proxmox_backup::add_common_prune_prameters!([ | |
1362 | ("dry-run", true, &BooleanSchema::new( | |
1363 | "Just show what prune would do, but do not delete anything.") | |
1364 | .schema()), | |
1365 | ("group", false, &StringSchema::new("Backup group.").schema()), | |
1366 | ], [ | |
1367 | ("output-format", true, &OUTPUT_FORMAT), | |
c48aa39f DM |
1368 | ( |
1369 | "quiet", | |
1370 | true, | |
1371 | &BooleanSchema::new("Minimal output - only show removals.") | |
1372 | .schema() | |
1373 | ), | |
032d3ad8 DM |
1374 | ("repository", true, &REPO_URL_SCHEMA), |
1375 | ]) | |
1376 | ) | |
1377 | ); | |
1378 | ||
1379 | fn prune<'a>( | |
1380 | param: Value, | |
1381 | _info: &ApiMethod, | |
1382 | _rpcenv: &'a mut dyn RpcEnvironment, | |
1383 | ) -> proxmox::api::ApiFuture<'a> { | |
1384 | async move { | |
1385 | prune_async(param).await | |
1386 | }.boxed() | |
1387 | } | |
83b7db02 | 1388 | |
032d3ad8 | 1389 | async fn prune_async(mut param: Value) -> Result<Value, Error> { |
2665cef7 | 1390 | let repo = extract_repository_from_value(¶m)?; |
83b7db02 | 1391 | |
d59dbeca | 1392 | let mut client = connect(repo.host(), repo.user())?; |
83b7db02 | 1393 | |
d0a03d40 | 1394 | let path = format!("api2/json/admin/datastore/{}/prune", repo.store()); |
83b7db02 | 1395 | |
9fdc3ef4 DM |
1396 | let group = tools::required_string_param(¶m, "group")?; |
1397 | let group = BackupGroup::parse(group)?; | |
c2043614 DM |
1398 | |
1399 | let output_format = get_output_format(¶m); | |
9fdc3ef4 | 1400 | |
c48aa39f DM |
1401 | let quiet = param["quiet"].as_bool().unwrap_or(false); |
1402 | ||
ea7a7ef2 DM |
1403 | param.as_object_mut().unwrap().remove("repository"); |
1404 | param.as_object_mut().unwrap().remove("group"); | |
163e9bbe | 1405 | param.as_object_mut().unwrap().remove("output-format"); |
c48aa39f | 1406 | param.as_object_mut().unwrap().remove("quiet"); |
ea7a7ef2 DM |
1407 | |
1408 | param["backup-type"] = group.backup_type().into(); | |
1409 | param["backup-id"] = group.backup_id().into(); | |
83b7db02 | 1410 | |
db1e061d | 1411 | let mut result = client.post(&path, Some(param)).await?; |
74fa81b8 | 1412 | |
87c42375 | 1413 | record_repository(&repo); |
3b03abfe | 1414 | |
db1e061d DM |
1415 | let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> { |
1416 | let item: PruneListItem = serde_json::from_value(record.to_owned())?; | |
1417 | let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time); | |
1418 | Ok(snapshot.relative_path().to_str().unwrap().to_owned()) | |
1419 | }; | |
1420 | ||
c48aa39f DM |
1421 | let render_prune_action = |v: &Value, _record: &Value| -> Result<String, Error> { |
1422 | Ok(match v.as_bool() { | |
1423 | Some(true) => "keep", | |
1424 | Some(false) => "remove", | |
1425 | None => "unknown", | |
1426 | }.to_string()) | |
1427 | }; | |
1428 | ||
db1e061d DM |
1429 | let options = default_table_format_options() |
1430 | .sortby("backup-type", false) | |
1431 | .sortby("backup-id", false) | |
1432 | .sortby("backup-time", false) | |
1433 | .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot")) | |
74f7240b | 1434 | .column(ColumnConfig::new("backup-time").renderer(tools::format::render_epoch).header("date")) |
c48aa39f | 1435 | .column(ColumnConfig::new("keep").renderer(render_prune_action).header("action")) |
db1e061d DM |
1436 | ; |
1437 | ||
1438 | let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_PRUNE; | |
1439 | ||
1440 | let mut data = result["data"].take(); | |
1441 | ||
c48aa39f DM |
1442 | if quiet { |
1443 | let list: Vec<Value> = data.as_array().unwrap().iter().filter(|item| { | |
1444 | item["keep"].as_bool() == Some(false) | |
1445 | }).map(|v| v.clone()).collect(); | |
1446 | data = list.into(); | |
1447 | } | |
1448 | ||
db1e061d | 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(); | |
add5861e | 2030 | // Finish creation of daemon by redirecting filedescriptors. |
70235f72 CE |
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 | |
7b22acd0 DM |
2423 | let rpcenv = CliEnvironment::new(); |
2424 | run_cli_command(cmd_def, rpcenv, Some(|future| { | |
d08bc483 DM |
2425 | proxmox_backup::tools::runtime::main(future) |
2426 | })); | |
ff5d3707 | 2427 | } |