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