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