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