]>
Commit | Line | Data |
---|---|---|
826f309b | 1 | //#[macro_use] |
fe0e04c6 | 2 | extern crate proxmox_backup; |
ff5d3707 | 3 | |
4 | use failure::*; | |
728797d0 | 5 | //use std::os::unix::io::AsRawFd; |
fa5d6977 | 6 | use chrono::{Local, Utc, TimeZone}; |
e9c9409a | 7 | use std::path::{Path, PathBuf}; |
2eeaacb9 | 8 | use std::collections::{HashSet, HashMap}; |
bf125261 | 9 | use std::io::Write; |
ff5d3707 | 10 | |
fe0e04c6 | 11 | use proxmox_backup::tools; |
4de0e142 | 12 | use proxmox_backup::cli::*; |
bbf9e7e9 | 13 | use proxmox_backup::api2::types::*; |
ef2f2efb | 14 | use proxmox_backup::api_schema::*; |
dc9a007b | 15 | use proxmox_backup::api_schema::router::*; |
151c6ce2 | 16 | use proxmox_backup::client::*; |
247cdbce | 17 | use proxmox_backup::backup::*; |
86eda3eb DM |
18 | use proxmox_backup::pxar; |
19 | ||
fe0e04c6 DM |
20 | //use proxmox_backup::backup::image_index::*; |
21 | //use proxmox_backup::config::datastore; | |
8968258b | 22 | //use proxmox_backup::pxar::encoder::*; |
728797d0 | 23 | //use proxmox_backup::backup::datastore::*; |
23bb8780 | 24 | |
f5f13ebc | 25 | use serde_json::{json, Value}; |
1c0472e8 | 26 | //use hyper::Body; |
33d64b81 | 27 | use std::sync::Arc; |
ae0be2dd | 28 | use regex::Regex; |
d0a03d40 | 29 | use xdg::BaseDirectories; |
ae0be2dd DM |
30 | |
31 | use lazy_static::lazy_static; | |
5a2df000 | 32 | use futures::*; |
c4ff3dce | 33 | use tokio::sync::mpsc; |
ae0be2dd DM |
34 | |
35 | lazy_static! { | |
79679c2d | 36 | static ref BACKUPSPEC_REGEX: Regex = Regex::new(r"^([a-zA-Z0-9_-]+\.(?:pxar|img|conf|log)):(.+)$").unwrap(); |
f2401311 DM |
37 | |
38 | static ref REPO_URL_SCHEMA: Arc<Schema> = Arc::new( | |
39 | StringSchema::new("Repository URL.") | |
40 | .format(BACKUP_REPO_URL.clone()) | |
41 | .max_length(256) | |
42 | .into() | |
43 | ); | |
ae0be2dd | 44 | } |
33d64b81 | 45 | |
d0a03d40 | 46 | |
2665cef7 DM |
47 | fn get_default_repository() -> Option<String> { |
48 | std::env::var("PBS_REPOSITORY").ok() | |
49 | } | |
50 | ||
51 | fn extract_repository_from_value( | |
52 | param: &Value, | |
53 | ) -> Result<BackupRepository, Error> { | |
54 | ||
55 | let repo_url = param["repository"] | |
56 | .as_str() | |
57 | .map(String::from) | |
58 | .or_else(get_default_repository) | |
59 | .ok_or_else(|| format_err!("unable to get (default) repository"))?; | |
60 | ||
61 | let repo: BackupRepository = repo_url.parse()?; | |
62 | ||
63 | Ok(repo) | |
64 | } | |
65 | ||
66 | fn extract_repository_from_map( | |
67 | param: &HashMap<String, String>, | |
68 | ) -> Option<BackupRepository> { | |
69 | ||
70 | param.get("repository") | |
71 | .map(String::from) | |
72 | .or_else(get_default_repository) | |
73 | .and_then(|repo_url| repo_url.parse::<BackupRepository>().ok()) | |
74 | } | |
75 | ||
d0a03d40 DM |
76 | fn record_repository(repo: &BackupRepository) { |
77 | ||
78 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
79 | Ok(v) => v, | |
80 | _ => return, | |
81 | }; | |
82 | ||
83 | // usually $HOME/.cache/proxmox-backup/repo-list | |
84 | let path = match base.place_cache_file("repo-list") { | |
85 | Ok(v) => v, | |
86 | _ => return, | |
87 | }; | |
88 | ||
49cf9f3d | 89 | let mut data = tools::file_get_json(&path, None).unwrap_or(json!({})); |
d0a03d40 DM |
90 | |
91 | let repo = repo.to_string(); | |
92 | ||
93 | data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 }; | |
94 | ||
95 | let mut map = serde_json::map::Map::new(); | |
96 | ||
97 | loop { | |
98 | let mut max_used = 0; | |
99 | let mut max_repo = None; | |
100 | for (repo, count) in data.as_object().unwrap() { | |
101 | if map.contains_key(repo) { continue; } | |
102 | if let Some(count) = count.as_i64() { | |
103 | if count > max_used { | |
104 | max_used = count; | |
105 | max_repo = Some(repo); | |
106 | } | |
107 | } | |
108 | } | |
109 | if let Some(repo) = max_repo { | |
110 | map.insert(repo.to_owned(), json!(max_used)); | |
111 | } else { | |
112 | break; | |
113 | } | |
114 | if map.len() > 10 { // store max. 10 repos | |
115 | break; | |
116 | } | |
117 | } | |
118 | ||
119 | let new_data = json!(map); | |
120 | ||
121 | let _ = tools::file_set_contents(path, new_data.to_string().as_bytes(), None); | |
122 | } | |
123 | ||
49811347 | 124 | fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
d0a03d40 DM |
125 | |
126 | let mut result = vec![]; | |
127 | ||
128 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
129 | Ok(v) => v, | |
130 | _ => return result, | |
131 | }; | |
132 | ||
133 | // usually $HOME/.cache/proxmox-backup/repo-list | |
134 | let path = match base.place_cache_file("repo-list") { | |
135 | Ok(v) => v, | |
136 | _ => return result, | |
137 | }; | |
138 | ||
49cf9f3d | 139 | let data = tools::file_get_json(&path, None).unwrap_or(json!({})); |
d0a03d40 DM |
140 | |
141 | if let Some(map) = data.as_object() { | |
49811347 | 142 | for (repo, _count) in map { |
d0a03d40 DM |
143 | result.push(repo.to_owned()); |
144 | } | |
145 | } | |
146 | ||
147 | result | |
148 | } | |
149 | ||
17d6979a | 150 | fn backup_directory<P: AsRef<Path>>( |
c4ff3dce | 151 | client: &BackupClient, |
17d6979a | 152 | dir_path: P, |
247cdbce | 153 | archive_name: &str, |
36898ffc | 154 | chunk_size: Option<usize>, |
2eeaacb9 | 155 | device_set: Option<HashSet<u64>>, |
219ef0e6 | 156 | verbose: bool, |
5b72c9b4 | 157 | skip_lost_and_found: bool, |
f98ac774 | 158 | crypt_config: Option<Arc<CryptConfig>>, |
247cdbce | 159 | ) -> Result<(), Error> { |
33d64b81 | 160 | |
5b72c9b4 | 161 | let pxar_stream = PxarBackupStream::open(dir_path.as_ref(), device_set, verbose, skip_lost_and_found)?; |
36898ffc | 162 | let chunk_stream = ChunkStream::new(pxar_stream, chunk_size); |
ff3d3100 | 163 | |
c4ff3dce | 164 | let (tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks |
5e7a09be | 165 | |
c4ff3dce DM |
166 | let stream = rx |
167 | .map_err(Error::from) | |
168 | .and_then(|x| x); // flatten | |
17d6979a | 169 | |
c4ff3dce DM |
170 | // spawn chunker inside a separate task so that it can run parallel |
171 | tokio::spawn( | |
172 | tx.send_all(chunk_stream.then(|r| Ok(r))) | |
1c0472e8 | 173 | .map_err(|_| {}).map(|_| ()) |
c4ff3dce | 174 | ); |
17d6979a | 175 | |
f98ac774 | 176 | client.upload_stream(archive_name, stream, "dynamic", None, crypt_config).wait()?; |
bcd879cf DM |
177 | |
178 | Ok(()) | |
179 | } | |
180 | ||
6af905c1 DM |
181 | fn backup_image<P: AsRef<Path>>( |
182 | client: &BackupClient, | |
183 | image_path: P, | |
184 | archive_name: &str, | |
185 | image_size: u64, | |
36898ffc | 186 | chunk_size: Option<usize>, |
1c0472e8 | 187 | _verbose: bool, |
f98ac774 | 188 | crypt_config: Option<Arc<CryptConfig>>, |
6af905c1 DM |
189 | ) -> Result<(), Error> { |
190 | ||
6af905c1 DM |
191 | let path = image_path.as_ref().to_owned(); |
192 | ||
193 | let file = tokio::fs::File::open(path).wait()?; | |
194 | ||
195 | let stream = tokio::codec::FramedRead::new(file, tokio::codec::BytesCodec::new()) | |
196 | .map_err(Error::from); | |
197 | ||
36898ffc | 198 | let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024)); |
6af905c1 | 199 | |
f98ac774 | 200 | client.upload_stream(archive_name, stream, "fixed", Some(image_size), crypt_config).wait()?; |
6af905c1 DM |
201 | |
202 | Ok(()) | |
203 | } | |
204 | ||
52c171e4 DM |
205 | fn strip_server_file_expenstion(name: &str) -> String { |
206 | ||
207 | if name.ends_with(".didx") { | |
208 | return name[..name.len()-5].to_owned(); | |
209 | } else if name.ends_with(".fidx") { | |
210 | return name[..name.len()-5].to_owned(); | |
211 | } else if name.ends_with(".blob") { | |
212 | return name[..name.len()-5].to_owned(); | |
213 | } else { | |
214 | return name.to_owned(); // should not happen | |
8e39232a | 215 | } |
8e39232a DM |
216 | } |
217 | ||
812c6f87 DM |
218 | fn list_backup_groups( |
219 | param: Value, | |
220 | _info: &ApiMethod, | |
dd5495d6 | 221 | _rpcenv: &mut dyn RpcEnvironment, |
812c6f87 DM |
222 | ) -> Result<Value, Error> { |
223 | ||
2665cef7 | 224 | let repo = extract_repository_from_value(¶m)?; |
812c6f87 | 225 | |
45cdce06 | 226 | let client = HttpClient::new(repo.host(), repo.user())?; |
812c6f87 | 227 | |
d0a03d40 | 228 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
812c6f87 | 229 | |
9e391bb7 | 230 | let mut result = client.get(&path, None).wait()?; |
812c6f87 | 231 | |
d0a03d40 DM |
232 | record_repository(&repo); |
233 | ||
812c6f87 | 234 | // fixme: implement and use output formatter instead .. |
80822b95 DM |
235 | let list = result["data"].as_array_mut().unwrap(); |
236 | ||
237 | list.sort_unstable_by(|a, b| { | |
238 | let a_id = a["backup-id"].as_str().unwrap(); | |
239 | let a_backup_type = a["backup-type"].as_str().unwrap(); | |
240 | let b_id = b["backup-id"].as_str().unwrap(); | |
241 | let b_backup_type = b["backup-type"].as_str().unwrap(); | |
242 | ||
243 | let type_order = a_backup_type.cmp(b_backup_type); | |
244 | if type_order == std::cmp::Ordering::Equal { | |
245 | a_id.cmp(b_id) | |
246 | } else { | |
247 | type_order | |
248 | } | |
249 | }); | |
812c6f87 | 250 | |
34a816cc DM |
251 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); |
252 | ||
253 | let mut result = vec![]; | |
254 | ||
812c6f87 DM |
255 | for item in list { |
256 | ||
ad20d198 DM |
257 | let id = item["backup-id"].as_str().unwrap(); |
258 | let btype = item["backup-type"].as_str().unwrap(); | |
259 | let epoch = item["last-backup"].as_i64().unwrap(); | |
fa5d6977 | 260 | let last_backup = Utc.timestamp(epoch, 0); |
ad20d198 | 261 | let backup_count = item["backup-count"].as_u64().unwrap(); |
812c6f87 | 262 | |
1e9a94e5 | 263 | let group = BackupGroup::new(btype, id); |
812c6f87 DM |
264 | |
265 | let path = group.group_path().to_str().unwrap().to_owned(); | |
ad20d198 | 266 | |
52c171e4 DM |
267 | let files = item["files"].as_array().unwrap().iter() |
268 | .map(|v| strip_server_file_expenstion(v.as_str().unwrap())).collect(); | |
ad20d198 | 269 | |
34a816cc | 270 | if output_format == "text" { |
fa5d6977 DM |
271 | println!( |
272 | "{:20} | {} | {:5} | {}", | |
273 | path, | |
274 | BackupDir::backup_time_to_string(last_backup), | |
275 | backup_count, | |
276 | tools::join(&files, ' '), | |
277 | ); | |
34a816cc DM |
278 | } else { |
279 | result.push(json!({ | |
280 | "backup-type": btype, | |
281 | "backup-id": id, | |
282 | "last-backup": epoch, | |
283 | "backup-count": backup_count, | |
284 | "files": files, | |
285 | })); | |
286 | } | |
812c6f87 DM |
287 | } |
288 | ||
9aa3f682 | 289 | if output_format != "text" { format_and_print_result(&result.into(), &output_format); } |
34a816cc | 290 | |
812c6f87 DM |
291 | Ok(Value::Null) |
292 | } | |
293 | ||
184f17af DM |
294 | fn list_snapshots( |
295 | param: Value, | |
296 | _info: &ApiMethod, | |
dd5495d6 | 297 | _rpcenv: &mut dyn RpcEnvironment, |
184f17af DM |
298 | ) -> Result<Value, Error> { |
299 | ||
2665cef7 | 300 | let repo = extract_repository_from_value(¶m)?; |
184f17af | 301 | |
34a816cc DM |
302 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); |
303 | ||
45cdce06 | 304 | let client = HttpClient::new(repo.host(), repo.user())?; |
184f17af | 305 | |
9e391bb7 | 306 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
184f17af | 307 | |
15c847f1 DM |
308 | let mut args = json!({}); |
309 | if let Some(path) = param["group"].as_str() { | |
310 | let group = BackupGroup::parse(path)?; | |
311 | args["backup-type"] = group.backup_type().into(); | |
312 | args["backup-id"] = group.backup_id().into(); | |
313 | } | |
314 | ||
315 | let result = client.get(&path, Some(args)).wait()?; | |
184f17af | 316 | |
d0a03d40 DM |
317 | record_repository(&repo); |
318 | ||
184f17af DM |
319 | let list = result["data"].as_array().unwrap(); |
320 | ||
34a816cc DM |
321 | let mut result = vec![]; |
322 | ||
184f17af DM |
323 | for item in list { |
324 | ||
325 | let id = item["backup-id"].as_str().unwrap(); | |
326 | let btype = item["backup-type"].as_str().unwrap(); | |
327 | let epoch = item["backup-time"].as_i64().unwrap(); | |
184f17af | 328 | |
391d3107 | 329 | let snapshot = BackupDir::new(btype, id, epoch); |
184f17af DM |
330 | |
331 | let path = snapshot.relative_path().to_str().unwrap().to_owned(); | |
332 | ||
52c171e4 DM |
333 | let files = item["files"].as_array().unwrap().iter() |
334 | .map(|v| strip_server_file_expenstion(v.as_str().unwrap())).collect(); | |
184f17af | 335 | |
34a816cc | 336 | if output_format == "text" { |
fa5d6977 | 337 | println!("{} | {}", path, tools::join(&files, ' ')); |
34a816cc DM |
338 | } else { |
339 | result.push(json!({ | |
340 | "backup-type": btype, | |
341 | "backup-id": id, | |
342 | "backup-time": epoch, | |
343 | "files": files, | |
344 | })); | |
345 | } | |
184f17af DM |
346 | } |
347 | ||
f6ede796 | 348 | if output_format != "text" { format_and_print_result(&result.into(), &output_format); } |
34a816cc | 349 | |
184f17af DM |
350 | Ok(Value::Null) |
351 | } | |
352 | ||
6f62c924 DM |
353 | fn forget_snapshots( |
354 | param: Value, | |
355 | _info: &ApiMethod, | |
dd5495d6 | 356 | _rpcenv: &mut dyn RpcEnvironment, |
6f62c924 DM |
357 | ) -> Result<Value, Error> { |
358 | ||
2665cef7 | 359 | let repo = extract_repository_from_value(¶m)?; |
6f62c924 DM |
360 | |
361 | let path = tools::required_string_param(¶m, "snapshot")?; | |
362 | let snapshot = BackupDir::parse(path)?; | |
363 | ||
45cdce06 | 364 | let mut client = HttpClient::new(repo.host(), repo.user())?; |
6f62c924 | 365 | |
9e391bb7 | 366 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
6f62c924 | 367 | |
9e391bb7 DM |
368 | let result = client.delete(&path, Some(json!({ |
369 | "backup-type": snapshot.group().backup_type(), | |
370 | "backup-id": snapshot.group().backup_id(), | |
371 | "backup-time": snapshot.backup_time().timestamp(), | |
372 | }))).wait()?; | |
6f62c924 | 373 | |
d0a03d40 DM |
374 | record_repository(&repo); |
375 | ||
6f62c924 DM |
376 | Ok(result) |
377 | } | |
378 | ||
52c171e4 DM |
379 | fn list_snapshot_files( |
380 | param: Value, | |
381 | _info: &ApiMethod, | |
382 | _rpcenv: &mut dyn RpcEnvironment, | |
383 | ) -> Result<Value, Error> { | |
384 | ||
385 | let repo = extract_repository_from_value(¶m)?; | |
386 | ||
387 | let path = tools::required_string_param(¶m, "snapshot")?; | |
388 | let snapshot = BackupDir::parse(path)?; | |
389 | ||
390 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); | |
391 | ||
392 | let client = HttpClient::new(repo.host(), repo.user())?; | |
393 | ||
394 | let path = format!("api2/json/admin/datastore/{}/files", repo.store()); | |
395 | ||
396 | let result = client.get(&path, Some(json!({ | |
397 | "backup-type": snapshot.group().backup_type(), | |
398 | "backup-id": snapshot.group().backup_id(), | |
399 | "backup-time": snapshot.backup_time().timestamp(), | |
400 | }))).wait()?; | |
401 | ||
402 | record_repository(&repo); | |
403 | ||
404 | let list: Vec<String> = result["data"].as_array().unwrap().iter() | |
405 | .map(|v| strip_server_file_expenstion(v.as_str().unwrap())).collect(); | |
406 | ||
407 | if output_format == "text" { | |
408 | for file in list { | |
409 | println!("{}", file); | |
410 | } | |
411 | } else { | |
412 | format_and_print_result(&list.into(), &output_format); | |
413 | } | |
414 | ||
415 | Ok(Value::Null) | |
416 | } | |
417 | ||
8cc0d6af DM |
418 | fn start_garbage_collection( |
419 | param: Value, | |
420 | _info: &ApiMethod, | |
dd5495d6 | 421 | _rpcenv: &mut dyn RpcEnvironment, |
8cc0d6af DM |
422 | ) -> Result<Value, Error> { |
423 | ||
2665cef7 | 424 | let repo = extract_repository_from_value(¶m)?; |
8cc0d6af | 425 | |
45cdce06 | 426 | let mut client = HttpClient::new(repo.host(), repo.user())?; |
8cc0d6af | 427 | |
d0a03d40 | 428 | let path = format!("api2/json/admin/datastore/{}/gc", repo.store()); |
8cc0d6af | 429 | |
5a2df000 | 430 | let result = client.post(&path, None).wait()?; |
8cc0d6af | 431 | |
d0a03d40 DM |
432 | record_repository(&repo); |
433 | ||
8cc0d6af DM |
434 | Ok(result) |
435 | } | |
33d64b81 | 436 | |
ae0be2dd DM |
437 | fn parse_backupspec(value: &str) -> Result<(&str, &str), Error> { |
438 | ||
439 | if let Some(caps) = BACKUPSPEC_REGEX.captures(value) { | |
440 | return Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str())); | |
441 | } | |
442 | bail!("unable to parse directory specification '{}'", value); | |
443 | } | |
444 | ||
6049b71f DM |
445 | fn create_backup( |
446 | param: Value, | |
447 | _info: &ApiMethod, | |
dd5495d6 | 448 | _rpcenv: &mut dyn RpcEnvironment, |
6049b71f | 449 | ) -> Result<Value, Error> { |
ff5d3707 | 450 | |
2665cef7 | 451 | let repo = extract_repository_from_value(¶m)?; |
ae0be2dd DM |
452 | |
453 | let backupspec_list = tools::required_array_param(¶m, "backupspec")?; | |
a914a774 | 454 | |
eed6db39 DM |
455 | let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false); |
456 | ||
5b72c9b4 DM |
457 | let skip_lost_and_found = param["skip-lost-and-found"].as_bool().unwrap_or(false); |
458 | ||
219ef0e6 DM |
459 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
460 | ||
ca5d0b61 DM |
461 | let backup_time_opt = param["backup-time"].as_i64(); |
462 | ||
36898ffc | 463 | let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize); |
2d9d143a | 464 | |
247cdbce DM |
465 | if let Some(size) = chunk_size_opt { |
466 | verify_chunk_size(size)?; | |
2d9d143a DM |
467 | } |
468 | ||
6d0983db DM |
469 | let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p)); |
470 | ||
bbf9e7e9 | 471 | let backup_id = param["backup-id"].as_str().unwrap_or(&tools::nodename()); |
fba30411 | 472 | |
bbf9e7e9 | 473 | let backup_type = param["backup-type"].as_str().unwrap_or("host"); |
ca5d0b61 | 474 | |
2eeaacb9 DM |
475 | let include_dev = param["include-dev"].as_array(); |
476 | ||
477 | let mut devices = if all_file_systems { None } else { Some(HashSet::new()) }; | |
478 | ||
479 | if let Some(include_dev) = include_dev { | |
480 | if all_file_systems { | |
481 | bail!("option 'all-file-systems' conflicts with option 'include-dev'"); | |
482 | } | |
483 | ||
484 | let mut set = HashSet::new(); | |
485 | for path in include_dev { | |
486 | let path = path.as_str().unwrap(); | |
487 | let stat = nix::sys::stat::stat(path) | |
488 | .map_err(|err| format_err!("fstat {:?} failed - {}", path, err))?; | |
489 | set.insert(stat.st_dev); | |
490 | } | |
491 | devices = Some(set); | |
492 | } | |
493 | ||
ae0be2dd | 494 | let mut upload_list = vec![]; |
a914a774 | 495 | |
79679c2d | 496 | enum BackupType { PXAR, IMAGE, CONFIG, LOGFILE }; |
6af905c1 | 497 | |
ae0be2dd DM |
498 | for backupspec in backupspec_list { |
499 | let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?; | |
bcd879cf | 500 | |
eb1804c5 DM |
501 | use std::os::unix::fs::FileTypeExt; |
502 | ||
503 | let metadata = match std::fs::metadata(filename) { | |
504 | Ok(m) => m, | |
ae0be2dd DM |
505 | Err(err) => bail!("unable to access '{}' - {}", filename, err), |
506 | }; | |
eb1804c5 | 507 | let file_type = metadata.file_type(); |
23bb8780 | 508 | |
ec8a9bb9 | 509 | let extension = Path::new(target).extension().map(|s| s.to_str().unwrap()).unwrap(); |
bcd879cf | 510 | |
ec8a9bb9 DM |
511 | match extension { |
512 | "pxar" => { | |
513 | if !file_type.is_dir() { | |
514 | bail!("got unexpected file type (expected directory)"); | |
515 | } | |
516 | upload_list.push((BackupType::PXAR, filename.to_owned(), target.to_owned(), 0)); | |
517 | } | |
518 | "img" => { | |
eb1804c5 | 519 | |
ec8a9bb9 DM |
520 | if !(file_type.is_file() || file_type.is_block_device()) { |
521 | bail!("got unexpected file type (expected file or block device)"); | |
522 | } | |
eb1804c5 | 523 | |
ec8a9bb9 | 524 | let size = tools::image_size(&PathBuf::from(filename))?; |
23bb8780 | 525 | |
ec8a9bb9 | 526 | if size == 0 { bail!("got zero-sized file '{}'", filename); } |
ae0be2dd | 527 | |
ec8a9bb9 DM |
528 | upload_list.push((BackupType::IMAGE, filename.to_owned(), target.to_owned(), size)); |
529 | } | |
530 | "conf" => { | |
531 | if !file_type.is_file() { | |
532 | bail!("got unexpected file type (expected regular file)"); | |
533 | } | |
534 | upload_list.push((BackupType::CONFIG, filename.to_owned(), target.to_owned(), metadata.len())); | |
535 | } | |
79679c2d DM |
536 | "log" => { |
537 | if !file_type.is_file() { | |
538 | bail!("got unexpected file type (expected regular file)"); | |
539 | } | |
540 | upload_list.push((BackupType::LOGFILE, filename.to_owned(), target.to_owned(), metadata.len())); | |
541 | } | |
ec8a9bb9 DM |
542 | _ => { |
543 | bail!("got unknown archive extension '{}'", extension); | |
544 | } | |
ae0be2dd DM |
545 | } |
546 | } | |
547 | ||
ca5d0b61 | 548 | let backup_time = Utc.timestamp(backup_time_opt.unwrap_or(Utc::now().timestamp()), 0); |
ae0be2dd | 549 | |
c4ff3dce | 550 | let client = HttpClient::new(repo.host(), repo.user())?; |
d0a03d40 DM |
551 | record_repository(&repo); |
552 | ||
ca5d0b61 DM |
553 | println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time)); |
554 | ||
cdebd467 | 555 | println!("Client name: {}", tools::nodename()); |
ca5d0b61 DM |
556 | |
557 | let start_time = Local::now(); | |
558 | ||
7a6cfbd9 | 559 | println!("Starting protocol: {}", start_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false)); |
51144821 | 560 | |
bb823140 DM |
561 | let (crypt_config, rsa_encrypted_key) = match keyfile { |
562 | None => (None, None), | |
6d0983db | 563 | Some(path) => { |
bb823140 DM |
564 | let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?; |
565 | ||
566 | let crypt_config = CryptConfig::new(key)?; | |
567 | ||
568 | let path = master_pubkey_path()?; | |
569 | if path.exists() { | |
570 | let pem_data = proxmox_backup::tools::file_get_contents(&path)?; | |
571 | let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?; | |
572 | let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?; | |
573 | (Some(Arc::new(crypt_config)), Some(enc_key)) | |
574 | } else { | |
575 | (Some(Arc::new(crypt_config)), None) | |
576 | } | |
6d0983db DM |
577 | } |
578 | }; | |
f98ac774 | 579 | |
ca5d0b61 | 580 | let client = client.start_backup(repo.store(), backup_type, &backup_id, backup_time, verbose).wait()?; |
c4ff3dce | 581 | |
6af905c1 DM |
582 | for (backup_type, filename, target, size) in upload_list { |
583 | match backup_type { | |
ec8a9bb9 DM |
584 | BackupType::CONFIG => { |
585 | println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target); | |
9f46c7de | 586 | client.upload_blob_from_file(&filename, &target, crypt_config.clone(), true).wait()?; |
ec8a9bb9 | 587 | } |
ca5d0b61 | 588 | BackupType::LOGFILE => { // fixme: remove - not needed anymore ? |
79679c2d DM |
589 | println!("Upload log file '{}' to '{:?}' as {}", filename, repo, target); |
590 | client.upload_blob_from_file(&filename, &target, crypt_config.clone(), true).wait()?; | |
591 | } | |
6af905c1 DM |
592 | BackupType::PXAR => { |
593 | println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target); | |
f98ac774 DM |
594 | backup_directory( |
595 | &client, | |
596 | &filename, | |
597 | &target, | |
598 | chunk_size_opt, | |
2eeaacb9 | 599 | devices.clone(), |
f98ac774 | 600 | verbose, |
5b72c9b4 | 601 | skip_lost_and_found, |
f98ac774 DM |
602 | crypt_config.clone(), |
603 | )?; | |
6af905c1 DM |
604 | } |
605 | BackupType::IMAGE => { | |
606 | println!("Upload image '{}' to '{:?}' as {}", filename, repo, target); | |
f98ac774 DM |
607 | backup_image( |
608 | &client, | |
609 | &filename, | |
610 | &target, | |
611 | size, | |
612 | chunk_size_opt, | |
613 | verbose, | |
614 | crypt_config.clone(), | |
615 | )?; | |
6af905c1 DM |
616 | } |
617 | } | |
4818c8b6 DM |
618 | } |
619 | ||
bb823140 DM |
620 | if let Some(rsa_encrypted_key) = rsa_encrypted_key { |
621 | let target = "rsa-encrypted.key"; | |
622 | println!("Upload RSA encoded key to '{:?}' as {}", repo, target); | |
623 | client.upload_blob_from_data(rsa_encrypted_key, target, None, false).wait()?; | |
624 | ||
625 | // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t | |
626 | /* | |
627 | let mut buffer2 = vec![0u8; rsa.size() as usize]; | |
628 | let pem_data = proxmox_backup::tools::file_get_contents("master-private.pem")?; | |
629 | let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?; | |
630 | let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?; | |
631 | println!("TEST {} {:?}", len, buffer2); | |
632 | */ | |
9f46c7de DM |
633 | } |
634 | ||
c4ff3dce DM |
635 | client.finish().wait()?; |
636 | ||
7a6cfbd9 | 637 | let end_time = Local::now(); |
ca5d0b61 | 638 | let elapsed = end_time.signed_duration_since(start_time); |
3ec3ec3f DM |
639 | println!("Duration: {}", elapsed); |
640 | ||
7a6cfbd9 | 641 | println!("End Time: {}", end_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false)); |
3d5c11e5 | 642 | |
ff5d3707 | 643 | Ok(Value::Null) |
f98ea63d DM |
644 | } |
645 | ||
d0a03d40 | 646 | fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
f98ea63d DM |
647 | |
648 | let mut result = vec![]; | |
649 | ||
650 | let data: Vec<&str> = arg.splitn(2, ':').collect(); | |
651 | ||
bff11030 | 652 | if data.len() != 2 { |
8968258b DM |
653 | result.push(String::from("root.pxar:/")); |
654 | result.push(String::from("etc.pxar:/etc")); | |
bff11030 DM |
655 | return result; |
656 | } | |
f98ea63d | 657 | |
496a6784 | 658 | let files = tools::complete_file_name(data[1], param); |
f98ea63d DM |
659 | |
660 | for file in files { | |
661 | result.push(format!("{}:{}", data[0], file)); | |
662 | } | |
663 | ||
664 | result | |
ff5d3707 | 665 | } |
666 | ||
9f912493 DM |
667 | fn restore( |
668 | param: Value, | |
669 | _info: &ApiMethod, | |
dd5495d6 | 670 | _rpcenv: &mut dyn RpcEnvironment, |
9f912493 DM |
671 | ) -> Result<Value, Error> { |
672 | ||
2665cef7 | 673 | let repo = extract_repository_from_value(¶m)?; |
9f912493 | 674 | |
86eda3eb DM |
675 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
676 | ||
46d5aa0a DM |
677 | let allow_existing_dirs = param["allow-existing-dirs"].as_bool().unwrap_or(false); |
678 | ||
d5c34d98 DM |
679 | let archive_name = tools::required_string_param(¶m, "archive-name")?; |
680 | ||
86eda3eb | 681 | let client = HttpClient::new(repo.host(), repo.user())?; |
d0a03d40 | 682 | |
d0a03d40 | 683 | record_repository(&repo); |
d5c34d98 | 684 | |
9f912493 | 685 | let path = tools::required_string_param(¶m, "snapshot")?; |
9f912493 | 686 | |
86eda3eb | 687 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { |
d5c34d98 | 688 | let group = BackupGroup::parse(path)?; |
9f912493 | 689 | |
9e391bb7 DM |
690 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
691 | let result = client.get(&path, Some(json!({ | |
d5c34d98 DM |
692 | "backup-type": group.backup_type(), |
693 | "backup-id": group.backup_id(), | |
9e391bb7 | 694 | }))).wait()?; |
9f912493 | 695 | |
d5c34d98 DM |
696 | let list = result["data"].as_array().unwrap(); |
697 | if list.len() == 0 { | |
698 | bail!("backup group '{}' does not contain any snapshots:", path); | |
699 | } | |
9f912493 | 700 | |
86eda3eb | 701 | let epoch = list[0]["backup-time"].as_i64().unwrap(); |
fa5d6977 | 702 | let backup_time = Utc.timestamp(epoch, 0); |
86eda3eb | 703 | (group.backup_type().to_owned(), group.backup_id().to_owned(), backup_time) |
d5c34d98 DM |
704 | } else { |
705 | let snapshot = BackupDir::parse(path)?; | |
86eda3eb DM |
706 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) |
707 | }; | |
9f912493 | 708 | |
d5c34d98 | 709 | let target = tools::required_string_param(¶m, "target")?; |
bf125261 | 710 | let target = if target == "-" { None } else { Some(target) }; |
2ae7d196 | 711 | |
86eda3eb | 712 | let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p)); |
2ae7d196 | 713 | |
86eda3eb DM |
714 | let crypt_config = match keyfile { |
715 | None => None, | |
716 | Some(path) => { | |
717 | let (key, _) = load_and_decrtypt_key(&path, get_encryption_key_password)?; | |
718 | Some(Arc::new(CryptConfig::new(key)?)) | |
719 | } | |
720 | }; | |
d5c34d98 | 721 | |
afb4cd28 DM |
722 | let server_archive_name = if archive_name.ends_with(".pxar") { |
723 | format!("{}.didx", archive_name) | |
724 | } else if archive_name.ends_with(".img") { | |
725 | format!("{}.fidx", archive_name) | |
726 | } else { | |
f8100e96 | 727 | format!("{}.blob", archive_name) |
afb4cd28 | 728 | }; |
9f912493 | 729 | |
86eda3eb DM |
730 | let client = client.start_backup_reader(repo.store(), &backup_type, &backup_id, backup_time, true).wait()?; |
731 | ||
732 | use std::os::unix::fs::OpenOptionsExt; | |
733 | ||
734 | let tmpfile = std::fs::OpenOptions::new() | |
735 | .write(true) | |
736 | .read(true) | |
737 | .custom_flags(libc::O_TMPFILE) | |
738 | .open("/tmp")?; | |
739 | ||
f8100e96 DM |
740 | if server_archive_name.ends_with(".blob") { |
741 | ||
742 | let writer = Vec::with_capacity(1024*1024); | |
743 | let blob_data = client.download(&server_archive_name, writer).wait()?; | |
744 | let blob = DataBlob::from_raw(blob_data)?; | |
745 | blob.verify_crc()?; | |
746 | ||
747 | let raw_data = match crypt_config { | |
748 | Some(ref crypt_config) => blob.decode(Some(crypt_config))?, | |
749 | None => blob.decode(None)?, | |
750 | }; | |
751 | ||
bf125261 DM |
752 | if let Some(target) = target { |
753 | crate::tools::file_set_contents(target, &raw_data, None)?; | |
754 | } else { | |
755 | let stdout = std::io::stdout(); | |
756 | let mut writer = stdout.lock(); | |
757 | writer.write_all(&raw_data) | |
758 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
759 | } | |
f8100e96 DM |
760 | |
761 | } else if server_archive_name.ends_with(".didx") { | |
afb4cd28 | 762 | let tmpfile = client.download(&server_archive_name, tmpfile).wait()?; |
86eda3eb | 763 | |
afb4cd28 DM |
764 | let index = DynamicIndexReader::new(tmpfile) |
765 | .map_err(|err| format_err!("unable to read dynamic index '{}' - {}", archive_name, err))?; | |
86eda3eb | 766 | |
f4bf7dfc DM |
767 | let most_used = index.find_most_used_chunks(8); |
768 | ||
769 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
770 | ||
afb4cd28 | 771 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); |
86eda3eb | 772 | |
bf125261 | 773 | if let Some(target) = target { |
86eda3eb | 774 | |
bf125261 DM |
775 | let feature_flags = pxar::CA_FORMAT_DEFAULT; |
776 | let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags, |path| { | |
777 | if verbose { | |
778 | println!("{:?}", path); | |
779 | } | |
780 | Ok(()) | |
781 | }); | |
6a879109 CE |
782 | decoder.set_allow_existing_dirs(allow_existing_dirs); |
783 | ||
bf125261 | 784 | |
fa7e957c | 785 | decoder.restore(Path::new(target), &Vec::new())?; |
bf125261 DM |
786 | } else { |
787 | let stdout = std::io::stdout(); | |
788 | let mut writer = stdout.lock(); | |
afb4cd28 | 789 | |
bf125261 DM |
790 | std::io::copy(&mut reader, &mut writer) |
791 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
792 | } | |
afb4cd28 DM |
793 | } else if server_archive_name.ends_with(".fidx") { |
794 | let tmpfile = client.download(&server_archive_name, tmpfile).wait()?; | |
795 | ||
796 | let index = FixedIndexReader::new(tmpfile) | |
797 | .map_err(|err| format_err!("unable to read fixed index '{}' - {}", archive_name, err))?; | |
7dcbe051 | 798 | |
f4bf7dfc DM |
799 | let most_used = index.find_most_used_chunks(8); |
800 | ||
801 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
802 | ||
afb4cd28 DM |
803 | let mut reader = BufferedFixedReader::new(index, chunk_reader); |
804 | ||
bf125261 DM |
805 | if let Some(target) = target { |
806 | let mut writer = std::fs::OpenOptions::new() | |
807 | .write(true) | |
808 | .create(true) | |
809 | .create_new(true) | |
810 | .open(target) | |
811 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?; | |
812 | ||
813 | std::io::copy(&mut reader, &mut writer) | |
814 | .map_err(|err| format_err!("unable to store data - {}", err))?; | |
815 | } else { | |
816 | let stdout = std::io::stdout(); | |
817 | let mut writer = stdout.lock(); | |
afb4cd28 | 818 | |
bf125261 DM |
819 | std::io::copy(&mut reader, &mut writer) |
820 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
821 | } | |
45db6f89 | 822 | } else { |
f8100e96 | 823 | bail!("unknown archive file extension (expected .pxar of .img)"); |
3031e44c | 824 | } |
fef44d4f DM |
825 | |
826 | Ok(Value::Null) | |
45db6f89 DM |
827 | } |
828 | ||
ec34f7eb DM |
829 | fn upload_log( |
830 | param: Value, | |
831 | _info: &ApiMethod, | |
832 | _rpcenv: &mut dyn RpcEnvironment, | |
833 | ) -> Result<Value, Error> { | |
834 | ||
835 | let logfile = tools::required_string_param(¶m, "logfile")?; | |
836 | let repo = extract_repository_from_value(¶m)?; | |
837 | ||
838 | let snapshot = tools::required_string_param(¶m, "snapshot")?; | |
839 | let snapshot = BackupDir::parse(snapshot)?; | |
840 | ||
841 | let mut client = HttpClient::new(repo.host(), repo.user())?; | |
842 | ||
843 | let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p)); | |
844 | ||
845 | let crypt_config = match keyfile { | |
846 | None => None, | |
847 | Some(path) => { | |
848 | let (key, _created) = load_and_decrtypt_key(&path, get_encryption_key_password)?; | |
849 | let crypt_config = CryptConfig::new(key)?; | |
850 | Some(crypt_config) | |
851 | } | |
852 | }; | |
853 | ||
854 | let data = crate::tools::file_get_contents(logfile)?; | |
855 | ||
856 | let blob = if let Some(ref crypt_config) = crypt_config { | |
857 | DataBlob::encode(&data, Some(crypt_config), true)? | |
858 | } else { | |
859 | DataBlob::encode(&data, None, true)? | |
860 | }; | |
861 | ||
862 | let raw_data = blob.into_inner(); | |
863 | ||
864 | let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store()); | |
865 | ||
866 | let args = json!({ | |
867 | "backup-type": snapshot.group().backup_type(), | |
868 | "backup-id": snapshot.group().backup_id(), | |
869 | "backup-time": snapshot.backup_time().timestamp(), | |
870 | }); | |
871 | ||
872 | let body = hyper::Body::from(raw_data); | |
873 | ||
874 | let result = client.upload("application/octet-stream", body, &path, Some(args)).wait()?; | |
875 | ||
876 | Ok(result) | |
877 | } | |
878 | ||
83b7db02 | 879 | fn prune( |
ea7a7ef2 | 880 | mut param: Value, |
83b7db02 | 881 | _info: &ApiMethod, |
dd5495d6 | 882 | _rpcenv: &mut dyn RpcEnvironment, |
83b7db02 DM |
883 | ) -> Result<Value, Error> { |
884 | ||
2665cef7 | 885 | let repo = extract_repository_from_value(¶m)?; |
83b7db02 | 886 | |
45cdce06 | 887 | let mut client = HttpClient::new(repo.host(), repo.user())?; |
83b7db02 | 888 | |
d0a03d40 | 889 | let path = format!("api2/json/admin/datastore/{}/prune", repo.store()); |
83b7db02 | 890 | |
9fdc3ef4 DM |
891 | let group = tools::required_string_param(¶m, "group")?; |
892 | let group = BackupGroup::parse(group)?; | |
893 | ||
ea7a7ef2 DM |
894 | param.as_object_mut().unwrap().remove("repository"); |
895 | param.as_object_mut().unwrap().remove("group"); | |
896 | ||
897 | param["backup-type"] = group.backup_type().into(); | |
898 | param["backup-id"] = group.backup_id().into(); | |
83b7db02 | 899 | |
43a406fd | 900 | let _result = client.post(&path, Some(param)).wait()?; |
83b7db02 | 901 | |
d0a03d40 DM |
902 | record_repository(&repo); |
903 | ||
43a406fd | 904 | Ok(Value::Null) |
83b7db02 DM |
905 | } |
906 | ||
34a816cc DM |
907 | fn status( |
908 | param: Value, | |
909 | _info: &ApiMethod, | |
910 | _rpcenv: &mut dyn RpcEnvironment, | |
911 | ) -> Result<Value, Error> { | |
912 | ||
913 | let repo = extract_repository_from_value(¶m)?; | |
914 | ||
915 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); | |
916 | ||
917 | let client = HttpClient::new(repo.host(), repo.user())?; | |
918 | ||
919 | let path = format!("api2/json/admin/datastore/{}/status", repo.store()); | |
920 | ||
921 | let result = client.get(&path, None).wait()?; | |
922 | let data = &result["data"]; | |
923 | ||
924 | record_repository(&repo); | |
925 | ||
926 | if output_format == "text" { | |
927 | let total = data["total"].as_u64().unwrap(); | |
928 | let used = data["used"].as_u64().unwrap(); | |
929 | let avail = data["avail"].as_u64().unwrap(); | |
930 | let roundup = total/200; | |
931 | ||
932 | println!( | |
933 | "total: {} used: {} ({} %) available: {}", | |
934 | total, | |
935 | used, | |
936 | ((used+roundup)*100)/total, | |
937 | avail, | |
938 | ); | |
939 | } else { | |
f6ede796 | 940 | format_and_print_result(data, &output_format); |
34a816cc DM |
941 | } |
942 | ||
943 | Ok(Value::Null) | |
944 | } | |
945 | ||
5a2df000 | 946 | // like get, but simply ignore errors and return Null instead |
b2388518 | 947 | fn try_get(repo: &BackupRepository, url: &str) -> Value { |
024f11bb | 948 | |
45cdce06 DM |
949 | let client = match HttpClient::new(repo.host(), repo.user()) { |
950 | Ok(v) => v, | |
951 | _ => return Value::Null, | |
952 | }; | |
b2388518 | 953 | |
9e391bb7 | 954 | let mut resp = match client.get(url, None).wait() { |
b2388518 DM |
955 | Ok(v) => v, |
956 | _ => return Value::Null, | |
957 | }; | |
958 | ||
959 | if let Some(map) = resp.as_object_mut() { | |
960 | if let Some(data) = map.remove("data") { | |
961 | return data; | |
962 | } | |
963 | } | |
964 | Value::Null | |
965 | } | |
966 | ||
b2388518 | 967 | fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
024f11bb | 968 | |
b2388518 DM |
969 | let mut result = vec![]; |
970 | ||
2665cef7 | 971 | let repo = match extract_repository_from_map(param) { |
b2388518 | 972 | Some(v) => v, |
024f11bb DM |
973 | _ => return result, |
974 | }; | |
975 | ||
b2388518 DM |
976 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
977 | ||
978 | let data = try_get(&repo, &path); | |
979 | ||
980 | if let Some(list) = data.as_array() { | |
024f11bb | 981 | for item in list { |
98f0b972 DM |
982 | if let (Some(backup_id), Some(backup_type)) = |
983 | (item["backup-id"].as_str(), item["backup-type"].as_str()) | |
984 | { | |
985 | result.push(format!("{}/{}", backup_type, backup_id)); | |
024f11bb DM |
986 | } |
987 | } | |
988 | } | |
989 | ||
990 | result | |
991 | } | |
992 | ||
b2388518 DM |
993 | fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
994 | ||
995 | let mut result = vec![]; | |
996 | ||
2665cef7 | 997 | let repo = match extract_repository_from_map(param) { |
b2388518 DM |
998 | Some(v) => v, |
999 | _ => return result, | |
1000 | }; | |
1001 | ||
1002 | if arg.matches('/').count() < 2 { | |
1003 | let groups = complete_backup_group(arg, param); | |
1004 | for group in groups { | |
1005 | result.push(group.to_string()); | |
1006 | result.push(format!("{}/", group)); | |
1007 | } | |
1008 | return result; | |
1009 | } | |
1010 | ||
1011 | let mut parts = arg.split('/'); | |
1012 | let query = tools::json_object_to_query(json!({ | |
1013 | "backup-type": parts.next().unwrap(), | |
1014 | "backup-id": parts.next().unwrap(), | |
1015 | })).unwrap(); | |
1016 | ||
1017 | let path = format!("api2/json/admin/datastore/{}/snapshots?{}", repo.store(), query); | |
1018 | ||
1019 | let data = try_get(&repo, &path); | |
1020 | ||
1021 | if let Some(list) = data.as_array() { | |
1022 | for item in list { | |
1023 | if let (Some(backup_id), Some(backup_type), Some(backup_time)) = | |
1024 | (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64()) | |
1025 | { | |
1026 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time); | |
1027 | result.push(snapshot.relative_path().to_str().unwrap().to_owned()); | |
1028 | } | |
1029 | } | |
1030 | } | |
1031 | ||
1032 | result | |
1033 | } | |
1034 | ||
45db6f89 | 1035 | fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
08dc340a DM |
1036 | |
1037 | let mut result = vec![]; | |
1038 | ||
2665cef7 | 1039 | let repo = match extract_repository_from_map(param) { |
08dc340a DM |
1040 | Some(v) => v, |
1041 | _ => return result, | |
1042 | }; | |
1043 | ||
1044 | let snapshot = match param.get("snapshot") { | |
1045 | Some(path) => { | |
1046 | match BackupDir::parse(path) { | |
1047 | Ok(v) => v, | |
1048 | _ => return result, | |
1049 | } | |
1050 | } | |
1051 | _ => return result, | |
1052 | }; | |
1053 | ||
1054 | let query = tools::json_object_to_query(json!({ | |
1055 | "backup-type": snapshot.group().backup_type(), | |
1056 | "backup-id": snapshot.group().backup_id(), | |
1057 | "backup-time": snapshot.backup_time().timestamp(), | |
1058 | })).unwrap(); | |
1059 | ||
1060 | let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query); | |
1061 | ||
1062 | let data = try_get(&repo, &path); | |
1063 | ||
1064 | if let Some(list) = data.as_array() { | |
1065 | for item in list { | |
1066 | if let Some(filename) = item.as_str() { | |
1067 | result.push(filename.to_owned()); | |
1068 | } | |
1069 | } | |
1070 | } | |
1071 | ||
45db6f89 DM |
1072 | result |
1073 | } | |
1074 | ||
1075 | fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
1076 | ||
52c171e4 DM |
1077 | complete_server_file_name(arg, param) |
1078 | .iter().map(|v| strip_server_file_expenstion(&v)).collect() | |
08dc340a DM |
1079 | } |
1080 | ||
49811347 DM |
1081 | fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
1082 | ||
1083 | let mut result = vec![]; | |
1084 | ||
1085 | let mut size = 64; | |
1086 | loop { | |
1087 | result.push(size.to_string()); | |
1088 | size = size * 2; | |
1089 | if size > 4096 { break; } | |
1090 | } | |
1091 | ||
1092 | result | |
1093 | } | |
1094 | ||
826f309b | 1095 | fn get_encryption_key_password() -> Result<Vec<u8>, Error> { |
ff5d3707 | 1096 | |
f2401311 DM |
1097 | // fixme: implement other input methods |
1098 | ||
1099 | use std::env::VarError::*; | |
1100 | match std::env::var("PBS_ENCRYPTION_PASSWORD") { | |
826f309b | 1101 | Ok(p) => return Ok(p.as_bytes().to_vec()), |
f2401311 DM |
1102 | Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"), |
1103 | Err(NotPresent) => { | |
1104 | // Try another method | |
1105 | } | |
1106 | } | |
1107 | ||
1108 | // If we're on a TTY, query the user for a password | |
1109 | if crate::tools::tty::stdin_isatty() { | |
826f309b | 1110 | return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?); |
f2401311 DM |
1111 | } |
1112 | ||
1113 | bail!("no password input mechanism available"); | |
1114 | } | |
1115 | ||
ac716234 DM |
1116 | fn key_create( |
1117 | param: Value, | |
1118 | _info: &ApiMethod, | |
1119 | _rpcenv: &mut dyn RpcEnvironment, | |
1120 | ) -> Result<Value, Error> { | |
1121 | ||
9b06db45 DM |
1122 | let path = tools::required_string_param(¶m, "path")?; |
1123 | let path = PathBuf::from(path); | |
ac716234 | 1124 | |
181f097a | 1125 | let kdf = param["kdf"].as_str().unwrap_or("scrypt"); |
ac716234 DM |
1126 | |
1127 | let key = proxmox::sys::linux::random_data(32)?; | |
1128 | ||
181f097a DM |
1129 | if kdf == "scrypt" { |
1130 | // always read passphrase from tty | |
1131 | if !crate::tools::tty::stdin_isatty() { | |
1132 | bail!("unable to read passphrase - no tty"); | |
1133 | } | |
ac716234 | 1134 | |
181f097a DM |
1135 | let password = crate::tools::tty::read_password("Encryption Key Password: ")?; |
1136 | ||
ab44acff | 1137 | let key_config = encrypt_key_with_passphrase(&key, &password)?; |
37c5a175 | 1138 | |
ab44acff | 1139 | store_key_config(&path, false, key_config)?; |
181f097a DM |
1140 | |
1141 | Ok(Value::Null) | |
1142 | } else if kdf == "none" { | |
1143 | let created = Local.timestamp(Local::now().timestamp(), 0); | |
1144 | ||
1145 | store_key_config(&path, false, KeyConfig { | |
1146 | kdf: None, | |
1147 | created, | |
ab44acff | 1148 | modified: created, |
181f097a DM |
1149 | data: key, |
1150 | })?; | |
1151 | ||
1152 | Ok(Value::Null) | |
1153 | } else { | |
1154 | unreachable!(); | |
1155 | } | |
ac716234 DM |
1156 | } |
1157 | ||
9f46c7de DM |
1158 | fn master_pubkey_path() -> Result<PathBuf, Error> { |
1159 | let base = BaseDirectories::with_prefix("proxmox-backup")?; | |
1160 | ||
1161 | // usually $HOME/.config/proxmox-backup/master-public.pem | |
1162 | let path = base.place_config_file("master-public.pem")?; | |
1163 | ||
1164 | Ok(path) | |
1165 | } | |
1166 | ||
3ea8bfc9 DM |
1167 | fn key_import_master_pubkey( |
1168 | param: Value, | |
1169 | _info: &ApiMethod, | |
1170 | _rpcenv: &mut dyn RpcEnvironment, | |
1171 | ) -> Result<Value, Error> { | |
1172 | ||
1173 | let path = tools::required_string_param(¶m, "path")?; | |
1174 | let path = PathBuf::from(path); | |
1175 | ||
1176 | let pem_data = proxmox_backup::tools::file_get_contents(&path)?; | |
1177 | ||
1178 | if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) { | |
1179 | bail!("Unable to decode PEM data - {}", err); | |
1180 | } | |
1181 | ||
9f46c7de | 1182 | let target_path = master_pubkey_path()?; |
3ea8bfc9 DM |
1183 | |
1184 | proxmox_backup::tools::file_set_contents(&target_path, &pem_data, None)?; | |
1185 | ||
1186 | println!("Imported public master key to {:?}", target_path); | |
1187 | ||
1188 | Ok(Value::Null) | |
1189 | } | |
1190 | ||
37c5a175 DM |
1191 | fn key_create_master_key( |
1192 | _param: Value, | |
1193 | _info: &ApiMethod, | |
1194 | _rpcenv: &mut dyn RpcEnvironment, | |
1195 | ) -> Result<Value, Error> { | |
1196 | ||
1197 | // we need a TTY to query the new password | |
1198 | if !crate::tools::tty::stdin_isatty() { | |
1199 | bail!("unable to create master key - no tty"); | |
1200 | } | |
1201 | ||
1202 | let rsa = openssl::rsa::Rsa::generate(4096)?; | |
1203 | let pkey = openssl::pkey::PKey::from_rsa(rsa)?; | |
1204 | ||
1205 | let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?; | |
1206 | let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?; | |
1207 | ||
1208 | if new_pw != verify_pw { | |
1209 | bail!("Password verification fail!"); | |
1210 | } | |
1211 | ||
1212 | if new_pw.len() < 5 { | |
1213 | bail!("Password is too short!"); | |
1214 | } | |
1215 | ||
1216 | let pub_key: Vec<u8> = pkey.public_key_to_pem()?; | |
1217 | let filename_pub = "master-public.pem"; | |
1218 | println!("Writing public master key to {}", filename_pub); | |
1219 | proxmox_backup::tools::file_set_contents(filename_pub, pub_key.as_slice(), None)?; | |
1220 | ||
1221 | let cipher = openssl::symm::Cipher::aes_256_cbc(); | |
1222 | let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?; | |
1223 | ||
1224 | let filename_priv = "master-private.pem"; | |
1225 | println!("Writing private master key to {}", filename_priv); | |
1226 | proxmox_backup::tools::file_set_contents(filename_priv, priv_key.as_slice(), None)?; | |
1227 | ||
1228 | Ok(Value::Null) | |
1229 | } | |
ac716234 DM |
1230 | |
1231 | fn key_change_passphrase( | |
1232 | param: Value, | |
1233 | _info: &ApiMethod, | |
1234 | _rpcenv: &mut dyn RpcEnvironment, | |
1235 | ) -> Result<Value, Error> { | |
1236 | ||
9b06db45 DM |
1237 | let path = tools::required_string_param(¶m, "path")?; |
1238 | let path = PathBuf::from(path); | |
ac716234 | 1239 | |
181f097a DM |
1240 | let kdf = param["kdf"].as_str().unwrap_or("scrypt"); |
1241 | ||
ac716234 DM |
1242 | // we need a TTY to query the new password |
1243 | if !crate::tools::tty::stdin_isatty() { | |
1244 | bail!("unable to change passphrase - no tty"); | |
1245 | } | |
1246 | ||
ab44acff | 1247 | let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?; |
ac716234 | 1248 | |
181f097a | 1249 | if kdf == "scrypt" { |
ac716234 | 1250 | |
181f097a DM |
1251 | let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?; |
1252 | let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?; | |
ac716234 | 1253 | |
181f097a DM |
1254 | if new_pw != verify_pw { |
1255 | bail!("Password verification fail!"); | |
1256 | } | |
1257 | ||
1258 | if new_pw.len() < 5 { | |
1259 | bail!("Password is too short!"); | |
1260 | } | |
ac716234 | 1261 | |
ab44acff DM |
1262 | let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?; |
1263 | new_key_config.created = created; // keep original value | |
1264 | ||
1265 | store_key_config(&path, true, new_key_config)?; | |
ac716234 | 1266 | |
181f097a DM |
1267 | Ok(Value::Null) |
1268 | } else if kdf == "none" { | |
ab44acff | 1269 | let modified = Local.timestamp(Local::now().timestamp(), 0); |
181f097a DM |
1270 | |
1271 | store_key_config(&path, true, KeyConfig { | |
1272 | kdf: None, | |
ab44acff DM |
1273 | created, // keep original value |
1274 | modified, | |
6d0983db | 1275 | data: key.to_vec(), |
181f097a DM |
1276 | })?; |
1277 | ||
1278 | Ok(Value::Null) | |
1279 | } else { | |
1280 | unreachable!(); | |
1281 | } | |
f2401311 DM |
1282 | } |
1283 | ||
1284 | fn key_mgmt_cli() -> CliCommandMap { | |
1285 | ||
181f097a DM |
1286 | let kdf_schema: Arc<Schema> = Arc::new( |
1287 | StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.") | |
1288 | .format(Arc::new(ApiStringFormat::Enum(&["scrypt", "none"]))) | |
1289 | .default("scrypt") | |
1290 | .into() | |
1291 | ); | |
1292 | ||
f2401311 DM |
1293 | let key_create_cmd_def = CliCommand::new( |
1294 | ApiMethod::new( | |
1295 | key_create, | |
1296 | ObjectSchema::new("Create a new encryption key.") | |
9b06db45 | 1297 | .required("path", StringSchema::new("File system path.")) |
181f097a | 1298 | .optional("kdf", kdf_schema.clone()) |
f2401311 | 1299 | )) |
9b06db45 DM |
1300 | .arg_param(vec!["path"]) |
1301 | .completion_cb("path", tools::complete_file_name); | |
f2401311 | 1302 | |
ac716234 DM |
1303 | let key_change_passphrase_cmd_def = CliCommand::new( |
1304 | ApiMethod::new( | |
1305 | key_change_passphrase, | |
1306 | ObjectSchema::new("Change the passphrase required to decrypt the key.") | |
9b06db45 | 1307 | .required("path", StringSchema::new("File system path.")) |
181f097a | 1308 | .optional("kdf", kdf_schema.clone()) |
9b06db45 DM |
1309 | )) |
1310 | .arg_param(vec!["path"]) | |
1311 | .completion_cb("path", tools::complete_file_name); | |
ac716234 | 1312 | |
37c5a175 DM |
1313 | let key_create_master_key_cmd_def = CliCommand::new( |
1314 | ApiMethod::new( | |
1315 | key_create_master_key, | |
1316 | ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.") | |
1317 | )); | |
1318 | ||
3ea8bfc9 DM |
1319 | let key_import_master_pubkey_cmd_def = CliCommand::new( |
1320 | ApiMethod::new( | |
1321 | key_import_master_pubkey, | |
1322 | ObjectSchema::new("Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.") | |
1323 | .required("path", StringSchema::new("File system path.")) | |
1324 | )) | |
1325 | .arg_param(vec!["path"]) | |
1326 | .completion_cb("path", tools::complete_file_name); | |
1327 | ||
f2401311 | 1328 | let cmd_def = CliCommandMap::new() |
ac716234 | 1329 | .insert("create".to_owned(), key_create_cmd_def.into()) |
37c5a175 | 1330 | .insert("create-master-key".to_owned(), key_create_master_key_cmd_def.into()) |
3ea8bfc9 | 1331 | .insert("import-master-pubkey".to_owned(), key_import_master_pubkey_cmd_def.into()) |
ac716234 | 1332 | .insert("change-passphrase".to_owned(), key_change_passphrase_cmd_def.into()); |
f2401311 DM |
1333 | |
1334 | cmd_def | |
1335 | } | |
1336 | ||
f2401311 | 1337 | fn main() { |
33d64b81 | 1338 | |
25f1650b DM |
1339 | let backup_source_schema: Arc<Schema> = Arc::new( |
1340 | StringSchema::new("Backup source specification ([<label>:<path>]).") | |
1341 | .format(Arc::new(ApiStringFormat::Pattern(&BACKUPSPEC_REGEX))) | |
1342 | .into() | |
1343 | ); | |
1344 | ||
597a9203 | 1345 | let backup_cmd_def = CliCommand::new( |
ff5d3707 | 1346 | ApiMethod::new( |
bcd879cf | 1347 | create_backup, |
597a9203 | 1348 | ObjectSchema::new("Create (host) backup.") |
ae0be2dd DM |
1349 | .required( |
1350 | "backupspec", | |
1351 | ArraySchema::new( | |
74cdb521 | 1352 | "List of backup source specifications ([<label.ext>:<path>] ...)", |
25f1650b | 1353 | backup_source_schema, |
ae0be2dd DM |
1354 | ).min_length(1) |
1355 | ) | |
2665cef7 | 1356 | .optional("repository", REPO_URL_SCHEMA.clone()) |
2eeaacb9 DM |
1357 | .optional( |
1358 | "include-dev", | |
1359 | ArraySchema::new( | |
1360 | "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.", | |
1361 | StringSchema::new("Path to file.").into() | |
1362 | ) | |
1363 | ) | |
6d0983db DM |
1364 | .optional( |
1365 | "keyfile", | |
1366 | StringSchema::new("Path to encryption key. All data will be encrypted using this key.")) | |
219ef0e6 DM |
1367 | .optional( |
1368 | "verbose", | |
1369 | BooleanSchema::new("Verbose output.").default(false)) | |
5b72c9b4 DM |
1370 | .optional( |
1371 | "skip-lost-and-found", | |
1372 | BooleanSchema::new("Skip lost+found directory").default(false)) | |
fba30411 | 1373 | .optional( |
bbf9e7e9 DM |
1374 | "backup-type", |
1375 | BACKUP_TYPE_SCHEMA.clone() | |
1376 | ) | |
1377 | .optional( | |
1378 | "backup-id", | |
1379 | BACKUP_ID_SCHEMA.clone() | |
1380 | ) | |
ca5d0b61 DM |
1381 | .optional( |
1382 | "backup-time", | |
bbf9e7e9 | 1383 | BACKUP_TIME_SCHEMA.clone() |
ca5d0b61 | 1384 | ) |
2d9d143a DM |
1385 | .optional( |
1386 | "chunk-size", | |
1387 | IntegerSchema::new("Chunk size in KB. Must be a power of 2.") | |
1388 | .minimum(64) | |
1389 | .maximum(4096) | |
1390 | .default(4096) | |
1391 | ) | |
ff5d3707 | 1392 | )) |
2665cef7 | 1393 | .arg_param(vec!["backupspec"]) |
d0a03d40 | 1394 | .completion_cb("repository", complete_repository) |
49811347 | 1395 | .completion_cb("backupspec", complete_backup_source) |
6d0983db | 1396 | .completion_cb("keyfile", tools::complete_file_name) |
49811347 | 1397 | .completion_cb("chunk-size", complete_chunk_size); |
f8838fe9 | 1398 | |
ec34f7eb DM |
1399 | let upload_log_cmd_def = CliCommand::new( |
1400 | ApiMethod::new( | |
1401 | upload_log, | |
1402 | ObjectSchema::new("Upload backup log file.") | |
1403 | .required("snapshot", StringSchema::new("Snapshot path.")) | |
1404 | .required("logfile", StringSchema::new("The path to the log file you want to upload.")) | |
1405 | .optional("repository", REPO_URL_SCHEMA.clone()) | |
1406 | .optional( | |
1407 | "keyfile", | |
1408 | StringSchema::new("Path to encryption key. All data will be encrypted using this key.")) | |
1409 | )) | |
1410 | .arg_param(vec!["snapshot", "logfile"]) | |
1411 | .completion_cb("snapshot", complete_group_or_snapshot) | |
1412 | .completion_cb("logfile", tools::complete_file_name) | |
1413 | .completion_cb("keyfile", tools::complete_file_name) | |
1414 | .completion_cb("repository", complete_repository); | |
1415 | ||
41c039e1 DM |
1416 | let list_cmd_def = CliCommand::new( |
1417 | ApiMethod::new( | |
812c6f87 DM |
1418 | list_backup_groups, |
1419 | ObjectSchema::new("List backup groups.") | |
2665cef7 | 1420 | .optional("repository", REPO_URL_SCHEMA.clone()) |
34a816cc | 1421 | .optional("output-format", OUTPUT_FORMAT.clone()) |
41c039e1 | 1422 | )) |
d0a03d40 | 1423 | .completion_cb("repository", complete_repository); |
41c039e1 | 1424 | |
184f17af DM |
1425 | let snapshots_cmd_def = CliCommand::new( |
1426 | ApiMethod::new( | |
1427 | list_snapshots, | |
1428 | ObjectSchema::new("List backup snapshots.") | |
15c847f1 | 1429 | .optional("group", StringSchema::new("Backup group.")) |
2665cef7 | 1430 | .optional("repository", REPO_URL_SCHEMA.clone()) |
34a816cc | 1431 | .optional("output-format", OUTPUT_FORMAT.clone()) |
184f17af | 1432 | )) |
2665cef7 | 1433 | .arg_param(vec!["group"]) |
024f11bb | 1434 | .completion_cb("group", complete_backup_group) |
d0a03d40 | 1435 | .completion_cb("repository", complete_repository); |
184f17af | 1436 | |
6f62c924 DM |
1437 | let forget_cmd_def = CliCommand::new( |
1438 | ApiMethod::new( | |
1439 | forget_snapshots, | |
1440 | ObjectSchema::new("Forget (remove) backup snapshots.") | |
6f62c924 | 1441 | .required("snapshot", StringSchema::new("Snapshot path.")) |
2665cef7 | 1442 | .optional("repository", REPO_URL_SCHEMA.clone()) |
6f62c924 | 1443 | )) |
2665cef7 | 1444 | .arg_param(vec!["snapshot"]) |
b2388518 DM |
1445 | .completion_cb("repository", complete_repository) |
1446 | .completion_cb("snapshot", complete_group_or_snapshot); | |
6f62c924 | 1447 | |
8cc0d6af DM |
1448 | let garbage_collect_cmd_def = CliCommand::new( |
1449 | ApiMethod::new( | |
1450 | start_garbage_collection, | |
1451 | ObjectSchema::new("Start garbage collection for a specific repository.") | |
2665cef7 | 1452 | .optional("repository", REPO_URL_SCHEMA.clone()) |
8cc0d6af | 1453 | )) |
d0a03d40 | 1454 | .completion_cb("repository", complete_repository); |
8cc0d6af | 1455 | |
9f912493 DM |
1456 | let restore_cmd_def = CliCommand::new( |
1457 | ApiMethod::new( | |
1458 | restore, | |
1459 | ObjectSchema::new("Restore backup repository.") | |
d5c34d98 DM |
1460 | .required("snapshot", StringSchema::new("Group/Snapshot path.")) |
1461 | .required("archive-name", StringSchema::new("Backup archive name.")) | |
bf125261 DM |
1462 | .required("target", StringSchema::new(r###"Target directory path. Use '-' to write to stdandard output. |
1463 | ||
1464 | We do not extraxt '.pxar' archives when writing to stdandard output. | |
1465 | ||
1466 | "### | |
1467 | )) | |
46d5aa0a DM |
1468 | .optional( |
1469 | "allow-existing-dirs", | |
1470 | BooleanSchema::new("Do not fail if directories already exists.").default(false)) | |
2665cef7 | 1471 | .optional("repository", REPO_URL_SCHEMA.clone()) |
86eda3eb DM |
1472 | .optional("keyfile", StringSchema::new("Path to encryption key.")) |
1473 | .optional( | |
1474 | "verbose", | |
1475 | BooleanSchema::new("Verbose output.").default(false) | |
1476 | ) | |
9f912493 | 1477 | )) |
2665cef7 | 1478 | .arg_param(vec!["snapshot", "archive-name", "target"]) |
b2388518 | 1479 | .completion_cb("repository", complete_repository) |
08dc340a DM |
1480 | .completion_cb("snapshot", complete_group_or_snapshot) |
1481 | .completion_cb("archive-name", complete_archive_name) | |
1482 | .completion_cb("target", tools::complete_file_name); | |
9f912493 | 1483 | |
52c171e4 DM |
1484 | let files_cmd_def = CliCommand::new( |
1485 | ApiMethod::new( | |
1486 | list_snapshot_files, | |
1487 | ObjectSchema::new("List snapshot files.") | |
1488 | .required("snapshot", StringSchema::new("Snapshot path.")) | |
cec17a3e | 1489 | .optional("repository", REPO_URL_SCHEMA.clone()) |
52c171e4 DM |
1490 | .optional("output-format", OUTPUT_FORMAT.clone()) |
1491 | )) | |
1492 | .arg_param(vec!["snapshot"]) | |
1493 | .completion_cb("repository", complete_repository) | |
1494 | .completion_cb("snapshot", complete_group_or_snapshot); | |
1495 | ||
83b7db02 DM |
1496 | let prune_cmd_def = CliCommand::new( |
1497 | ApiMethod::new( | |
1498 | prune, | |
1499 | proxmox_backup::api2::admin::datastore::add_common_prune_prameters( | |
1500 | ObjectSchema::new("Prune backup repository.") | |
9fdc3ef4 | 1501 | .required("group", StringSchema::new("Backup group.")) |
2665cef7 | 1502 | .optional("repository", REPO_URL_SCHEMA.clone()) |
83b7db02 DM |
1503 | ) |
1504 | )) | |
9fdc3ef4 DM |
1505 | .arg_param(vec!["group"]) |
1506 | .completion_cb("group", complete_backup_group) | |
d0a03d40 | 1507 | .completion_cb("repository", complete_repository); |
9f912493 | 1508 | |
34a816cc DM |
1509 | let status_cmd_def = CliCommand::new( |
1510 | ApiMethod::new( | |
1511 | status, | |
1512 | ObjectSchema::new("Get repository status.") | |
1513 | .optional("repository", REPO_URL_SCHEMA.clone()) | |
1514 | .optional("output-format", OUTPUT_FORMAT.clone()) | |
1515 | )) | |
1516 | .completion_cb("repository", complete_repository); | |
1517 | ||
41c039e1 | 1518 | let cmd_def = CliCommandMap::new() |
597a9203 | 1519 | .insert("backup".to_owned(), backup_cmd_def.into()) |
ec34f7eb | 1520 | .insert("upload-log".to_owned(), upload_log_cmd_def.into()) |
6f62c924 | 1521 | .insert("forget".to_owned(), forget_cmd_def.into()) |
8cc0d6af | 1522 | .insert("garbage-collect".to_owned(), garbage_collect_cmd_def.into()) |
83b7db02 | 1523 | .insert("list".to_owned(), list_cmd_def.into()) |
184f17af | 1524 | .insert("prune".to_owned(), prune_cmd_def.into()) |
9f912493 | 1525 | .insert("restore".to_owned(), restore_cmd_def.into()) |
f2401311 | 1526 | .insert("snapshots".to_owned(), snapshots_cmd_def.into()) |
52c171e4 | 1527 | .insert("files".to_owned(), files_cmd_def.into()) |
34a816cc | 1528 | .insert("status".to_owned(), status_cmd_def.into()) |
f2401311 | 1529 | .insert("key".to_owned(), key_mgmt_cli().into()); |
a914a774 | 1530 | |
5a2df000 DM |
1531 | hyper::rt::run(futures::future::lazy(move || { |
1532 | run_cli_command(cmd_def.into()); | |
1533 | Ok(()) | |
1534 | })); | |
496a6784 | 1535 | |
ff5d3707 | 1536 | } |