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