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