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