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