]>
Commit | Line | Data |
---|---|---|
2eeaacb9 | 1 | use std::collections::{HashSet, HashMap}; |
0351f23b WB |
2 | use std::convert::TryFrom; |
3 | use std::io::{self, Read, Write, Seek, SeekFrom}; | |
4 | use std::os::unix::io::{FromRawFd, RawFd}; | |
c443f58b WB |
5 | use std::path::{Path, PathBuf}; |
6 | use std::pin::Pin; | |
7 | use std::sync::{Arc, Mutex}; | |
a6f87283 | 8 | use std::task::Context; |
c443f58b WB |
9 | |
10 | use anyhow::{bail, format_err, Error}; | |
c443f58b | 11 | use futures::future::FutureExt; |
c443f58b | 12 | use futures::stream::{StreamExt, TryStreamExt}; |
c443f58b | 13 | use serde_json::{json, Value}; |
c443f58b WB |
14 | use tokio::sync::mpsc; |
15 | use xdg::BaseDirectories; | |
2761d6a4 | 16 | |
c443f58b | 17 | use pathpatterns::{MatchEntry, MatchType, PatternFlag}; |
6a7be83e DM |
18 | use proxmox::{ |
19 | tools::{ | |
20 | time::{strftime_local, epoch_i64}, | |
21 | fs::{file_get_contents, file_get_json, replace_file, CreateOptions, image_size}, | |
22 | }, | |
23 | api::{ | |
24 | api, | |
25 | ApiHandler, | |
26 | ApiMethod, | |
27 | RpcEnvironment, | |
28 | schema::*, | |
29 | cli::*, | |
30 | }, | |
31 | }; | |
a6f87283 | 32 | use pxar::accessor::{MaybeReady, ReadAt, ReadAtOperation}; |
ff5d3707 | 33 | |
fe0e04c6 | 34 | use proxmox_backup::tools; |
0224c3c2 | 35 | use proxmox_backup::api2::access::user::UserWithTokens; |
bbf9e7e9 | 36 | use proxmox_backup::api2::types::*; |
e39974af | 37 | use proxmox_backup::api2::version; |
151c6ce2 | 38 | use proxmox_backup::client::*; |
c443f58b | 39 | use proxmox_backup::pxar::catalog::*; |
4d16badf WB |
40 | use proxmox_backup::backup::{ |
41 | archive_type, | |
0351f23b | 42 | decrypt_key, |
4d16badf WB |
43 | verify_chunk_size, |
44 | ArchiveType, | |
8e6e18b7 | 45 | AsyncReadChunk, |
4d16badf WB |
46 | BackupDir, |
47 | BackupGroup, | |
48 | BackupManifest, | |
49 | BufferedDynamicReader, | |
f28d9088 | 50 | CATALOG_NAME, |
4d16badf WB |
51 | CatalogReader, |
52 | CatalogWriter, | |
4d16badf WB |
53 | ChunkStream, |
54 | CryptConfig, | |
f28d9088 | 55 | CryptMode, |
4d16badf WB |
56 | DataBlob, |
57 | DynamicIndexReader, | |
58 | FixedChunkStream, | |
59 | FixedIndexReader, | |
60 | IndexFile, | |
4d16badf | 61 | MANIFEST_BLOB_NAME, |
4d16badf WB |
62 | Shell, |
63 | }; | |
ae0be2dd | 64 | |
caea8d61 DM |
65 | mod proxmox_backup_client; |
66 | use proxmox_backup_client::*; | |
67 | ||
a05c0c6f | 68 | const ENV_VAR_PBS_FINGERPRINT: &str = "PBS_FINGERPRINT"; |
d1c65727 | 69 | const ENV_VAR_PBS_PASSWORD: &str = "PBS_PASSWORD"; |
a05c0c6f | 70 | |
33d64b81 | 71 | |
caea8d61 | 72 | pub const REPO_URL_SCHEMA: Schema = StringSchema::new("Repository URL.") |
255f378a DM |
73 | .format(&BACKUP_REPO_URL) |
74 | .max_length(256) | |
75 | .schema(); | |
d0a03d40 | 76 | |
caea8d61 | 77 | pub const KEYFILE_SCHEMA: Schema = StringSchema::new( |
a47a02ae DM |
78 | "Path to encryption key. All data will be encrypted using this key.") |
79 | .schema(); | |
80 | ||
0351f23b WB |
81 | pub const KEYFD_SCHEMA: Schema = IntegerSchema::new( |
82 | "Pass an encryption key via an already opened file descriptor.") | |
83 | .minimum(0) | |
84 | .schema(); | |
85 | ||
a47a02ae DM |
86 | const CHUNK_SIZE_SCHEMA: Schema = IntegerSchema::new( |
87 | "Chunk size in KB. Must be a power of 2.") | |
88 | .minimum(64) | |
89 | .maximum(4096) | |
90 | .default(4096) | |
91 | .schema(); | |
92 | ||
2665cef7 DM |
93 | fn get_default_repository() -> Option<String> { |
94 | std::env::var("PBS_REPOSITORY").ok() | |
95 | } | |
96 | ||
caea8d61 | 97 | pub fn extract_repository_from_value( |
2665cef7 DM |
98 | param: &Value, |
99 | ) -> Result<BackupRepository, Error> { | |
100 | ||
101 | let repo_url = param["repository"] | |
102 | .as_str() | |
103 | .map(String::from) | |
104 | .or_else(get_default_repository) | |
105 | .ok_or_else(|| format_err!("unable to get (default) repository"))?; | |
106 | ||
107 | let repo: BackupRepository = repo_url.parse()?; | |
108 | ||
109 | Ok(repo) | |
110 | } | |
111 | ||
112 | fn extract_repository_from_map( | |
113 | param: &HashMap<String, String>, | |
114 | ) -> Option<BackupRepository> { | |
115 | ||
116 | param.get("repository") | |
117 | .map(String::from) | |
118 | .or_else(get_default_repository) | |
119 | .and_then(|repo_url| repo_url.parse::<BackupRepository>().ok()) | |
120 | } | |
121 | ||
d0a03d40 DM |
122 | fn record_repository(repo: &BackupRepository) { |
123 | ||
124 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
125 | Ok(v) => v, | |
126 | _ => return, | |
127 | }; | |
128 | ||
129 | // usually $HOME/.cache/proxmox-backup/repo-list | |
130 | let path = match base.place_cache_file("repo-list") { | |
131 | Ok(v) => v, | |
132 | _ => return, | |
133 | }; | |
134 | ||
11377a47 | 135 | let mut data = file_get_json(&path, None).unwrap_or_else(|_| json!({})); |
d0a03d40 DM |
136 | |
137 | let repo = repo.to_string(); | |
138 | ||
139 | data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 }; | |
140 | ||
141 | let mut map = serde_json::map::Map::new(); | |
142 | ||
143 | loop { | |
144 | let mut max_used = 0; | |
145 | let mut max_repo = None; | |
146 | for (repo, count) in data.as_object().unwrap() { | |
147 | if map.contains_key(repo) { continue; } | |
148 | if let Some(count) = count.as_i64() { | |
149 | if count > max_used { | |
150 | max_used = count; | |
151 | max_repo = Some(repo); | |
152 | } | |
153 | } | |
154 | } | |
155 | if let Some(repo) = max_repo { | |
156 | map.insert(repo.to_owned(), json!(max_used)); | |
157 | } else { | |
158 | break; | |
159 | } | |
160 | if map.len() > 10 { // store max. 10 repos | |
161 | break; | |
162 | } | |
163 | } | |
164 | ||
165 | let new_data = json!(map); | |
166 | ||
feaa1ad3 | 167 | let _ = replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new()); |
d0a03d40 DM |
168 | } |
169 | ||
43abba4b | 170 | pub fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
d0a03d40 DM |
171 | |
172 | let mut result = vec![]; | |
173 | ||
174 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
175 | Ok(v) => v, | |
176 | _ => return result, | |
177 | }; | |
178 | ||
179 | // usually $HOME/.cache/proxmox-backup/repo-list | |
180 | let path = match base.place_cache_file("repo-list") { | |
181 | Ok(v) => v, | |
182 | _ => return result, | |
183 | }; | |
184 | ||
11377a47 | 185 | let data = file_get_json(&path, None).unwrap_or_else(|_| json!({})); |
d0a03d40 DM |
186 | |
187 | if let Some(map) = data.as_object() { | |
49811347 | 188 | for (repo, _count) in map { |
d0a03d40 DM |
189 | result.push(repo.to_owned()); |
190 | } | |
191 | } | |
192 | ||
193 | result | |
194 | } | |
195 | ||
f3fde36b WB |
196 | fn connect(repo: &BackupRepository) -> Result<HttpClient, Error> { |
197 | connect_do(repo.host(), repo.port(), repo.auth_id()) | |
198 | .map_err(|err| format_err!("error building client for repository {} - {}", repo, err)) | |
199 | } | |
d59dbeca | 200 | |
f3fde36b | 201 | fn connect_do(server: &str, port: u16, auth_id: &Authid) -> Result<HttpClient, Error> { |
a05c0c6f DM |
202 | let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok(); |
203 | ||
d1c65727 DM |
204 | use std::env::VarError::*; |
205 | let password = match std::env::var(ENV_VAR_PBS_PASSWORD) { | |
206 | Ok(p) => Some(p), | |
207 | Err(NotUnicode(_)) => bail!(format!("{} contains bad characters", ENV_VAR_PBS_PASSWORD)), | |
208 | Err(NotPresent) => None, | |
209 | }; | |
210 | ||
d59dbeca | 211 | let options = HttpClientOptions::new() |
5030b7ce | 212 | .prefix(Some("proxmox-backup".to_string())) |
d1c65727 | 213 | .password(password) |
d59dbeca | 214 | .interactive(true) |
a05c0c6f | 215 | .fingerprint(fingerprint) |
5a74756c | 216 | .fingerprint_cache(true) |
d59dbeca DM |
217 | .ticket_cache(true); |
218 | ||
34aa8e13 | 219 | HttpClient::new(server, port, auth_id, options) |
d59dbeca DM |
220 | } |
221 | ||
d105176f DM |
222 | async fn view_task_result( |
223 | client: HttpClient, | |
224 | result: Value, | |
225 | output_format: &str, | |
226 | ) -> Result<(), Error> { | |
227 | let data = &result["data"]; | |
228 | if output_format == "text" { | |
229 | if let Some(upid) = data.as_str() { | |
230 | display_task_log(client, upid, true).await?; | |
231 | } | |
232 | } else { | |
233 | format_and_print_result(&data, &output_format); | |
234 | } | |
235 | ||
236 | Ok(()) | |
237 | } | |
238 | ||
42af4b8f DM |
239 | async fn api_datastore_list_snapshots( |
240 | client: &HttpClient, | |
241 | store: &str, | |
242 | group: Option<BackupGroup>, | |
f24fc116 | 243 | ) -> Result<Value, Error> { |
42af4b8f DM |
244 | |
245 | let path = format!("api2/json/admin/datastore/{}/snapshots", store); | |
246 | ||
247 | let mut args = json!({}); | |
248 | if let Some(group) = group { | |
249 | args["backup-type"] = group.backup_type().into(); | |
250 | args["backup-id"] = group.backup_id().into(); | |
251 | } | |
252 | ||
253 | let mut result = client.get(&path, Some(args)).await?; | |
254 | ||
f24fc116 | 255 | Ok(result["data"].take()) |
42af4b8f DM |
256 | } |
257 | ||
43abba4b | 258 | pub async fn api_datastore_latest_snapshot( |
27c9affb DM |
259 | client: &HttpClient, |
260 | store: &str, | |
261 | group: BackupGroup, | |
6a7be83e | 262 | ) -> Result<(String, String, i64), Error> { |
27c9affb | 263 | |
f24fc116 DM |
264 | let list = api_datastore_list_snapshots(client, store, Some(group.clone())).await?; |
265 | let mut list: Vec<SnapshotListItem> = serde_json::from_value(list)?; | |
27c9affb DM |
266 | |
267 | if list.is_empty() { | |
268 | bail!("backup group {:?} does not contain any snapshots.", group.group_path()); | |
269 | } | |
270 | ||
271 | list.sort_unstable_by(|a, b| b.backup_time.cmp(&a.backup_time)); | |
272 | ||
6a7be83e | 273 | let backup_time = list[0].backup_time; |
27c9affb DM |
274 | |
275 | Ok((group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time)) | |
276 | } | |
277 | ||
e9722f8b | 278 | async fn backup_directory<P: AsRef<Path>>( |
cf9271e2 | 279 | client: &BackupWriter, |
b957aa81 | 280 | previous_manifest: Option<Arc<BackupManifest>>, |
17d6979a | 281 | dir_path: P, |
247cdbce | 282 | archive_name: &str, |
36898ffc | 283 | chunk_size: Option<usize>, |
2eeaacb9 | 284 | device_set: Option<HashSet<u64>>, |
219ef0e6 | 285 | verbose: bool, |
5b72c9b4 | 286 | skip_lost_and_found: bool, |
f1d99e3f | 287 | catalog: Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>, |
c443f58b | 288 | exclude_pattern: Vec<MatchEntry>, |
6fc053ed | 289 | entries_max: usize, |
3638341a DM |
290 | compress: bool, |
291 | encrypt: bool, | |
2c3891d1 | 292 | ) -> Result<BackupStats, Error> { |
33d64b81 | 293 | |
6fc053ed CE |
294 | let pxar_stream = PxarBackupStream::open( |
295 | dir_path.as_ref(), | |
296 | device_set, | |
297 | verbose, | |
298 | skip_lost_and_found, | |
299 | catalog, | |
189996cf | 300 | exclude_pattern, |
6fc053ed CE |
301 | entries_max, |
302 | )?; | |
e9722f8b | 303 | let mut chunk_stream = ChunkStream::new(pxar_stream, chunk_size); |
ff3d3100 | 304 | |
e9722f8b | 305 | let (mut tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks |
5e7a09be | 306 | |
c4ff3dce | 307 | let stream = rx |
e9722f8b | 308 | .map_err(Error::from); |
17d6979a | 309 | |
c4ff3dce | 310 | // spawn chunker inside a separate task so that it can run parallel |
e9722f8b | 311 | tokio::spawn(async move { |
db0cb9ce WB |
312 | while let Some(v) = chunk_stream.next().await { |
313 | let _ = tx.send(v).await; | |
314 | } | |
e9722f8b | 315 | }); |
17d6979a | 316 | |
e9722f8b | 317 | let stats = client |
3638341a | 318 | .upload_stream(previous_manifest, archive_name, stream, "dynamic", None, compress, encrypt) |
e9722f8b | 319 | .await?; |
bcd879cf | 320 | |
2c3891d1 | 321 | Ok(stats) |
bcd879cf DM |
322 | } |
323 | ||
e9722f8b | 324 | async fn backup_image<P: AsRef<Path>>( |
cf9271e2 | 325 | client: &BackupWriter, |
b957aa81 | 326 | previous_manifest: Option<Arc<BackupManifest>>, |
6af905c1 DM |
327 | image_path: P, |
328 | archive_name: &str, | |
329 | image_size: u64, | |
36898ffc | 330 | chunk_size: Option<usize>, |
3638341a DM |
331 | compress: bool, |
332 | encrypt: bool, | |
1c0472e8 | 333 | _verbose: bool, |
2c3891d1 | 334 | ) -> Result<BackupStats, Error> { |
6af905c1 | 335 | |
6af905c1 DM |
336 | let path = image_path.as_ref().to_owned(); |
337 | ||
e9722f8b | 338 | let file = tokio::fs::File::open(path).await?; |
6af905c1 | 339 | |
db0cb9ce | 340 | let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new()) |
6af905c1 DM |
341 | .map_err(Error::from); |
342 | ||
36898ffc | 343 | let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024)); |
6af905c1 | 344 | |
e9722f8b | 345 | let stats = client |
3638341a | 346 | .upload_stream(previous_manifest, archive_name, stream, "fixed", Some(image_size), compress, encrypt) |
e9722f8b | 347 | .await?; |
6af905c1 | 348 | |
2c3891d1 | 349 | Ok(stats) |
6af905c1 DM |
350 | } |
351 | ||
a47a02ae DM |
352 | #[api( |
353 | input: { | |
354 | properties: { | |
355 | repository: { | |
356 | schema: REPO_URL_SCHEMA, | |
357 | optional: true, | |
358 | }, | |
359 | "output-format": { | |
360 | schema: OUTPUT_FORMAT, | |
361 | optional: true, | |
362 | }, | |
363 | } | |
364 | } | |
365 | )] | |
366 | /// List backup groups. | |
367 | async fn list_backup_groups(param: Value) -> Result<Value, Error> { | |
812c6f87 | 368 | |
c81b2b7c DM |
369 | let output_format = get_output_format(¶m); |
370 | ||
2665cef7 | 371 | let repo = extract_repository_from_value(¶m)?; |
812c6f87 | 372 | |
f3fde36b | 373 | let client = connect(&repo)?; |
812c6f87 | 374 | |
d0a03d40 | 375 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
812c6f87 | 376 | |
8a8a4703 | 377 | let mut result = client.get(&path, None).await?; |
812c6f87 | 378 | |
d0a03d40 DM |
379 | record_repository(&repo); |
380 | ||
c81b2b7c DM |
381 | let render_group_path = |_v: &Value, record: &Value| -> Result<String, Error> { |
382 | let item: GroupListItem = serde_json::from_value(record.to_owned())?; | |
383 | let group = BackupGroup::new(item.backup_type, item.backup_id); | |
384 | Ok(group.group_path().to_str().unwrap().to_owned()) | |
385 | }; | |
812c6f87 | 386 | |
18deda40 DM |
387 | let render_last_backup = |_v: &Value, record: &Value| -> Result<String, Error> { |
388 | let item: GroupListItem = serde_json::from_value(record.to_owned())?; | |
e0e5b442 | 389 | let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.last_backup)?; |
18deda40 | 390 | Ok(snapshot.relative_path().to_str().unwrap().to_owned()) |
c81b2b7c | 391 | }; |
812c6f87 | 392 | |
c81b2b7c DM |
393 | let render_files = |_v: &Value, record: &Value| -> Result<String, Error> { |
394 | let item: GroupListItem = serde_json::from_value(record.to_owned())?; | |
4939255f | 395 | Ok(tools::format::render_backup_file_list(&item.files)) |
c81b2b7c | 396 | }; |
812c6f87 | 397 | |
c81b2b7c DM |
398 | let options = default_table_format_options() |
399 | .sortby("backup-type", false) | |
400 | .sortby("backup-id", false) | |
401 | .column(ColumnConfig::new("backup-id").renderer(render_group_path).header("group")) | |
18deda40 DM |
402 | .column( |
403 | ColumnConfig::new("last-backup") | |
404 | .renderer(render_last_backup) | |
405 | .header("last snapshot") | |
406 | .right_align(false) | |
407 | ) | |
c81b2b7c DM |
408 | .column(ColumnConfig::new("backup-count")) |
409 | .column(ColumnConfig::new("files").renderer(render_files)); | |
ad20d198 | 410 | |
c81b2b7c | 411 | let mut data: Value = result["data"].take(); |
ad20d198 | 412 | |
c81b2b7c | 413 | let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_GROUPS; |
812c6f87 | 414 | |
c81b2b7c | 415 | format_and_print_result_full(&mut data, info, &output_format, &options); |
34a816cc | 416 | |
812c6f87 DM |
417 | Ok(Value::Null) |
418 | } | |
419 | ||
344add38 DW |
420 | #[api( |
421 | input: { | |
422 | properties: { | |
423 | repository: { | |
424 | schema: REPO_URL_SCHEMA, | |
425 | optional: true, | |
426 | }, | |
427 | group: { | |
428 | type: String, | |
429 | description: "Backup group.", | |
430 | }, | |
431 | "new-owner": { | |
e6dc35ac | 432 | type: Authid, |
344add38 DW |
433 | }, |
434 | } | |
435 | } | |
436 | )] | |
437 | /// Change owner of a backup group | |
438 | async fn change_backup_owner(group: String, mut param: Value) -> Result<(), Error> { | |
439 | ||
440 | let repo = extract_repository_from_value(¶m)?; | |
441 | ||
f3fde36b | 442 | let mut client = connect(&repo)?; |
344add38 DW |
443 | |
444 | param.as_object_mut().unwrap().remove("repository"); | |
445 | ||
446 | let group: BackupGroup = group.parse()?; | |
447 | ||
448 | param["backup-type"] = group.backup_type().into(); | |
449 | param["backup-id"] = group.backup_id().into(); | |
450 | ||
451 | let path = format!("api2/json/admin/datastore/{}/change-owner", repo.store()); | |
452 | client.post(&path, Some(param)).await?; | |
453 | ||
454 | record_repository(&repo); | |
455 | ||
456 | Ok(()) | |
457 | } | |
458 | ||
a47a02ae DM |
459 | #[api( |
460 | input: { | |
461 | properties: { | |
462 | repository: { | |
463 | schema: REPO_URL_SCHEMA, | |
464 | optional: true, | |
465 | }, | |
466 | group: { | |
467 | type: String, | |
468 | description: "Backup group.", | |
469 | optional: true, | |
470 | }, | |
471 | "output-format": { | |
472 | schema: OUTPUT_FORMAT, | |
473 | optional: true, | |
474 | }, | |
475 | } | |
476 | } | |
477 | )] | |
478 | /// List backup snapshots. | |
479 | async fn list_snapshots(param: Value) -> Result<Value, Error> { | |
184f17af | 480 | |
2665cef7 | 481 | let repo = extract_repository_from_value(¶m)?; |
184f17af | 482 | |
c2043614 | 483 | let output_format = get_output_format(¶m); |
34a816cc | 484 | |
f3fde36b | 485 | let client = connect(&repo)?; |
184f17af | 486 | |
d6d3b353 DM |
487 | let group: Option<BackupGroup> = if let Some(path) = param["group"].as_str() { |
488 | Some(path.parse()?) | |
42af4b8f DM |
489 | } else { |
490 | None | |
491 | }; | |
184f17af | 492 | |
f24fc116 | 493 | let mut data = api_datastore_list_snapshots(&client, repo.store(), group).await?; |
184f17af | 494 | |
d0a03d40 DM |
495 | record_repository(&repo); |
496 | ||
f24fc116 DM |
497 | let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> { |
498 | let item: SnapshotListItem = serde_json::from_value(record.to_owned())?; | |
e0e5b442 | 499 | let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time)?; |
f24fc116 DM |
500 | Ok(snapshot.relative_path().to_str().unwrap().to_owned()) |
501 | }; | |
184f17af | 502 | |
f24fc116 DM |
503 | let render_files = |_v: &Value, record: &Value| -> Result<String, Error> { |
504 | let item: SnapshotListItem = serde_json::from_value(record.to_owned())?; | |
1c090810 DC |
505 | let mut filenames = Vec::new(); |
506 | for file in &item.files { | |
507 | filenames.push(file.filename.to_string()); | |
508 | } | |
509 | Ok(tools::format::render_backup_file_list(&filenames[..])) | |
f24fc116 DM |
510 | }; |
511 | ||
c2043614 | 512 | let options = default_table_format_options() |
f24fc116 DM |
513 | .sortby("backup-type", false) |
514 | .sortby("backup-id", false) | |
515 | .sortby("backup-time", false) | |
516 | .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot")) | |
23440482 | 517 | .column(ColumnConfig::new("size").renderer(tools::format::render_bytes_human_readable)) |
f24fc116 DM |
518 | .column(ColumnConfig::new("files").renderer(render_files)) |
519 | ; | |
520 | ||
521 | let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOTS; | |
522 | ||
523 | format_and_print_result_full(&mut data, info, &output_format, &options); | |
184f17af DM |
524 | |
525 | Ok(Value::Null) | |
526 | } | |
527 | ||
a47a02ae DM |
528 | #[api( |
529 | input: { | |
530 | properties: { | |
531 | repository: { | |
532 | schema: REPO_URL_SCHEMA, | |
533 | optional: true, | |
534 | }, | |
535 | snapshot: { | |
536 | type: String, | |
537 | description: "Snapshot path.", | |
538 | }, | |
539 | } | |
540 | } | |
541 | )] | |
542 | /// Forget (remove) backup snapshots. | |
543 | async fn forget_snapshots(param: Value) -> Result<Value, Error> { | |
6f62c924 | 544 | |
2665cef7 | 545 | let repo = extract_repository_from_value(¶m)?; |
6f62c924 DM |
546 | |
547 | let path = tools::required_string_param(¶m, "snapshot")?; | |
a67f7d0a | 548 | let snapshot: BackupDir = path.parse()?; |
6f62c924 | 549 | |
f3fde36b | 550 | let mut client = connect(&repo)?; |
6f62c924 | 551 | |
9e391bb7 | 552 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
6f62c924 | 553 | |
8a8a4703 DM |
554 | let result = client.delete(&path, Some(json!({ |
555 | "backup-type": snapshot.group().backup_type(), | |
556 | "backup-id": snapshot.group().backup_id(), | |
6a7be83e | 557 | "backup-time": snapshot.backup_time(), |
8a8a4703 | 558 | }))).await?; |
6f62c924 | 559 | |
d0a03d40 DM |
560 | record_repository(&repo); |
561 | ||
6f62c924 DM |
562 | Ok(result) |
563 | } | |
564 | ||
a47a02ae DM |
565 | #[api( |
566 | input: { | |
567 | properties: { | |
568 | repository: { | |
569 | schema: REPO_URL_SCHEMA, | |
570 | optional: true, | |
571 | }, | |
572 | } | |
573 | } | |
574 | )] | |
575 | /// Try to login. If successful, store ticket. | |
576 | async fn api_login(param: Value) -> Result<Value, Error> { | |
e240d8be DM |
577 | |
578 | let repo = extract_repository_from_value(¶m)?; | |
579 | ||
f3fde36b | 580 | let client = connect(&repo)?; |
8a8a4703 | 581 | client.login().await?; |
e240d8be DM |
582 | |
583 | record_repository(&repo); | |
584 | ||
585 | Ok(Value::Null) | |
586 | } | |
587 | ||
a47a02ae DM |
588 | #[api( |
589 | input: { | |
590 | properties: { | |
591 | repository: { | |
592 | schema: REPO_URL_SCHEMA, | |
593 | optional: true, | |
594 | }, | |
595 | } | |
596 | } | |
597 | )] | |
598 | /// Logout (delete stored ticket). | |
599 | fn api_logout(param: Value) -> Result<Value, Error> { | |
e240d8be DM |
600 | |
601 | let repo = extract_repository_from_value(¶m)?; | |
602 | ||
5030b7ce | 603 | delete_ticket_info("proxmox-backup", repo.host(), repo.user())?; |
e240d8be DM |
604 | |
605 | Ok(Value::Null) | |
606 | } | |
607 | ||
e39974af TL |
608 | #[api( |
609 | input: { | |
610 | properties: { | |
611 | repository: { | |
612 | schema: REPO_URL_SCHEMA, | |
613 | optional: true, | |
614 | }, | |
615 | "output-format": { | |
616 | schema: OUTPUT_FORMAT, | |
617 | optional: true, | |
618 | }, | |
619 | } | |
620 | } | |
621 | )] | |
622 | /// Show client and optional server version | |
623 | async fn api_version(param: Value) -> Result<(), Error> { | |
624 | ||
625 | let output_format = get_output_format(¶m); | |
626 | ||
627 | let mut version_info = json!({ | |
628 | "client": { | |
629 | "version": version::PROXMOX_PKG_VERSION, | |
630 | "release": version::PROXMOX_PKG_RELEASE, | |
631 | "repoid": version::PROXMOX_PKG_REPOID, | |
632 | } | |
633 | }); | |
634 | ||
635 | let repo = extract_repository_from_value(¶m); | |
636 | if let Ok(repo) = repo { | |
f3fde36b | 637 | let client = connect(&repo)?; |
e39974af TL |
638 | |
639 | match client.get("api2/json/version", None).await { | |
640 | Ok(mut result) => version_info["server"] = result["data"].take(), | |
641 | Err(e) => eprintln!("could not connect to server - {}", e), | |
642 | } | |
643 | } | |
644 | if output_format == "text" { | |
645 | println!("client version: {}.{}", version::PROXMOX_PKG_VERSION, version::PROXMOX_PKG_RELEASE); | |
646 | if let Some(server) = version_info["server"].as_object() { | |
647 | let server_version = server["version"].as_str().unwrap(); | |
648 | let server_release = server["release"].as_str().unwrap(); | |
649 | println!("server version: {}.{}", server_version, server_release); | |
650 | } | |
651 | } else { | |
652 | format_and_print_result(&version_info, &output_format); | |
653 | } | |
654 | ||
655 | Ok(()) | |
656 | } | |
657 | ||
9049a8cf | 658 | |
a47a02ae DM |
659 | #[api( |
660 | input: { | |
661 | properties: { | |
662 | repository: { | |
663 | schema: REPO_URL_SCHEMA, | |
664 | optional: true, | |
665 | }, | |
666 | snapshot: { | |
667 | type: String, | |
668 | description: "Snapshot path.", | |
669 | }, | |
670 | "output-format": { | |
671 | schema: OUTPUT_FORMAT, | |
672 | optional: true, | |
673 | }, | |
674 | } | |
675 | } | |
676 | )] | |
677 | /// List snapshot files. | |
678 | async fn list_snapshot_files(param: Value) -> Result<Value, Error> { | |
52c171e4 DM |
679 | |
680 | let repo = extract_repository_from_value(¶m)?; | |
681 | ||
682 | let path = tools::required_string_param(¶m, "snapshot")?; | |
a67f7d0a | 683 | let snapshot: BackupDir = path.parse()?; |
52c171e4 | 684 | |
c2043614 | 685 | let output_format = get_output_format(¶m); |
52c171e4 | 686 | |
f3fde36b | 687 | let client = connect(&repo)?; |
52c171e4 DM |
688 | |
689 | let path = format!("api2/json/admin/datastore/{}/files", repo.store()); | |
690 | ||
8a8a4703 DM |
691 | let mut result = client.get(&path, Some(json!({ |
692 | "backup-type": snapshot.group().backup_type(), | |
693 | "backup-id": snapshot.group().backup_id(), | |
6a7be83e | 694 | "backup-time": snapshot.backup_time(), |
8a8a4703 | 695 | }))).await?; |
52c171e4 DM |
696 | |
697 | record_repository(&repo); | |
698 | ||
ea5f547f | 699 | let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOT_FILES; |
52c171e4 | 700 | |
ea5f547f DM |
701 | let mut data: Value = result["data"].take(); |
702 | ||
c2043614 | 703 | let options = default_table_format_options(); |
ea5f547f DM |
704 | |
705 | format_and_print_result_full(&mut data, info, &output_format, &options); | |
52c171e4 DM |
706 | |
707 | Ok(Value::Null) | |
708 | } | |
709 | ||
a47a02ae | 710 | #[api( |
94913f35 | 711 | input: { |
a47a02ae DM |
712 | properties: { |
713 | repository: { | |
714 | schema: REPO_URL_SCHEMA, | |
715 | optional: true, | |
716 | }, | |
94913f35 DM |
717 | "output-format": { |
718 | schema: OUTPUT_FORMAT, | |
719 | optional: true, | |
720 | }, | |
721 | }, | |
722 | }, | |
a47a02ae DM |
723 | )] |
724 | /// Start garbage collection for a specific repository. | |
725 | async fn start_garbage_collection(param: Value) -> Result<Value, Error> { | |
8cc0d6af | 726 | |
2665cef7 | 727 | let repo = extract_repository_from_value(¶m)?; |
c2043614 DM |
728 | |
729 | let output_format = get_output_format(¶m); | |
8cc0d6af | 730 | |
f3fde36b | 731 | let mut client = connect(&repo)?; |
8cc0d6af | 732 | |
d0a03d40 | 733 | let path = format!("api2/json/admin/datastore/{}/gc", repo.store()); |
8cc0d6af | 734 | |
8a8a4703 | 735 | let result = client.post(&path, None).await?; |
8cc0d6af | 736 | |
8a8a4703 | 737 | record_repository(&repo); |
d0a03d40 | 738 | |
8a8a4703 | 739 | view_task_result(client, result, &output_format).await?; |
e5f7def4 | 740 | |
e5f7def4 | 741 | Ok(Value::Null) |
8cc0d6af | 742 | } |
33d64b81 | 743 | |
bf6e3217 | 744 | fn spawn_catalog_upload( |
3bad3e6e | 745 | client: Arc<BackupWriter>, |
3638341a | 746 | encrypt: bool, |
bf6e3217 DM |
747 | ) -> Result< |
748 | ( | |
f1d99e3f | 749 | Arc<Mutex<CatalogWriter<crate::tools::StdChannelWriter>>>, |
bf6e3217 DM |
750 | tokio::sync::oneshot::Receiver<Result<BackupStats, Error>> |
751 | ), Error> | |
752 | { | |
f1d99e3f DM |
753 | let (catalog_tx, catalog_rx) = std::sync::mpsc::sync_channel(10); // allow to buffer 10 writes |
754 | let catalog_stream = crate::tools::StdChannelStream(catalog_rx); | |
bf6e3217 DM |
755 | let catalog_chunk_size = 512*1024; |
756 | let catalog_chunk_stream = ChunkStream::new(catalog_stream, Some(catalog_chunk_size)); | |
757 | ||
f1d99e3f | 758 | let catalog = Arc::new(Mutex::new(CatalogWriter::new(crate::tools::StdChannelWriter::new(catalog_tx))?)); |
bf6e3217 DM |
759 | |
760 | let (catalog_result_tx, catalog_result_rx) = tokio::sync::oneshot::channel(); | |
761 | ||
762 | tokio::spawn(async move { | |
763 | let catalog_upload_result = client | |
3638341a | 764 | .upload_stream(None, CATALOG_NAME, catalog_chunk_stream, "dynamic", None, true, encrypt) |
bf6e3217 DM |
765 | .await; |
766 | ||
767 | if let Err(ref err) = catalog_upload_result { | |
768 | eprintln!("catalog upload error - {}", err); | |
769 | client.cancel(); | |
770 | } | |
771 | ||
772 | let _ = catalog_result_tx.send(catalog_upload_result); | |
773 | }); | |
774 | ||
775 | Ok((catalog, catalog_result_rx)) | |
776 | } | |
777 | ||
0351f23b | 778 | fn keyfile_parameters(param: &Value) -> Result<(Option<Vec<u8>>, CryptMode), Error> { |
f28d9088 WB |
779 | let keyfile = match param.get("keyfile") { |
780 | Some(Value::String(keyfile)) => Some(keyfile), | |
781 | Some(_) => bail!("bad --keyfile parameter type"), | |
782 | None => None, | |
783 | }; | |
784 | ||
0351f23b WB |
785 | let key_fd = match param.get("keyfd") { |
786 | Some(Value::Number(key_fd)) => Some( | |
787 | RawFd::try_from(key_fd | |
788 | .as_i64() | |
789 | .ok_or_else(|| format_err!("bad key fd: {:?}", key_fd))? | |
790 | ) | |
791 | .map_err(|err| format_err!("bad key fd: {:?}: {}", key_fd, err))? | |
792 | ), | |
793 | Some(_) => bail!("bad --keyfd parameter type"), | |
794 | None => None, | |
795 | }; | |
796 | ||
f28d9088 WB |
797 | let crypt_mode: Option<CryptMode> = match param.get("crypt-mode") { |
798 | Some(mode) => Some(serde_json::from_value(mode.clone())?), | |
799 | None => None, | |
800 | }; | |
801 | ||
0351f23b WB |
802 | let keydata = match (keyfile, key_fd) { |
803 | (None, None) => None, | |
804 | (Some(_), Some(_)) => bail!("--keyfile and --keyfd are mutually exclusive"), | |
beb07279 SI |
805 | (Some(keyfile), None) => { |
806 | println!("Using encryption key file: {}", keyfile); | |
807 | Some(file_get_contents(keyfile)?) | |
808 | }, | |
0351f23b WB |
809 | (None, Some(fd)) => { |
810 | let input = unsafe { std::fs::File::from_raw_fd(fd) }; | |
811 | let mut data = Vec::new(); | |
812 | let _len: usize = { input }.read_to_end(&mut data) | |
813 | .map_err(|err| { | |
814 | format_err!("error reading encryption key from fd {}: {}", fd, err) | |
815 | })?; | |
beb07279 | 816 | println!("Using encryption key from file descriptor"); |
0351f23b WB |
817 | Some(data) |
818 | } | |
819 | }; | |
820 | ||
821 | Ok(match (keydata, crypt_mode) { | |
96ee8577 | 822 | // no parameters: |
0351f23b | 823 | (None, None) => match key::read_optional_default_encryption_key()? { |
8c6854c8 SI |
824 | Some(key) => { |
825 | println!("Encrypting with default encryption key!"); | |
826 | (Some(key), CryptMode::Encrypt) | |
827 | }, | |
05389a01 WB |
828 | None => (None, CryptMode::None), |
829 | }, | |
96ee8577 | 830 | |
f28d9088 WB |
831 | // just --crypt-mode=none |
832 | (None, Some(CryptMode::None)) => (None, CryptMode::None), | |
96ee8577 | 833 | |
f28d9088 | 834 | // just --crypt-mode other than none |
0351f23b | 835 | (None, Some(crypt_mode)) => match key::read_optional_default_encryption_key()? { |
f28d9088 | 836 | None => bail!("--crypt-mode without --keyfile and no default key file available"), |
beb07279 SI |
837 | Some(key) => { |
838 | println!("Encrypting with default encryption key!"); | |
839 | (Some(key), crypt_mode) | |
840 | }, | |
96ee8577 WB |
841 | } |
842 | ||
843 | // just --keyfile | |
0351f23b | 844 | (Some(key), None) => (Some(key), CryptMode::Encrypt), |
96ee8577 | 845 | |
f28d9088 WB |
846 | // --keyfile and --crypt-mode=none |
847 | (Some(_), Some(CryptMode::None)) => { | |
0351f23b | 848 | bail!("--keyfile/--keyfd and --crypt-mode=none are mutually exclusive"); |
96ee8577 WB |
849 | } |
850 | ||
f28d9088 | 851 | // --keyfile and --crypt-mode other than none |
0351f23b | 852 | (Some(key), Some(crypt_mode)) => (Some(key), crypt_mode), |
96ee8577 WB |
853 | }) |
854 | } | |
855 | ||
a47a02ae DM |
856 | #[api( |
857 | input: { | |
858 | properties: { | |
859 | backupspec: { | |
860 | type: Array, | |
861 | description: "List of backup source specifications ([<label.ext>:<path>] ...)", | |
862 | items: { | |
863 | schema: BACKUP_SOURCE_SCHEMA, | |
864 | } | |
865 | }, | |
866 | repository: { | |
867 | schema: REPO_URL_SCHEMA, | |
868 | optional: true, | |
869 | }, | |
870 | "include-dev": { | |
871 | description: "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.", | |
872 | optional: true, | |
873 | items: { | |
874 | type: String, | |
875 | description: "Path to file.", | |
876 | } | |
877 | }, | |
58fcbf5a FE |
878 | "all-file-systems": { |
879 | type: Boolean, | |
880 | description: "Include all mounted subdirectories.", | |
881 | optional: true, | |
882 | }, | |
a47a02ae DM |
883 | keyfile: { |
884 | schema: KEYFILE_SCHEMA, | |
885 | optional: true, | |
886 | }, | |
0351f23b WB |
887 | "keyfd": { |
888 | schema: KEYFD_SCHEMA, | |
889 | optional: true, | |
890 | }, | |
24be37e3 WB |
891 | "crypt-mode": { |
892 | type: CryptMode, | |
96ee8577 WB |
893 | optional: true, |
894 | }, | |
a47a02ae DM |
895 | "skip-lost-and-found": { |
896 | type: Boolean, | |
897 | description: "Skip lost+found directory.", | |
898 | optional: true, | |
899 | }, | |
900 | "backup-type": { | |
901 | schema: BACKUP_TYPE_SCHEMA, | |
902 | optional: true, | |
903 | }, | |
904 | "backup-id": { | |
905 | schema: BACKUP_ID_SCHEMA, | |
906 | optional: true, | |
907 | }, | |
908 | "backup-time": { | |
909 | schema: BACKUP_TIME_SCHEMA, | |
910 | optional: true, | |
911 | }, | |
912 | "chunk-size": { | |
913 | schema: CHUNK_SIZE_SCHEMA, | |
914 | optional: true, | |
915 | }, | |
189996cf CE |
916 | "exclude": { |
917 | type: Array, | |
918 | description: "List of paths or patterns for matching files to exclude.", | |
919 | optional: true, | |
920 | items: { | |
921 | type: String, | |
922 | description: "Path or match pattern.", | |
923 | } | |
924 | }, | |
6fc053ed CE |
925 | "entries-max": { |
926 | type: Integer, | |
927 | description: "Max number of entries to hold in memory.", | |
928 | optional: true, | |
c443f58b | 929 | default: proxmox_backup::pxar::ENCODER_MAX_ENTRIES as isize, |
6fc053ed | 930 | }, |
e02c3d46 DM |
931 | "verbose": { |
932 | type: Boolean, | |
933 | description: "Verbose output.", | |
934 | optional: true, | |
935 | }, | |
a47a02ae DM |
936 | } |
937 | } | |
938 | )] | |
939 | /// Create (host) backup. | |
940 | async fn create_backup( | |
6049b71f DM |
941 | param: Value, |
942 | _info: &ApiMethod, | |
dd5495d6 | 943 | _rpcenv: &mut dyn RpcEnvironment, |
6049b71f | 944 | ) -> Result<Value, Error> { |
ff5d3707 | 945 | |
2665cef7 | 946 | let repo = extract_repository_from_value(¶m)?; |
ae0be2dd DM |
947 | |
948 | let backupspec_list = tools::required_array_param(¶m, "backupspec")?; | |
a914a774 | 949 | |
eed6db39 DM |
950 | let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false); |
951 | ||
5b72c9b4 DM |
952 | let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false); |
953 | ||
219ef0e6 DM |
954 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
955 | ||
ca5d0b61 DM |
956 | let backup_time_opt = param["backup-time"].as_i64(); |
957 | ||
36898ffc | 958 | let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize); |
2d9d143a | 959 | |
247cdbce DM |
960 | if let Some(size) = chunk_size_opt { |
961 | verify_chunk_size(size)?; | |
2d9d143a DM |
962 | } |
963 | ||
0351f23b | 964 | let (keydata, crypt_mode) = keyfile_parameters(¶m)?; |
6d0983db | 965 | |
f69adc81 | 966 | let backup_id = param["backup-id"].as_str().unwrap_or(&proxmox::tools::nodename()); |
fba30411 | 967 | |
bbf9e7e9 | 968 | let backup_type = param["backup-type"].as_str().unwrap_or("host"); |
ca5d0b61 | 969 | |
2eeaacb9 DM |
970 | let include_dev = param["include-dev"].as_array(); |
971 | ||
c443f58b WB |
972 | let entries_max = param["entries-max"].as_u64() |
973 | .unwrap_or(proxmox_backup::pxar::ENCODER_MAX_ENTRIES as u64); | |
6fc053ed | 974 | |
189996cf | 975 | let empty = Vec::new(); |
c443f58b WB |
976 | let exclude_args = param["exclude"].as_array().unwrap_or(&empty); |
977 | ||
239e49f9 | 978 | let mut pattern_list = Vec::with_capacity(exclude_args.len()); |
c443f58b WB |
979 | for entry in exclude_args { |
980 | let entry = entry.as_str().ok_or_else(|| format_err!("Invalid pattern string slice"))?; | |
239e49f9 | 981 | pattern_list.push( |
c443f58b WB |
982 | MatchEntry::parse_pattern(entry, PatternFlag::PATH_NAME, MatchType::Exclude) |
983 | .map_err(|err| format_err!("invalid exclude pattern entry: {}", err))? | |
984 | ); | |
189996cf CE |
985 | } |
986 | ||
2eeaacb9 DM |
987 | let mut devices = if all_file_systems { None } else { Some(HashSet::new()) }; |
988 | ||
989 | if let Some(include_dev) = include_dev { | |
990 | if all_file_systems { | |
991 | bail!("option 'all-file-systems' conflicts with option 'include-dev'"); | |
992 | } | |
993 | ||
994 | let mut set = HashSet::new(); | |
995 | for path in include_dev { | |
996 | let path = path.as_str().unwrap(); | |
997 | let stat = nix::sys::stat::stat(path) | |
998 | .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?; | |
999 | set.insert(stat.st_dev); | |
1000 | } | |
1001 | devices = Some(set); | |
1002 | } | |
1003 | ||
ae0be2dd | 1004 | let mut upload_list = vec![]; |
f2b4b4b9 | 1005 | let mut target_set = HashSet::new(); |
a914a774 | 1006 | |
ae0be2dd | 1007 | for backupspec in backupspec_list { |
7cc3473a DM |
1008 | let spec = parse_backup_specification(backupspec.as_str().unwrap())?; |
1009 | let filename = &spec.config_string; | |
1010 | let target = &spec.archive_name; | |
bcd879cf | 1011 | |
f2b4b4b9 SI |
1012 | if target_set.contains(target) { |
1013 | bail!("got target twice: '{}'", target); | |
1014 | } | |
1015 | target_set.insert(target.to_string()); | |
1016 | ||
eb1804c5 DM |
1017 | use std::os::unix::fs::FileTypeExt; |
1018 | ||
3fa71727 CE |
1019 | let metadata = std::fs::metadata(filename) |
1020 | .map_err(|err| format_err!("unable to access '{}' - {}", filename, err))?; | |
eb1804c5 | 1021 | let file_type = metadata.file_type(); |
23bb8780 | 1022 | |
7cc3473a DM |
1023 | match spec.spec_type { |
1024 | BackupSpecificationType::PXAR => { | |
ec8a9bb9 DM |
1025 | if !file_type.is_dir() { |
1026 | bail!("got unexpected file type (expected directory)"); | |
1027 | } | |
7cc3473a | 1028 | upload_list.push((BackupSpecificationType::PXAR, filename.to_owned(), format!("{}.didx", target), 0)); |
ec8a9bb9 | 1029 | } |
7cc3473a | 1030 | BackupSpecificationType::IMAGE => { |
ec8a9bb9 DM |
1031 | if !(file_type.is_file() || file_type.is_block_device()) { |
1032 | bail!("got unexpected file type (expected file or block device)"); | |
1033 | } | |
eb1804c5 | 1034 | |
e18a6c9e | 1035 | let size = image_size(&PathBuf::from(filename))?; |
23bb8780 | 1036 | |
ec8a9bb9 | 1037 | if size == 0 { bail!("got zero-sized file '{}'", filename); } |
ae0be2dd | 1038 | |
7cc3473a | 1039 | upload_list.push((BackupSpecificationType::IMAGE, filename.to_owned(), format!("{}.fidx", target), size)); |
ec8a9bb9 | 1040 | } |
7cc3473a | 1041 | BackupSpecificationType::CONFIG => { |
ec8a9bb9 DM |
1042 | if !file_type.is_file() { |
1043 | bail!("got unexpected file type (expected regular file)"); | |
1044 | } | |
7cc3473a | 1045 | upload_list.push((BackupSpecificationType::CONFIG, filename.to_owned(), format!("{}.blob", target), metadata.len())); |
ec8a9bb9 | 1046 | } |
7cc3473a | 1047 | BackupSpecificationType::LOGFILE => { |
79679c2d DM |
1048 | if !file_type.is_file() { |
1049 | bail!("got unexpected file type (expected regular file)"); | |
1050 | } | |
7cc3473a | 1051 | upload_list.push((BackupSpecificationType::LOGFILE, filename.to_owned(), format!("{}.blob", target), metadata.len())); |
ec8a9bb9 | 1052 | } |
ae0be2dd DM |
1053 | } |
1054 | } | |
1055 | ||
6a7be83e | 1056 | let backup_time = backup_time_opt.unwrap_or_else(|| epoch_i64()); |
ae0be2dd | 1057 | |
f3fde36b | 1058 | let client = connect(&repo)?; |
d0a03d40 DM |
1059 | record_repository(&repo); |
1060 | ||
6a7be83e | 1061 | println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time)?); |
ca5d0b61 | 1062 | |
f69adc81 | 1063 | println!("Client name: {}", proxmox::tools::nodename()); |
ca5d0b61 | 1064 | |
6a7be83e | 1065 | let start_time = std::time::Instant::now(); |
ca5d0b61 | 1066 | |
6a7be83e | 1067 | println!("Starting backup protocol: {}", strftime_local("%c", epoch_i64())?); |
51144821 | 1068 | |
0351f23b | 1069 | let (crypt_config, rsa_encrypted_key) = match keydata { |
bb823140 | 1070 | None => (None, None), |
0351f23b | 1071 | Some(key) => { |
6f2626ae FG |
1072 | let (key, created, fingerprint) = decrypt_key(&key, &key::get_encryption_key_password)?; |
1073 | println!("Encryption key fingerprint: {}", fingerprint); | |
bb823140 DM |
1074 | |
1075 | let crypt_config = CryptConfig::new(key)?; | |
1076 | ||
05389a01 WB |
1077 | match key::find_master_pubkey()? { |
1078 | Some(ref path) if path.exists() => { | |
1079 | let pem_data = file_get_contents(path)?; | |
1080 | let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?; | |
1081 | let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?; | |
6f2626ae FG |
1082 | println!("Master key '{:?}'", path); |
1083 | ||
05389a01 WB |
1084 | (Some(Arc::new(crypt_config)), Some(enc_key)) |
1085 | } | |
1086 | _ => (Some(Arc::new(crypt_config)), None), | |
bb823140 | 1087 | } |
6d0983db DM |
1088 | } |
1089 | }; | |
f98ac774 | 1090 | |
8a8a4703 DM |
1091 | let client = BackupWriter::start( |
1092 | client, | |
b957aa81 | 1093 | crypt_config.clone(), |
8a8a4703 DM |
1094 | repo.store(), |
1095 | backup_type, | |
1096 | &backup_id, | |
1097 | backup_time, | |
1098 | verbose, | |
61d7b501 | 1099 | false |
8a8a4703 DM |
1100 | ).await?; |
1101 | ||
b957aa81 DM |
1102 | let previous_manifest = if let Ok(previous_manifest) = client.download_previous_manifest().await { |
1103 | Some(Arc::new(previous_manifest)) | |
1104 | } else { | |
1105 | None | |
1106 | }; | |
1107 | ||
6a7be83e | 1108 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time)?; |
8a8a4703 DM |
1109 | let mut manifest = BackupManifest::new(snapshot); |
1110 | ||
5d85847f DC |
1111 | let mut catalog = None; |
1112 | let mut catalog_result_tx = None; | |
8a8a4703 DM |
1113 | |
1114 | for (backup_type, filename, target, size) in upload_list { | |
1115 | match backup_type { | |
7cc3473a | 1116 | BackupSpecificationType::CONFIG => { |
5b32820e | 1117 | println!("Upload config file '{}' to '{}' as {}", filename, repo, target); |
8a8a4703 | 1118 | let stats = client |
3638341a | 1119 | .upload_blob_from_file(&filename, &target, true, crypt_mode == CryptMode::Encrypt) |
8a8a4703 | 1120 | .await?; |
f28d9088 | 1121 | manifest.add_file(target, stats.size, stats.csum, crypt_mode)?; |
8a8a4703 | 1122 | } |
7cc3473a | 1123 | BackupSpecificationType::LOGFILE => { // fixme: remove - not needed anymore ? |
5b32820e | 1124 | println!("Upload log file '{}' to '{}' as {}", filename, repo, target); |
8a8a4703 | 1125 | let stats = client |
3638341a | 1126 | .upload_blob_from_file(&filename, &target, true, crypt_mode == CryptMode::Encrypt) |
8a8a4703 | 1127 | .await?; |
f28d9088 | 1128 | manifest.add_file(target, stats.size, stats.csum, crypt_mode)?; |
8a8a4703 | 1129 | } |
7cc3473a | 1130 | BackupSpecificationType::PXAR => { |
5d85847f DC |
1131 | // start catalog upload on first use |
1132 | if catalog.is_none() { | |
3638341a | 1133 | let (cat, res) = spawn_catalog_upload(client.clone(), crypt_mode == CryptMode::Encrypt)?; |
5d85847f DC |
1134 | catalog = Some(cat); |
1135 | catalog_result_tx = Some(res); | |
1136 | } | |
1137 | let catalog = catalog.as_ref().unwrap(); | |
1138 | ||
5b32820e | 1139 | println!("Upload directory '{}' to '{}' as {}", filename, repo, target); |
8a8a4703 DM |
1140 | catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?; |
1141 | let stats = backup_directory( | |
1142 | &client, | |
b957aa81 | 1143 | previous_manifest.clone(), |
8a8a4703 DM |
1144 | &filename, |
1145 | &target, | |
1146 | chunk_size_opt, | |
1147 | devices.clone(), | |
1148 | verbose, | |
1149 | skip_lost_and_found, | |
8a8a4703 | 1150 | catalog.clone(), |
239e49f9 | 1151 | pattern_list.clone(), |
6fc053ed | 1152 | entries_max as usize, |
3638341a DM |
1153 | true, |
1154 | crypt_mode == CryptMode::Encrypt, | |
8a8a4703 | 1155 | ).await?; |
f28d9088 | 1156 | manifest.add_file(target, stats.size, stats.csum, crypt_mode)?; |
8a8a4703 DM |
1157 | catalog.lock().unwrap().end_directory()?; |
1158 | } | |
7cc3473a | 1159 | BackupSpecificationType::IMAGE => { |
8a8a4703 DM |
1160 | println!("Upload image '{}' to '{:?}' as {}", filename, repo, target); |
1161 | let stats = backup_image( | |
1162 | &client, | |
b957aa81 DM |
1163 | previous_manifest.clone(), |
1164 | &filename, | |
8a8a4703 DM |
1165 | &target, |
1166 | size, | |
1167 | chunk_size_opt, | |
3638341a DM |
1168 | true, |
1169 | crypt_mode == CryptMode::Encrypt, | |
8a8a4703 | 1170 | verbose, |
8a8a4703 | 1171 | ).await?; |
f28d9088 | 1172 | manifest.add_file(target, stats.size, stats.csum, crypt_mode)?; |
6af905c1 DM |
1173 | } |
1174 | } | |
8a8a4703 | 1175 | } |
4818c8b6 | 1176 | |
8a8a4703 | 1177 | // finalize and upload catalog |
5d85847f | 1178 | if let Some(catalog) = catalog { |
8a8a4703 DM |
1179 | let mutex = Arc::try_unwrap(catalog) |
1180 | .map_err(|_| format_err!("unable to get catalog (still used)"))?; | |
1181 | let mut catalog = mutex.into_inner().unwrap(); | |
bf6e3217 | 1182 | |
8a8a4703 | 1183 | catalog.finish()?; |
2761d6a4 | 1184 | |
8a8a4703 | 1185 | drop(catalog); // close upload stream |
2761d6a4 | 1186 | |
5d85847f DC |
1187 | if let Some(catalog_result_rx) = catalog_result_tx { |
1188 | let stats = catalog_result_rx.await??; | |
f28d9088 | 1189 | manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum, crypt_mode)?; |
5d85847f | 1190 | } |
8a8a4703 | 1191 | } |
2761d6a4 | 1192 | |
8a8a4703 | 1193 | if let Some(rsa_encrypted_key) = rsa_encrypted_key { |
5f76ac37 | 1194 | let target = "rsa-encrypted.key.blob"; |
8a8a4703 DM |
1195 | println!("Upload RSA encoded key to '{:?}' as {}", repo, target); |
1196 | let stats = client | |
3638341a | 1197 | .upload_blob_from_data(rsa_encrypted_key, target, false, false) |
8a8a4703 | 1198 | .await?; |
5f76ac37 | 1199 | manifest.add_file(target.to_string(), stats.size, stats.csum, crypt_mode)?; |
8a8a4703 DM |
1200 | |
1201 | // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t | |
1202 | /* | |
1203 | let mut buffer2 = vec![0u8; rsa.size() as usize]; | |
1204 | let pem_data = file_get_contents("master-private.pem")?; | |
1205 | let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?; | |
1206 | let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?; | |
1207 | println!("TEST {} {:?}", len, buffer2); | |
1208 | */ | |
1209 | } | |
8a8a4703 | 1210 | // create manifest (index.json) |
3638341a | 1211 | // manifests are never encrypted, but include a signature |
dfa517ad | 1212 | let manifest = manifest.to_string(crypt_config.as_ref().map(Arc::as_ref)) |
b53f6379 | 1213 | .map_err(|err| format_err!("unable to format manifest - {}", err))?; |
3638341a | 1214 | |
b53f6379 | 1215 | |
9688f6de | 1216 | if verbose { println!("Upload index.json to '{}'", repo) }; |
8a8a4703 | 1217 | client |
b53f6379 | 1218 | .upload_blob_from_data(manifest.into_bytes(), MANIFEST_BLOB_NAME, true, false) |
8a8a4703 | 1219 | .await?; |
2c3891d1 | 1220 | |
8a8a4703 | 1221 | client.finish().await?; |
c4ff3dce | 1222 | |
6a7be83e DM |
1223 | let end_time = std::time::Instant::now(); |
1224 | let elapsed = end_time.duration_since(start_time); | |
1225 | println!("Duration: {:.2}s", elapsed.as_secs_f64()); | |
3ec3ec3f | 1226 | |
6a7be83e | 1227 | println!("End Time: {}", strftime_local("%c", epoch_i64())?); |
3d5c11e5 | 1228 | |
8a8a4703 | 1229 | Ok(Value::Null) |
f98ea63d DM |
1230 | } |
1231 | ||
d0a03d40 | 1232 | fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
f98ea63d DM |
1233 | |
1234 | let mut result = vec![]; | |
1235 | ||
1236 | let data: Vec<&str> = arg.splitn(2, ':').collect(); | |
1237 | ||
bff11030 | 1238 | if data.len() != 2 { |
8968258b DM |
1239 | result.push(String::from("root.pxar:/")); |
1240 | result.push(String::from("etc.pxar:/etc")); | |
bff11030 DM |
1241 | return result; |
1242 | } | |
f98ea63d | 1243 | |
496a6784 | 1244 | let files = tools::complete_file_name(data[1], param); |
f98ea63d DM |
1245 | |
1246 | for file in files { | |
1247 | result.push(format!("{}:{}", data[0], file)); | |
1248 | } | |
1249 | ||
1250 | result | |
ff5d3707 | 1251 | } |
1252 | ||
8e6e18b7 | 1253 | async fn dump_image<W: Write>( |
88892ea8 DM |
1254 | client: Arc<BackupReader>, |
1255 | crypt_config: Option<Arc<CryptConfig>>, | |
14f6c9cb | 1256 | crypt_mode: CryptMode, |
88892ea8 DM |
1257 | index: FixedIndexReader, |
1258 | mut writer: W, | |
fd04ca7a | 1259 | verbose: bool, |
88892ea8 DM |
1260 | ) -> Result<(), Error> { |
1261 | ||
1262 | let most_used = index.find_most_used_chunks(8); | |
1263 | ||
14f6c9cb | 1264 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, crypt_mode, most_used); |
88892ea8 DM |
1265 | |
1266 | // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy | |
1267 | // and thus slows down reading. Instead, directly use RemoteChunkReader | |
fd04ca7a DM |
1268 | let mut per = 0; |
1269 | let mut bytes = 0; | |
1270 | let start_time = std::time::Instant::now(); | |
1271 | ||
88892ea8 DM |
1272 | for pos in 0..index.index_count() { |
1273 | let digest = index.index_digest(pos).unwrap(); | |
8e6e18b7 | 1274 | let raw_data = chunk_reader.read_chunk(&digest).await?; |
88892ea8 | 1275 | writer.write_all(&raw_data)?; |
fd04ca7a DM |
1276 | bytes += raw_data.len(); |
1277 | if verbose { | |
1278 | let next_per = ((pos+1)*100)/index.index_count(); | |
1279 | if per != next_per { | |
1280 | eprintln!("progress {}% (read {} bytes, duration {} sec)", | |
1281 | next_per, bytes, start_time.elapsed().as_secs()); | |
1282 | per = next_per; | |
1283 | } | |
1284 | } | |
88892ea8 DM |
1285 | } |
1286 | ||
fd04ca7a DM |
1287 | let end_time = std::time::Instant::now(); |
1288 | let elapsed = end_time.duration_since(start_time); | |
1289 | eprintln!("restore image complete (bytes={}, duration={:.2}s, speed={:.2}MB/s)", | |
1290 | bytes, | |
1291 | elapsed.as_secs_f64(), | |
1292 | bytes as f64/(1024.0*1024.0*elapsed.as_secs_f64()) | |
1293 | ); | |
1294 | ||
1295 | ||
88892ea8 DM |
1296 | Ok(()) |
1297 | } | |
1298 | ||
dc155e9b | 1299 | fn parse_archive_type(name: &str) -> (String, ArchiveType) { |
2d32fe2c TL |
1300 | if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") { |
1301 | (name.into(), archive_type(name).unwrap()) | |
1302 | } else if name.ends_with(".pxar") { | |
dc155e9b TL |
1303 | (format!("{}.didx", name), ArchiveType::DynamicIndex) |
1304 | } else if name.ends_with(".img") { | |
1305 | (format!("{}.fidx", name), ArchiveType::FixedIndex) | |
1306 | } else { | |
1307 | (format!("{}.blob", name), ArchiveType::Blob) | |
1308 | } | |
1309 | } | |
1310 | ||
a47a02ae DM |
1311 | #[api( |
1312 | input: { | |
1313 | properties: { | |
1314 | repository: { | |
1315 | schema: REPO_URL_SCHEMA, | |
1316 | optional: true, | |
1317 | }, | |
1318 | snapshot: { | |
1319 | type: String, | |
1320 | description: "Group/Snapshot path.", | |
1321 | }, | |
1322 | "archive-name": { | |
1323 | description: "Backup archive name.", | |
1324 | type: String, | |
1325 | }, | |
1326 | target: { | |
1327 | type: String, | |
90c815bf | 1328 | description: r###"Target directory path. Use '-' to write to standard output. |
8a8a4703 | 1329 | |
5eee6d89 | 1330 | We do not extraxt '.pxar' archives when writing to standard output. |
8a8a4703 | 1331 | |
a47a02ae DM |
1332 | "### |
1333 | }, | |
1334 | "allow-existing-dirs": { | |
1335 | type: Boolean, | |
1336 | description: "Do not fail if directories already exists.", | |
1337 | optional: true, | |
1338 | }, | |
1339 | keyfile: { | |
1340 | schema: KEYFILE_SCHEMA, | |
1341 | optional: true, | |
1342 | }, | |
0351f23b WB |
1343 | "keyfd": { |
1344 | schema: KEYFD_SCHEMA, | |
1345 | optional: true, | |
1346 | }, | |
24be37e3 WB |
1347 | "crypt-mode": { |
1348 | type: CryptMode, | |
96ee8577 WB |
1349 | optional: true, |
1350 | }, | |
a47a02ae DM |
1351 | } |
1352 | } | |
1353 | )] | |
1354 | /// Restore backup repository. | |
1355 | async fn restore(param: Value) -> Result<Value, Error> { | |
2665cef7 | 1356 | let repo = extract_repository_from_value(¶m)?; |
9f912493 | 1357 | |
86eda3eb DM |
1358 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
1359 | ||
46d5aa0a DM |
1360 | let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false); |
1361 | ||
d5c34d98 DM |
1362 | let archive_name = tools::required_string_param(¶m, "archive-name")?; |
1363 | ||
f3fde36b | 1364 | let client = connect(&repo)?; |
d0a03d40 | 1365 | |
d0a03d40 | 1366 | record_repository(&repo); |
d5c34d98 | 1367 | |
9f912493 | 1368 | let path = tools::required_string_param(¶m, "snapshot")?; |
9f912493 | 1369 | |
86eda3eb | 1370 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { |
d6d3b353 | 1371 | let group: BackupGroup = path.parse()?; |
27c9affb | 1372 | api_datastore_latest_snapshot(&client, repo.store(), group).await? |
d5c34d98 | 1373 | } else { |
a67f7d0a | 1374 | let snapshot: BackupDir = path.parse()?; |
86eda3eb DM |
1375 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) |
1376 | }; | |
9f912493 | 1377 | |
d5c34d98 | 1378 | let target = tools::required_string_param(¶m, "target")?; |
bf125261 | 1379 | let target = if target == "-" { None } else { Some(target) }; |
2ae7d196 | 1380 | |
0351f23b | 1381 | let (keydata, _crypt_mode) = keyfile_parameters(¶m)?; |
2ae7d196 | 1382 | |
0351f23b | 1383 | let crypt_config = match keydata { |
86eda3eb | 1384 | None => None, |
0351f23b | 1385 | Some(key) => { |
6f2626ae FG |
1386 | let (key, _, fingerprint) = decrypt_key(&key, &key::get_encryption_key_password)?; |
1387 | println!("Encryption key fingerprint: '{}'", fingerprint); | |
86eda3eb DM |
1388 | Some(Arc::new(CryptConfig::new(key)?)) |
1389 | } | |
1390 | }; | |
d5c34d98 | 1391 | |
296c50ba DM |
1392 | let client = BackupReader::start( |
1393 | client, | |
1394 | crypt_config.clone(), | |
1395 | repo.store(), | |
1396 | &backup_type, | |
1397 | &backup_id, | |
1398 | backup_time, | |
1399 | true, | |
1400 | ).await?; | |
86eda3eb | 1401 | |
2107a5ae | 1402 | let (manifest, backup_index_data) = client.download_manifest().await?; |
02fcf372 | 1403 | |
dc155e9b TL |
1404 | let (archive_name, archive_type) = parse_archive_type(archive_name); |
1405 | ||
1406 | if archive_name == MANIFEST_BLOB_NAME { | |
02fcf372 | 1407 | if let Some(target) = target { |
2107a5ae | 1408 | replace_file(target, &backup_index_data, CreateOptions::new())?; |
02fcf372 DM |
1409 | } else { |
1410 | let stdout = std::io::stdout(); | |
1411 | let mut writer = stdout.lock(); | |
2107a5ae | 1412 | writer.write_all(&backup_index_data) |
02fcf372 DM |
1413 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1414 | } | |
1415 | ||
14f6c9cb FG |
1416 | return Ok(Value::Null); |
1417 | } | |
1418 | ||
1419 | let file_info = manifest.lookup_file_info(&archive_name)?; | |
1420 | ||
1421 | if archive_type == ArchiveType::Blob { | |
d2267b11 | 1422 | |
dc155e9b | 1423 | let mut reader = client.download_blob(&manifest, &archive_name).await?; |
f8100e96 | 1424 | |
bf125261 | 1425 | if let Some(target) = target { |
0d986280 DM |
1426 | let mut writer = std::fs::OpenOptions::new() |
1427 | .write(true) | |
1428 | .create(true) | |
1429 | .create_new(true) | |
1430 | .open(target) | |
1431 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?; | |
1432 | std::io::copy(&mut reader, &mut writer)?; | |
bf125261 DM |
1433 | } else { |
1434 | let stdout = std::io::stdout(); | |
1435 | let mut writer = stdout.lock(); | |
0d986280 | 1436 | std::io::copy(&mut reader, &mut writer) |
bf125261 DM |
1437 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
1438 | } | |
f8100e96 | 1439 | |
dc155e9b | 1440 | } else if archive_type == ArchiveType::DynamicIndex { |
86eda3eb | 1441 | |
dc155e9b | 1442 | let index = client.download_dynamic_index(&manifest, &archive_name).await?; |
df65bd3d | 1443 | |
f4bf7dfc DM |
1444 | let most_used = index.find_most_used_chunks(8); |
1445 | ||
14f6c9cb | 1446 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, file_info.chunk_crypt_mode(), most_used); |
f4bf7dfc | 1447 | |
afb4cd28 | 1448 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); |
86eda3eb | 1449 | |
bf125261 | 1450 | if let Some(target) = target { |
c443f58b WB |
1451 | proxmox_backup::pxar::extract_archive( |
1452 | pxar::decoder::Decoder::from_std(reader)?, | |
1453 | Path::new(target), | |
1454 | &[], | |
d44185c4 | 1455 | true, |
5444fa94 | 1456 | proxmox_backup::pxar::Flags::DEFAULT, |
c443f58b WB |
1457 | allow_existing_dirs, |
1458 | |path| { | |
1459 | if verbose { | |
1460 | println!("{:?}", path); | |
1461 | } | |
1462 | }, | |
d9b8e2c7 | 1463 | None, |
c443f58b WB |
1464 | ) |
1465 | .map_err(|err| format_err!("error extracting archive - {}", err))?; | |
bf125261 | 1466 | } else { |
88892ea8 DM |
1467 | let mut writer = std::fs::OpenOptions::new() |
1468 | .write(true) | |
1469 | .open("/dev/stdout") | |
1470 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))?; | |
afb4cd28 | 1471 | |
bf125261 DM |
1472 | std::io::copy(&mut reader, &mut writer) |
1473 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
1474 | } | |
dc155e9b | 1475 | } else if archive_type == ArchiveType::FixedIndex { |
afb4cd28 | 1476 | |
dc155e9b | 1477 | let index = client.download_fixed_index(&manifest, &archive_name).await?; |
df65bd3d | 1478 | |
88892ea8 DM |
1479 | let mut writer = if let Some(target) = target { |
1480 | std::fs::OpenOptions::new() | |
bf125261 DM |
1481 | .write(true) |
1482 | .create(true) | |
1483 | .create_new(true) | |
1484 | .open(target) | |
88892ea8 | 1485 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))? |
bf125261 | 1486 | } else { |
88892ea8 DM |
1487 | std::fs::OpenOptions::new() |
1488 | .write(true) | |
1489 | .open("/dev/stdout") | |
1490 | .map_err(|err| format_err!("unable to open /dev/stdout - {}", err))? | |
1491 | }; | |
afb4cd28 | 1492 | |
14f6c9cb | 1493 | dump_image(client.clone(), crypt_config.clone(), file_info.chunk_crypt_mode(), index, &mut writer, verbose).await?; |
3031e44c | 1494 | } |
fef44d4f DM |
1495 | |
1496 | Ok(Value::Null) | |
45db6f89 DM |
1497 | } |
1498 | ||
a47a02ae DM |
1499 | #[api( |
1500 | input: { | |
1501 | properties: { | |
1502 | repository: { | |
1503 | schema: REPO_URL_SCHEMA, | |
1504 | optional: true, | |
1505 | }, | |
1506 | snapshot: { | |
1507 | type: String, | |
1508 | description: "Group/Snapshot path.", | |
1509 | }, | |
1510 | logfile: { | |
1511 | type: String, | |
1512 | description: "The path to the log file you want to upload.", | |
1513 | }, | |
1514 | keyfile: { | |
1515 | schema: KEYFILE_SCHEMA, | |
1516 | optional: true, | |
1517 | }, | |
0351f23b WB |
1518 | "keyfd": { |
1519 | schema: KEYFD_SCHEMA, | |
1520 | optional: true, | |
1521 | }, | |
24be37e3 WB |
1522 | "crypt-mode": { |
1523 | type: CryptMode, | |
96ee8577 WB |
1524 | optional: true, |
1525 | }, | |
a47a02ae DM |
1526 | } |
1527 | } | |
1528 | )] | |
1529 | /// Upload backup log file. | |
1530 | async fn upload_log(param: Value) -> Result<Value, Error> { | |
ec34f7eb DM |
1531 | |
1532 | let logfile = tools::required_string_param(¶m, "logfile")?; | |
1533 | let repo = extract_repository_from_value(¶m)?; | |
1534 | ||
1535 | let snapshot = tools::required_string_param(¶m, "snapshot")?; | |
a67f7d0a | 1536 | let snapshot: BackupDir = snapshot.parse()?; |
ec34f7eb | 1537 | |
f3fde36b | 1538 | let mut client = connect(&repo)?; |
ec34f7eb | 1539 | |
0351f23b | 1540 | let (keydata, crypt_mode) = keyfile_parameters(¶m)?; |
ec34f7eb | 1541 | |
0351f23b | 1542 | let crypt_config = match keydata { |
ec34f7eb | 1543 | None => None, |
0351f23b | 1544 | Some(key) => { |
37e60ddc | 1545 | let (key, _created, _) = decrypt_key(&key, &key::get_encryption_key_password)?; |
ec34f7eb | 1546 | let crypt_config = CryptConfig::new(key)?; |
9025312a | 1547 | Some(Arc::new(crypt_config)) |
ec34f7eb DM |
1548 | } |
1549 | }; | |
1550 | ||
e18a6c9e | 1551 | let data = file_get_contents(logfile)?; |
ec34f7eb | 1552 | |
3638341a | 1553 | // fixme: howto sign log? |
f28d9088 | 1554 | let blob = match crypt_mode { |
3638341a DM |
1555 | CryptMode::None | CryptMode::SignOnly => DataBlob::encode(&data, None, true)?, |
1556 | CryptMode::Encrypt => DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?, | |
f28d9088 | 1557 | }; |
ec34f7eb DM |
1558 | |
1559 | let raw_data = blob.into_inner(); | |
1560 | ||
1561 | let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store()); | |
1562 | ||
1563 | let args = json!({ | |
1564 | "backup-type": snapshot.group().backup_type(), | |
1565 | "backup-id": snapshot.group().backup_id(), | |
6a7be83e | 1566 | "backup-time": snapshot.backup_time(), |
ec34f7eb DM |
1567 | }); |
1568 | ||
1569 | let body = hyper::Body::from(raw_data); | |
1570 | ||
8a8a4703 | 1571 | client.upload("application/octet-stream", body, &path, Some(args)).await |
ec34f7eb DM |
1572 | } |
1573 | ||
032d3ad8 DM |
1574 | const API_METHOD_PRUNE: ApiMethod = ApiMethod::new( |
1575 | &ApiHandler::Async(&prune), | |
1576 | &ObjectSchema::new( | |
1577 | "Prune a backup repository.", | |
1578 | &proxmox_backup::add_common_prune_prameters!([ | |
1579 | ("dry-run", true, &BooleanSchema::new( | |
1580 | "Just show what prune would do, but do not delete anything.") | |
1581 | .schema()), | |
1582 | ("group", false, &StringSchema::new("Backup group.").schema()), | |
1583 | ], [ | |
1584 | ("output-format", true, &OUTPUT_FORMAT), | |
c48aa39f DM |
1585 | ( |
1586 | "quiet", | |
1587 | true, | |
1588 | &BooleanSchema::new("Minimal output - only show removals.") | |
1589 | .schema() | |
1590 | ), | |
032d3ad8 DM |
1591 | ("repository", true, &REPO_URL_SCHEMA), |
1592 | ]) | |
1593 | ) | |
1594 | ); | |
1595 | ||
1596 | fn prune<'a>( | |
1597 | param: Value, | |
1598 | _info: &ApiMethod, | |
1599 | _rpcenv: &'a mut dyn RpcEnvironment, | |
1600 | ) -> proxmox::api::ApiFuture<'a> { | |
1601 | async move { | |
1602 | prune_async(param).await | |
1603 | }.boxed() | |
1604 | } | |
83b7db02 | 1605 | |
032d3ad8 | 1606 | async fn prune_async(mut param: Value) -> Result<Value, Error> { |
2665cef7 | 1607 | let repo = extract_repository_from_value(¶m)?; |
83b7db02 | 1608 | |
f3fde36b | 1609 | let mut client = connect(&repo)?; |
83b7db02 | 1610 | |
d0a03d40 | 1611 | let path = format!("api2/json/admin/datastore/{}/prune", repo.store()); |
83b7db02 | 1612 | |
9fdc3ef4 | 1613 | let group = tools::required_string_param(¶m, "group")?; |
d6d3b353 | 1614 | let group: BackupGroup = group.parse()?; |
c2043614 DM |
1615 | |
1616 | let output_format = get_output_format(¶m); | |
9fdc3ef4 | 1617 | |
c48aa39f DM |
1618 | let quiet = param["quiet"].as_bool().unwrap_or(false); |
1619 | ||
ea7a7ef2 DM |
1620 | param.as_object_mut().unwrap().remove("repository"); |
1621 | param.as_object_mut().unwrap().remove("group"); | |
163e9bbe | 1622 | param.as_object_mut().unwrap().remove("output-format"); |
c48aa39f | 1623 | param.as_object_mut().unwrap().remove("quiet"); |
ea7a7ef2 DM |
1624 | |
1625 | param["backup-type"] = group.backup_type().into(); | |
1626 | param["backup-id"] = group.backup_id().into(); | |
83b7db02 | 1627 | |
db1e061d | 1628 | let mut result = client.post(&path, Some(param)).await?; |
74fa81b8 | 1629 | |
87c42375 | 1630 | record_repository(&repo); |
3b03abfe | 1631 | |
db1e061d DM |
1632 | let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> { |
1633 | let item: PruneListItem = serde_json::from_value(record.to_owned())?; | |
e0e5b442 | 1634 | let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time)?; |
db1e061d DM |
1635 | Ok(snapshot.relative_path().to_str().unwrap().to_owned()) |
1636 | }; | |
1637 | ||
c48aa39f DM |
1638 | let render_prune_action = |v: &Value, _record: &Value| -> Result<String, Error> { |
1639 | Ok(match v.as_bool() { | |
1640 | Some(true) => "keep", | |
1641 | Some(false) => "remove", | |
1642 | None => "unknown", | |
1643 | }.to_string()) | |
1644 | }; | |
1645 | ||
db1e061d DM |
1646 | let options = default_table_format_options() |
1647 | .sortby("backup-type", false) | |
1648 | .sortby("backup-id", false) | |
1649 | .sortby("backup-time", false) | |
1650 | .column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot")) | |
74f7240b | 1651 | .column(ColumnConfig::new("backup-time").renderer(tools::format::render_epoch).header("date")) |
c48aa39f | 1652 | .column(ColumnConfig::new("keep").renderer(render_prune_action).header("action")) |
db1e061d DM |
1653 | ; |
1654 | ||
1655 | let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_PRUNE; | |
1656 | ||
1657 | let mut data = result["data"].take(); | |
1658 | ||
c48aa39f DM |
1659 | if quiet { |
1660 | let list: Vec<Value> = data.as_array().unwrap().iter().filter(|item| { | |
1661 | item["keep"].as_bool() == Some(false) | |
1662 | }).map(|v| v.clone()).collect(); | |
1663 | data = list.into(); | |
1664 | } | |
1665 | ||
db1e061d | 1666 | format_and_print_result_full(&mut data, info, &output_format, &options); |
d0a03d40 | 1667 | |
43a406fd | 1668 | Ok(Value::Null) |
83b7db02 DM |
1669 | } |
1670 | ||
a47a02ae DM |
1671 | #[api( |
1672 | input: { | |
1673 | properties: { | |
1674 | repository: { | |
1675 | schema: REPO_URL_SCHEMA, | |
1676 | optional: true, | |
1677 | }, | |
1678 | "output-format": { | |
1679 | schema: OUTPUT_FORMAT, | |
1680 | optional: true, | |
1681 | }, | |
1682 | } | |
f9beae9c TL |
1683 | }, |
1684 | returns: { | |
1685 | type: StorageStatus, | |
1686 | }, | |
a47a02ae DM |
1687 | )] |
1688 | /// Get repository status. | |
1689 | async fn status(param: Value) -> Result<Value, Error> { | |
34a816cc DM |
1690 | |
1691 | let repo = extract_repository_from_value(¶m)?; | |
1692 | ||
c2043614 | 1693 | let output_format = get_output_format(¶m); |
34a816cc | 1694 | |
f3fde36b | 1695 | let client = connect(&repo)?; |
34a816cc DM |
1696 | |
1697 | let path = format!("api2/json/admin/datastore/{}/status", repo.store()); | |
1698 | ||
1dc117bb | 1699 | let mut result = client.get(&path, None).await?; |
14e08625 | 1700 | let mut data = result["data"].take(); |
34a816cc DM |
1701 | |
1702 | record_repository(&repo); | |
1703 | ||
390c5bdd DM |
1704 | let render_total_percentage = |v: &Value, record: &Value| -> Result<String, Error> { |
1705 | let v = v.as_u64().unwrap(); | |
1706 | let total = record["total"].as_u64().unwrap(); | |
1707 | let roundup = total/200; | |
1708 | let per = ((v+roundup)*100)/total; | |
e23f5863 DM |
1709 | let info = format!(" ({} %)", per); |
1710 | Ok(format!("{} {:>8}", v, info)) | |
390c5bdd | 1711 | }; |
1dc117bb | 1712 | |
c2043614 | 1713 | let options = default_table_format_options() |
be2425ff | 1714 | .noheader(true) |
e23f5863 | 1715 | .column(ColumnConfig::new("total").renderer(render_total_percentage)) |
390c5bdd DM |
1716 | .column(ColumnConfig::new("used").renderer(render_total_percentage)) |
1717 | .column(ColumnConfig::new("avail").renderer(render_total_percentage)); | |
34a816cc | 1718 | |
f9beae9c | 1719 | let schema = &API_RETURN_SCHEMA_STATUS; |
390c5bdd DM |
1720 | |
1721 | format_and_print_result_full(&mut data, schema, &output_format, &options); | |
34a816cc DM |
1722 | |
1723 | Ok(Value::Null) | |
1724 | } | |
1725 | ||
5a2df000 | 1726 | // like get, but simply ignore errors and return Null instead |
e9722f8b | 1727 | async fn try_get(repo: &BackupRepository, url: &str) -> Value { |
024f11bb | 1728 | |
a05c0c6f | 1729 | let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok(); |
d1c65727 | 1730 | let password = std::env::var(ENV_VAR_PBS_PASSWORD).ok(); |
a05c0c6f | 1731 | |
d59dbeca | 1732 | let options = HttpClientOptions::new() |
5030b7ce | 1733 | .prefix(Some("proxmox-backup".to_string())) |
d1c65727 | 1734 | .password(password) |
d59dbeca | 1735 | .interactive(false) |
a05c0c6f | 1736 | .fingerprint(fingerprint) |
5a74756c | 1737 | .fingerprint_cache(true) |
d59dbeca DM |
1738 | .ticket_cache(true); |
1739 | ||
34aa8e13 | 1740 | let client = match HttpClient::new(repo.host(), repo.port(), repo.auth_id(), options) { |
45cdce06 DM |
1741 | Ok(v) => v, |
1742 | _ => return Value::Null, | |
1743 | }; | |
b2388518 | 1744 | |
e9722f8b | 1745 | let mut resp = match client.get(url, None).await { |
b2388518 DM |
1746 | Ok(v) => v, |
1747 | _ => return Value::Null, | |
1748 | }; | |
1749 | ||
1750 | if let Some(map) = resp.as_object_mut() { | |
1751 | if let Some(data) = map.remove("data") { | |
1752 | return data; | |
1753 | } | |
1754 | } | |
1755 | Value::Null | |
1756 | } | |
1757 | ||
b2388518 | 1758 | fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
3f06d6fb | 1759 | proxmox_backup::tools::runtime::main(async { complete_backup_group_do(param).await }) |
e9722f8b WB |
1760 | } |
1761 | ||
1762 | async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> { | |
024f11bb | 1763 | |
b2388518 DM |
1764 | let mut result = vec![]; |
1765 | ||
2665cef7 | 1766 | let repo = match extract_repository_from_map(param) { |
b2388518 | 1767 | Some(v) => v, |
024f11bb DM |
1768 | _ => return result, |
1769 | }; | |
1770 | ||
b2388518 DM |
1771 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
1772 | ||
e9722f8b | 1773 | let data = try_get(&repo, &path).await; |
b2388518 DM |
1774 | |
1775 | if let Some(list) = data.as_array() { | |
024f11bb | 1776 | for item in list { |
98f0b972 DM |
1777 | if let (Some(backup_id), Some(backup_type)) = |
1778 | (item["backup-id"].as_str(), item["backup-type"].as_str()) | |
1779 | { | |
1780 | result.push(format!("{}/{}", backup_type, backup_id)); | |
024f11bb DM |
1781 | } |
1782 | } | |
1783 | } | |
1784 | ||
1785 | result | |
1786 | } | |
1787 | ||
43abba4b | 1788 | pub fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
3f06d6fb | 1789 | proxmox_backup::tools::runtime::main(async { complete_group_or_snapshot_do(arg, param).await }) |
e9722f8b WB |
1790 | } |
1791 | ||
1792 | async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
b2388518 | 1793 | |
b2388518 | 1794 | if arg.matches('/').count() < 2 { |
e9722f8b | 1795 | let groups = complete_backup_group_do(param).await; |
543a260f | 1796 | let mut result = vec![]; |
b2388518 DM |
1797 | for group in groups { |
1798 | result.push(group.to_string()); | |
1799 | result.push(format!("{}/", group)); | |
1800 | } | |
1801 | return result; | |
1802 | } | |
1803 | ||
e9722f8b | 1804 | complete_backup_snapshot_do(param).await |
543a260f | 1805 | } |
b2388518 | 1806 | |
3fb53e07 | 1807 | fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
3f06d6fb | 1808 | proxmox_backup::tools::runtime::main(async { complete_backup_snapshot_do(param).await }) |
e9722f8b WB |
1809 | } |
1810 | ||
1811 | async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> { | |
543a260f DM |
1812 | |
1813 | let mut result = vec![]; | |
1814 | ||
1815 | let repo = match extract_repository_from_map(param) { | |
1816 | Some(v) => v, | |
1817 | _ => return result, | |
1818 | }; | |
1819 | ||
1820 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); | |
b2388518 | 1821 | |
e9722f8b | 1822 | let data = try_get(&repo, &path).await; |
b2388518 DM |
1823 | |
1824 | if let Some(list) = data.as_array() { | |
1825 | for item in list { | |
1826 | if let (Some(backup_id), Some(backup_type), Some(backup_time)) = | |
1827 | (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64()) | |
1828 | { | |
e0e5b442 FG |
1829 | if let Ok(snapshot) = BackupDir::new(backup_type, backup_id, backup_time) { |
1830 | result.push(snapshot.relative_path().to_str().unwrap().to_owned()); | |
1831 | } | |
b2388518 DM |
1832 | } |
1833 | } | |
1834 | } | |
1835 | ||
1836 | result | |
1837 | } | |
1838 | ||
45db6f89 | 1839 | fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
3f06d6fb | 1840 | proxmox_backup::tools::runtime::main(async { complete_server_file_name_do(param).await }) |
e9722f8b WB |
1841 | } |
1842 | ||
1843 | async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> { | |
08dc340a DM |
1844 | |
1845 | let mut result = vec![]; | |
1846 | ||
2665cef7 | 1847 | let repo = match extract_repository_from_map(param) { |
08dc340a DM |
1848 | Some(v) => v, |
1849 | _ => return result, | |
1850 | }; | |
1851 | ||
a67f7d0a | 1852 | let snapshot: BackupDir = match param.get("snapshot") { |
08dc340a | 1853 | Some(path) => { |
a67f7d0a | 1854 | match path.parse() { |
08dc340a DM |
1855 | Ok(v) => v, |
1856 | _ => return result, | |
1857 | } | |
1858 | } | |
1859 | _ => return result, | |
1860 | }; | |
1861 | ||
1862 | let query = tools::json_object_to_query(json!({ | |
1863 | "backup-type": snapshot.group().backup_type(), | |
1864 | "backup-id": snapshot.group().backup_id(), | |
6a7be83e | 1865 | "backup-time": snapshot.backup_time(), |
08dc340a DM |
1866 | })).unwrap(); |
1867 | ||
1868 | let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query); | |
1869 | ||
e9722f8b | 1870 | let data = try_get(&repo, &path).await; |
08dc340a DM |
1871 | |
1872 | if let Some(list) = data.as_array() { | |
1873 | for item in list { | |
c4f025eb | 1874 | if let Some(filename) = item["filename"].as_str() { |
08dc340a DM |
1875 | result.push(filename.to_owned()); |
1876 | } | |
1877 | } | |
1878 | } | |
1879 | ||
45db6f89 DM |
1880 | result |
1881 | } | |
1882 | ||
1883 | fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
52c171e4 | 1884 | complete_server_file_name(arg, param) |
e9722f8b | 1885 | .iter() |
708fab30 | 1886 | .map(|v| tools::format::strip_server_file_extension(&v)) |
e9722f8b | 1887 | .collect() |
08dc340a DM |
1888 | } |
1889 | ||
43abba4b | 1890 | pub fn complete_pxar_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
0ec9e1b0 DM |
1891 | complete_server_file_name(arg, param) |
1892 | .iter() | |
2995aedf DM |
1893 | .filter_map(|name| { |
1894 | if name.ends_with(".pxar.didx") { | |
708fab30 | 1895 | Some(tools::format::strip_server_file_extension(name)) |
2995aedf DM |
1896 | } else { |
1897 | None | |
1898 | } | |
1899 | }) | |
1900 | .collect() | |
1901 | } | |
1902 | ||
1903 | pub fn complete_img_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
1904 | complete_server_file_name(arg, param) | |
1905 | .iter() | |
1906 | .filter_map(|name| { | |
1907 | if name.ends_with(".img.fidx") { | |
708fab30 | 1908 | Some(tools::format::strip_server_file_extension(name)) |
0ec9e1b0 DM |
1909 | } else { |
1910 | None | |
1911 | } | |
1912 | }) | |
1913 | .collect() | |
1914 | } | |
1915 | ||
49811347 DM |
1916 | fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
1917 | ||
1918 | let mut result = vec![]; | |
1919 | ||
1920 | let mut size = 64; | |
1921 | loop { | |
1922 | result.push(size.to_string()); | |
11377a47 | 1923 | size *= 2; |
49811347 DM |
1924 | if size > 4096 { break; } |
1925 | } | |
1926 | ||
1927 | result | |
1928 | } | |
1929 | ||
0224c3c2 FG |
1930 | fn complete_auth_id(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
1931 | proxmox_backup::tools::runtime::main(async { complete_auth_id_do(param).await }) | |
1932 | } | |
1933 | ||
1934 | async fn complete_auth_id_do(param: &HashMap<String, String>) -> Vec<String> { | |
1935 | ||
1936 | let mut result = vec![]; | |
1937 | ||
1938 | let repo = match extract_repository_from_map(param) { | |
1939 | Some(v) => v, | |
1940 | _ => return result, | |
1941 | }; | |
1942 | ||
1943 | let data = try_get(&repo, "api2/json/access/users?include_tokens=true").await; | |
1944 | ||
1945 | if let Ok(parsed) = serde_json::from_value::<Vec<UserWithTokens>>(data) { | |
1946 | for user in parsed { | |
1947 | result.push(user.userid.to_string()); | |
1948 | for token in user.tokens { | |
1949 | result.push(token.tokenid.to_string()); | |
1950 | } | |
1951 | } | |
1952 | }; | |
1953 | ||
1954 | result | |
1955 | } | |
1956 | ||
c443f58b WB |
1957 | use proxmox_backup::client::RemoteChunkReader; |
1958 | /// This is a workaround until we have cleaned up the chunk/reader/... infrastructure for better | |
1959 | /// async use! | |
1960 | /// | |
1961 | /// Ideally BufferedDynamicReader gets replaced so the LruCache maps to `BroadcastFuture<Chunk>`, | |
1962 | /// so that we can properly access it from multiple threads simultaneously while not issuing | |
1963 | /// duplicate simultaneous reads over http. | |
43abba4b | 1964 | pub struct BufferedDynamicReadAt { |
c443f58b WB |
1965 | inner: Mutex<BufferedDynamicReader<RemoteChunkReader>>, |
1966 | } | |
1967 | ||
1968 | impl BufferedDynamicReadAt { | |
1969 | fn new(inner: BufferedDynamicReader<RemoteChunkReader>) -> Self { | |
1970 | Self { | |
1971 | inner: Mutex::new(inner), | |
1972 | } | |
1973 | } | |
1974 | } | |
1975 | ||
a6f87283 WB |
1976 | impl ReadAt for BufferedDynamicReadAt { |
1977 | fn start_read_at<'a>( | |
1978 | self: Pin<&'a Self>, | |
c443f58b | 1979 | _cx: &mut Context, |
a6f87283 | 1980 | buf: &'a mut [u8], |
c443f58b | 1981 | offset: u64, |
a6f87283 | 1982 | ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> { |
a6f87283 | 1983 | MaybeReady::Ready(tokio::task::block_in_place(move || { |
c443f58b WB |
1984 | let mut reader = self.inner.lock().unwrap(); |
1985 | reader.seek(SeekFrom::Start(offset))?; | |
a6f87283 WB |
1986 | Ok(reader.read(buf)?) |
1987 | })) | |
1988 | } | |
1989 | ||
1990 | fn poll_complete<'a>( | |
1991 | self: Pin<&'a Self>, | |
1992 | _op: ReadAtOperation<'a>, | |
1993 | ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> { | |
1994 | panic!("LocalDynamicReadAt::start_read_at returned Pending"); | |
c443f58b WB |
1995 | } |
1996 | } | |
1997 | ||
f2401311 | 1998 | fn main() { |
33d64b81 | 1999 | |
255f378a | 2000 | let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP) |
49fddd98 | 2001 | .arg_param(&["backupspec"]) |
d0a03d40 | 2002 | .completion_cb("repository", complete_repository) |
49811347 | 2003 | .completion_cb("backupspec", complete_backup_source) |
6d0983db | 2004 | .completion_cb("keyfile", tools::complete_file_name) |
49811347 | 2005 | .completion_cb("chunk-size", complete_chunk_size); |
f8838fe9 | 2006 | |
caea8d61 DM |
2007 | let benchmark_cmd_def = CliCommand::new(&API_METHOD_BENCHMARK) |
2008 | .completion_cb("repository", complete_repository) | |
2009 | .completion_cb("keyfile", tools::complete_file_name); | |
2010 | ||
255f378a | 2011 | let upload_log_cmd_def = CliCommand::new(&API_METHOD_UPLOAD_LOG) |
49fddd98 | 2012 | .arg_param(&["snapshot", "logfile"]) |
543a260f | 2013 | .completion_cb("snapshot", complete_backup_snapshot) |
ec34f7eb DM |
2014 | .completion_cb("logfile", tools::complete_file_name) |
2015 | .completion_cb("keyfile", tools::complete_file_name) | |
2016 | .completion_cb("repository", complete_repository); | |
2017 | ||
255f378a | 2018 | let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS) |
d0a03d40 | 2019 | .completion_cb("repository", complete_repository); |
41c039e1 | 2020 | |
255f378a | 2021 | let snapshots_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOTS) |
49fddd98 | 2022 | .arg_param(&["group"]) |
024f11bb | 2023 | .completion_cb("group", complete_backup_group) |
d0a03d40 | 2024 | .completion_cb("repository", complete_repository); |
184f17af | 2025 | |
255f378a | 2026 | let forget_cmd_def = CliCommand::new(&API_METHOD_FORGET_SNAPSHOTS) |
49fddd98 | 2027 | .arg_param(&["snapshot"]) |
b2388518 | 2028 | .completion_cb("repository", complete_repository) |
543a260f | 2029 | .completion_cb("snapshot", complete_backup_snapshot); |
6f62c924 | 2030 | |
255f378a | 2031 | let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION) |
d0a03d40 | 2032 | .completion_cb("repository", complete_repository); |
8cc0d6af | 2033 | |
255f378a | 2034 | let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE) |
49fddd98 | 2035 | .arg_param(&["snapshot", "archive-name", "target"]) |
b2388518 | 2036 | .completion_cb("repository", complete_repository) |
08dc340a DM |
2037 | .completion_cb("snapshot", complete_group_or_snapshot) |
2038 | .completion_cb("archive-name", complete_archive_name) | |
2039 | .completion_cb("target", tools::complete_file_name); | |
9f912493 | 2040 | |
255f378a | 2041 | let files_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOT_FILES) |
49fddd98 | 2042 | .arg_param(&["snapshot"]) |
52c171e4 | 2043 | .completion_cb("repository", complete_repository) |
543a260f | 2044 | .completion_cb("snapshot", complete_backup_snapshot); |
52c171e4 | 2045 | |
255f378a | 2046 | let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE) |
49fddd98 | 2047 | .arg_param(&["group"]) |
9fdc3ef4 | 2048 | .completion_cb("group", complete_backup_group) |
d0a03d40 | 2049 | .completion_cb("repository", complete_repository); |
9f912493 | 2050 | |
255f378a | 2051 | let status_cmd_def = CliCommand::new(&API_METHOD_STATUS) |
34a816cc DM |
2052 | .completion_cb("repository", complete_repository); |
2053 | ||
255f378a | 2054 | let login_cmd_def = CliCommand::new(&API_METHOD_API_LOGIN) |
e240d8be DM |
2055 | .completion_cb("repository", complete_repository); |
2056 | ||
255f378a | 2057 | let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT) |
e240d8be | 2058 | .completion_cb("repository", complete_repository); |
32efac1c | 2059 | |
e39974af TL |
2060 | let version_cmd_def = CliCommand::new(&API_METHOD_API_VERSION) |
2061 | .completion_cb("repository", complete_repository); | |
2062 | ||
344add38 DW |
2063 | let change_owner_cmd_def = CliCommand::new(&API_METHOD_CHANGE_BACKUP_OWNER) |
2064 | .arg_param(&["group", "new-owner"]) | |
2065 | .completion_cb("group", complete_backup_group) | |
0224c3c2 | 2066 | .completion_cb("new-owner", complete_auth_id) |
344add38 DW |
2067 | .completion_cb("repository", complete_repository); |
2068 | ||
41c039e1 | 2069 | let cmd_def = CliCommandMap::new() |
48ef3c33 DM |
2070 | .insert("backup", backup_cmd_def) |
2071 | .insert("upload-log", upload_log_cmd_def) | |
2072 | .insert("forget", forget_cmd_def) | |
2073 | .insert("garbage-collect", garbage_collect_cmd_def) | |
2074 | .insert("list", list_cmd_def) | |
2075 | .insert("login", login_cmd_def) | |
2076 | .insert("logout", logout_cmd_def) | |
2077 | .insert("prune", prune_cmd_def) | |
2078 | .insert("restore", restore_cmd_def) | |
2079 | .insert("snapshots", snapshots_cmd_def) | |
2080 | .insert("files", files_cmd_def) | |
2081 | .insert("status", status_cmd_def) | |
9696f519 | 2082 | .insert("key", key::cli()) |
43abba4b | 2083 | .insert("mount", mount_cmd_def()) |
45f9b32e SR |
2084 | .insert("map", map_cmd_def()) |
2085 | .insert("unmap", unmap_cmd_def()) | |
5830c205 | 2086 | .insert("catalog", catalog_mgmt_cli()) |
caea8d61 | 2087 | .insert("task", task_mgmt_cli()) |
e39974af | 2088 | .insert("version", version_cmd_def) |
344add38 DW |
2089 | .insert("benchmark", benchmark_cmd_def) |
2090 | .insert("change-owner", change_owner_cmd_def); | |
48ef3c33 | 2091 | |
7b22acd0 DM |
2092 | let rpcenv = CliEnvironment::new(); |
2093 | run_cli_command(cmd_def, rpcenv, Some(|future| { | |
d08bc483 DM |
2094 | proxmox_backup::tools::runtime::main(future) |
2095 | })); | |
ff5d3707 | 2096 | } |