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