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