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