]>
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; |
1c0472e8 | 6 | use chrono::{Local, TimeZone}; |
e9c9409a | 7 | use std::path::{Path, PathBuf}; |
496a6784 | 8 | use std::collections::HashMap; |
ff5d3707 | 9 | |
fe0e04c6 | 10 | use proxmox_backup::tools; |
4de0e142 | 11 | use proxmox_backup::cli::*; |
ef2f2efb | 12 | use proxmox_backup::api_schema::*; |
dc9a007b | 13 | use proxmox_backup::api_schema::router::*; |
151c6ce2 | 14 | use proxmox_backup::client::*; |
247cdbce | 15 | use proxmox_backup::backup::*; |
fe0e04c6 DM |
16 | //use proxmox_backup::backup::image_index::*; |
17 | //use proxmox_backup::config::datastore; | |
8968258b | 18 | //use proxmox_backup::pxar::encoder::*; |
728797d0 | 19 | //use proxmox_backup::backup::datastore::*; |
23bb8780 | 20 | |
f5f13ebc | 21 | use serde_json::{json, Value}; |
1c0472e8 | 22 | //use hyper::Body; |
33d64b81 | 23 | use std::sync::Arc; |
ae0be2dd | 24 | use regex::Regex; |
d0a03d40 | 25 | use xdg::BaseDirectories; |
ae0be2dd DM |
26 | |
27 | use lazy_static::lazy_static; | |
5a2df000 | 28 | use futures::*; |
c4ff3dce | 29 | use tokio::sync::mpsc; |
ae0be2dd DM |
30 | |
31 | lazy_static! { | |
ec8a9bb9 | 32 | static ref BACKUPSPEC_REGEX: Regex = Regex::new(r"^([a-zA-Z0-9_-]+\.(?:pxar|img|conf)):(.+)$").unwrap(); |
f2401311 DM |
33 | |
34 | static ref REPO_URL_SCHEMA: Arc<Schema> = Arc::new( | |
35 | StringSchema::new("Repository URL.") | |
36 | .format(BACKUP_REPO_URL.clone()) | |
37 | .max_length(256) | |
38 | .into() | |
39 | ); | |
ae0be2dd | 40 | } |
33d64b81 | 41 | |
d0a03d40 DM |
42 | |
43 | fn record_repository(repo: &BackupRepository) { | |
44 | ||
45 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
46 | Ok(v) => v, | |
47 | _ => return, | |
48 | }; | |
49 | ||
50 | // usually $HOME/.cache/proxmox-backup/repo-list | |
51 | let path = match base.place_cache_file("repo-list") { | |
52 | Ok(v) => v, | |
53 | _ => return, | |
54 | }; | |
55 | ||
49cf9f3d | 56 | let mut data = tools::file_get_json(&path, None).unwrap_or(json!({})); |
d0a03d40 DM |
57 | |
58 | let repo = repo.to_string(); | |
59 | ||
60 | data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 }; | |
61 | ||
62 | let mut map = serde_json::map::Map::new(); | |
63 | ||
64 | loop { | |
65 | let mut max_used = 0; | |
66 | let mut max_repo = None; | |
67 | for (repo, count) in data.as_object().unwrap() { | |
68 | if map.contains_key(repo) { continue; } | |
69 | if let Some(count) = count.as_i64() { | |
70 | if count > max_used { | |
71 | max_used = count; | |
72 | max_repo = Some(repo); | |
73 | } | |
74 | } | |
75 | } | |
76 | if let Some(repo) = max_repo { | |
77 | map.insert(repo.to_owned(), json!(max_used)); | |
78 | } else { | |
79 | break; | |
80 | } | |
81 | if map.len() > 10 { // store max. 10 repos | |
82 | break; | |
83 | } | |
84 | } | |
85 | ||
86 | let new_data = json!(map); | |
87 | ||
88 | let _ = tools::file_set_contents(path, new_data.to_string().as_bytes(), None); | |
89 | } | |
90 | ||
49811347 | 91 | fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
d0a03d40 DM |
92 | |
93 | let mut result = vec![]; | |
94 | ||
95 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
96 | Ok(v) => v, | |
97 | _ => return result, | |
98 | }; | |
99 | ||
100 | // usually $HOME/.cache/proxmox-backup/repo-list | |
101 | let path = match base.place_cache_file("repo-list") { | |
102 | Ok(v) => v, | |
103 | _ => return result, | |
104 | }; | |
105 | ||
49cf9f3d | 106 | let data = tools::file_get_json(&path, None).unwrap_or(json!({})); |
d0a03d40 DM |
107 | |
108 | if let Some(map) = data.as_object() { | |
49811347 | 109 | for (repo, _count) in map { |
d0a03d40 DM |
110 | result.push(repo.to_owned()); |
111 | } | |
112 | } | |
113 | ||
114 | result | |
115 | } | |
116 | ||
17d6979a | 117 | fn backup_directory<P: AsRef<Path>>( |
c4ff3dce | 118 | client: &BackupClient, |
17d6979a | 119 | dir_path: P, |
247cdbce | 120 | archive_name: &str, |
36898ffc | 121 | chunk_size: Option<usize>, |
eed6db39 | 122 | all_file_systems: bool, |
219ef0e6 | 123 | verbose: bool, |
f98ac774 | 124 | crypt_config: Option<Arc<CryptConfig>>, |
247cdbce | 125 | ) -> Result<(), Error> { |
33d64b81 | 126 | |
c4ff3dce | 127 | let pxar_stream = PxarBackupStream::open(dir_path.as_ref(), all_file_systems, verbose)?; |
36898ffc | 128 | let chunk_stream = ChunkStream::new(pxar_stream, chunk_size); |
ff3d3100 | 129 | |
c4ff3dce | 130 | let (tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks |
5e7a09be | 131 | |
c4ff3dce DM |
132 | let stream = rx |
133 | .map_err(Error::from) | |
134 | .and_then(|x| x); // flatten | |
17d6979a | 135 | |
c4ff3dce DM |
136 | // spawn chunker inside a separate task so that it can run parallel |
137 | tokio::spawn( | |
138 | tx.send_all(chunk_stream.then(|r| Ok(r))) | |
1c0472e8 | 139 | .map_err(|_| {}).map(|_| ()) |
c4ff3dce | 140 | ); |
17d6979a | 141 | |
f98ac774 | 142 | client.upload_stream(archive_name, stream, "dynamic", None, crypt_config).wait()?; |
bcd879cf DM |
143 | |
144 | Ok(()) | |
145 | } | |
146 | ||
6af905c1 DM |
147 | fn backup_image<P: AsRef<Path>>( |
148 | client: &BackupClient, | |
149 | image_path: P, | |
150 | archive_name: &str, | |
151 | image_size: u64, | |
36898ffc | 152 | chunk_size: Option<usize>, |
1c0472e8 | 153 | _verbose: bool, |
f98ac774 | 154 | crypt_config: Option<Arc<CryptConfig>>, |
6af905c1 DM |
155 | ) -> Result<(), Error> { |
156 | ||
6af905c1 DM |
157 | let path = image_path.as_ref().to_owned(); |
158 | ||
159 | let file = tokio::fs::File::open(path).wait()?; | |
160 | ||
161 | let stream = tokio::codec::FramedRead::new(file, tokio::codec::BytesCodec::new()) | |
162 | .map_err(Error::from); | |
163 | ||
36898ffc | 164 | let stream = FixedChunkStream::new(stream, chunk_size.unwrap_or(4*1024*1024)); |
6af905c1 | 165 | |
f98ac774 | 166 | client.upload_stream(archive_name, stream, "fixed", Some(image_size), crypt_config).wait()?; |
6af905c1 DM |
167 | |
168 | Ok(()) | |
169 | } | |
170 | ||
6899dbfb | 171 | fn strip_server_file_expenstions(list: Vec<String>) -> Vec<String> { |
8e39232a DM |
172 | |
173 | let mut result = vec![]; | |
174 | ||
175 | for file in list.into_iter() { | |
176 | if file.ends_with(".didx") { | |
177 | result.push(file[..file.len()-5].to_owned()); | |
178 | } else if file.ends_with(".fidx") { | |
179 | result.push(file[..file.len()-5].to_owned()); | |
6899dbfb DM |
180 | } else if file.ends_with(".blob") { |
181 | result.push(file[..file.len()-5].to_owned()); | |
8e39232a DM |
182 | } else { |
183 | result.push(file); // should not happen | |
184 | } | |
185 | } | |
186 | ||
187 | result | |
188 | } | |
189 | ||
8968258b | 190 | /* not used: |
6049b71f DM |
191 | fn list_backups( |
192 | param: Value, | |
193 | _info: &ApiMethod, | |
dd5495d6 | 194 | _rpcenv: &mut dyn RpcEnvironment, |
6049b71f | 195 | ) -> Result<Value, Error> { |
41c039e1 | 196 | |
33d64b81 | 197 | let repo_url = tools::required_string_param(¶m, "repository")?; |
edd3c8c6 | 198 | let repo: BackupRepository = repo_url.parse()?; |
41c039e1 | 199 | |
45cdce06 | 200 | let mut client = HttpClient::new(repo.host(), repo.user())?; |
41c039e1 | 201 | |
d0a03d40 | 202 | let path = format!("api2/json/admin/datastore/{}/backups", repo.store()); |
41c039e1 | 203 | |
9e391bb7 | 204 | let result = client.get(&path, None)?; |
41c039e1 | 205 | |
d0a03d40 DM |
206 | record_repository(&repo); |
207 | ||
8c75372b DM |
208 | // fixme: implement and use output formatter instead .. |
209 | let list = result["data"].as_array().unwrap(); | |
210 | ||
211 | for item in list { | |
212 | ||
49dc0740 DM |
213 | let id = item["backup-id"].as_str().unwrap(); |
214 | let btype = item["backup-type"].as_str().unwrap(); | |
215 | let epoch = item["backup-time"].as_i64().unwrap(); | |
e909522f | 216 | |
391d3107 | 217 | let backup_dir = BackupDir::new(btype, id, epoch); |
e909522f DM |
218 | |
219 | let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect(); | |
6899dbfb | 220 | let files = strip_server_file_expenstions(files); |
e909522f | 221 | |
8e39232a DM |
222 | for filename in files { |
223 | let path = backup_dir.relative_path().to_str().unwrap().to_owned(); | |
224 | println!("{} | {}/{}", backup_dir.backup_time().format("%c"), path, filename); | |
8c75372b DM |
225 | } |
226 | } | |
227 | ||
228 | //Ok(result) | |
229 | Ok(Value::Null) | |
41c039e1 | 230 | } |
8968258b | 231 | */ |
41c039e1 | 232 | |
812c6f87 DM |
233 | fn list_backup_groups( |
234 | param: Value, | |
235 | _info: &ApiMethod, | |
dd5495d6 | 236 | _rpcenv: &mut dyn RpcEnvironment, |
812c6f87 DM |
237 | ) -> Result<Value, Error> { |
238 | ||
239 | let repo_url = tools::required_string_param(¶m, "repository")?; | |
edd3c8c6 | 240 | let repo: BackupRepository = repo_url.parse()?; |
812c6f87 | 241 | |
45cdce06 | 242 | let client = HttpClient::new(repo.host(), repo.user())?; |
812c6f87 | 243 | |
d0a03d40 | 244 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
812c6f87 | 245 | |
9e391bb7 | 246 | let mut result = client.get(&path, None).wait()?; |
812c6f87 | 247 | |
d0a03d40 DM |
248 | record_repository(&repo); |
249 | ||
812c6f87 | 250 | // fixme: implement and use output formatter instead .. |
80822b95 DM |
251 | let list = result["data"].as_array_mut().unwrap(); |
252 | ||
253 | list.sort_unstable_by(|a, b| { | |
254 | let a_id = a["backup-id"].as_str().unwrap(); | |
255 | let a_backup_type = a["backup-type"].as_str().unwrap(); | |
256 | let b_id = b["backup-id"].as_str().unwrap(); | |
257 | let b_backup_type = b["backup-type"].as_str().unwrap(); | |
258 | ||
259 | let type_order = a_backup_type.cmp(b_backup_type); | |
260 | if type_order == std::cmp::Ordering::Equal { | |
261 | a_id.cmp(b_id) | |
262 | } else { | |
263 | type_order | |
264 | } | |
265 | }); | |
812c6f87 DM |
266 | |
267 | for item in list { | |
268 | ||
ad20d198 DM |
269 | let id = item["backup-id"].as_str().unwrap(); |
270 | let btype = item["backup-type"].as_str().unwrap(); | |
271 | let epoch = item["last-backup"].as_i64().unwrap(); | |
812c6f87 | 272 | let last_backup = Local.timestamp(epoch, 0); |
ad20d198 | 273 | let backup_count = item["backup-count"].as_u64().unwrap(); |
812c6f87 | 274 | |
1e9a94e5 | 275 | let group = BackupGroup::new(btype, id); |
812c6f87 DM |
276 | |
277 | let path = group.group_path().to_str().unwrap().to_owned(); | |
ad20d198 | 278 | |
8e39232a | 279 | let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect(); |
6899dbfb | 280 | let files = strip_server_file_expenstions(files); |
ad20d198 | 281 | |
80822b95 | 282 | println!("{:20} | {} | {:5} | {}", path, last_backup.format("%c"), |
ad20d198 | 283 | backup_count, tools::join(&files, ' ')); |
812c6f87 DM |
284 | } |
285 | ||
286 | //Ok(result) | |
287 | Ok(Value::Null) | |
288 | } | |
289 | ||
184f17af DM |
290 | fn list_snapshots( |
291 | param: Value, | |
292 | _info: &ApiMethod, | |
dd5495d6 | 293 | _rpcenv: &mut dyn RpcEnvironment, |
184f17af DM |
294 | ) -> Result<Value, Error> { |
295 | ||
296 | let repo_url = tools::required_string_param(¶m, "repository")?; | |
edd3c8c6 | 297 | let repo: BackupRepository = repo_url.parse()?; |
184f17af DM |
298 | |
299 | let path = tools::required_string_param(¶m, "group")?; | |
300 | let group = BackupGroup::parse(path)?; | |
301 | ||
45cdce06 | 302 | let client = HttpClient::new(repo.host(), repo.user())?; |
184f17af | 303 | |
9e391bb7 | 304 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
184f17af | 305 | |
9e391bb7 DM |
306 | let result = client.get(&path, Some(json!({ |
307 | "backup-type": group.backup_type(), | |
308 | "backup-id": group.backup_id(), | |
309 | }))).wait()?; | |
184f17af | 310 | |
d0a03d40 DM |
311 | record_repository(&repo); |
312 | ||
184f17af DM |
313 | // fixme: implement and use output formatter instead .. |
314 | let list = result["data"].as_array().unwrap(); | |
315 | ||
316 | for item in list { | |
317 | ||
318 | let id = item["backup-id"].as_str().unwrap(); | |
319 | let btype = item["backup-type"].as_str().unwrap(); | |
320 | let epoch = item["backup-time"].as_i64().unwrap(); | |
184f17af | 321 | |
391d3107 | 322 | let snapshot = BackupDir::new(btype, id, epoch); |
184f17af DM |
323 | |
324 | let path = snapshot.relative_path().to_str().unwrap().to_owned(); | |
325 | ||
8e39232a | 326 | let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect(); |
6899dbfb | 327 | let files = strip_server_file_expenstions(files); |
184f17af | 328 | |
875fb1c0 | 329 | println!("{} | {} | {}", path, snapshot.backup_time().format("%c"), tools::join(&files, ' ')); |
184f17af DM |
330 | } |
331 | ||
332 | Ok(Value::Null) | |
333 | } | |
334 | ||
6f62c924 DM |
335 | fn forget_snapshots( |
336 | param: Value, | |
337 | _info: &ApiMethod, | |
dd5495d6 | 338 | _rpcenv: &mut dyn RpcEnvironment, |
6f62c924 DM |
339 | ) -> Result<Value, Error> { |
340 | ||
341 | let repo_url = tools::required_string_param(¶m, "repository")?; | |
edd3c8c6 | 342 | let repo: BackupRepository = repo_url.parse()?; |
6f62c924 DM |
343 | |
344 | let path = tools::required_string_param(¶m, "snapshot")?; | |
345 | let snapshot = BackupDir::parse(path)?; | |
346 | ||
45cdce06 | 347 | let mut client = HttpClient::new(repo.host(), repo.user())?; |
6f62c924 | 348 | |
9e391bb7 | 349 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
6f62c924 | 350 | |
9e391bb7 DM |
351 | let result = client.delete(&path, Some(json!({ |
352 | "backup-type": snapshot.group().backup_type(), | |
353 | "backup-id": snapshot.group().backup_id(), | |
354 | "backup-time": snapshot.backup_time().timestamp(), | |
355 | }))).wait()?; | |
6f62c924 | 356 | |
d0a03d40 DM |
357 | record_repository(&repo); |
358 | ||
6f62c924 DM |
359 | Ok(result) |
360 | } | |
361 | ||
8cc0d6af DM |
362 | fn start_garbage_collection( |
363 | param: Value, | |
364 | _info: &ApiMethod, | |
dd5495d6 | 365 | _rpcenv: &mut dyn RpcEnvironment, |
8cc0d6af DM |
366 | ) -> Result<Value, Error> { |
367 | ||
368 | let repo_url = tools::required_string_param(¶m, "repository")?; | |
edd3c8c6 | 369 | let repo: BackupRepository = repo_url.parse()?; |
8cc0d6af | 370 | |
45cdce06 | 371 | let mut client = HttpClient::new(repo.host(), repo.user())?; |
8cc0d6af | 372 | |
d0a03d40 | 373 | let path = format!("api2/json/admin/datastore/{}/gc", repo.store()); |
8cc0d6af | 374 | |
5a2df000 | 375 | let result = client.post(&path, None).wait()?; |
8cc0d6af | 376 | |
d0a03d40 DM |
377 | record_repository(&repo); |
378 | ||
8cc0d6af DM |
379 | Ok(result) |
380 | } | |
33d64b81 | 381 | |
ae0be2dd DM |
382 | fn parse_backupspec(value: &str) -> Result<(&str, &str), Error> { |
383 | ||
384 | if let Some(caps) = BACKUPSPEC_REGEX.captures(value) { | |
385 | return Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str())); | |
386 | } | |
387 | bail!("unable to parse directory specification '{}'", value); | |
388 | } | |
389 | ||
6049b71f DM |
390 | fn create_backup( |
391 | param: Value, | |
392 | _info: &ApiMethod, | |
dd5495d6 | 393 | _rpcenv: &mut dyn RpcEnvironment, |
6049b71f | 394 | ) -> Result<Value, Error> { |
ff5d3707 | 395 | |
33d64b81 | 396 | let repo_url = tools::required_string_param(¶m, "repository")?; |
ae0be2dd DM |
397 | |
398 | let backupspec_list = tools::required_array_param(¶m, "backupspec")?; | |
a914a774 | 399 | |
edd3c8c6 | 400 | let repo: BackupRepository = repo_url.parse()?; |
33d64b81 | 401 | |
eed6db39 DM |
402 | let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false); |
403 | ||
219ef0e6 DM |
404 | let verbose = param["verbose"].as_bool().unwrap_or(false); |
405 | ||
36898ffc | 406 | let chunk_size_opt = param["chunk-size"].as_u64().map(|v| (v*1024) as usize); |
2d9d143a | 407 | |
247cdbce DM |
408 | if let Some(size) = chunk_size_opt { |
409 | verify_chunk_size(size)?; | |
2d9d143a DM |
410 | } |
411 | ||
6d0983db DM |
412 | let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p)); |
413 | ||
fba30411 DM |
414 | let backup_id = param["host-id"].as_str().unwrap_or(&tools::nodename()); |
415 | ||
ae0be2dd | 416 | let mut upload_list = vec![]; |
a914a774 | 417 | |
ec8a9bb9 | 418 | enum BackupType { PXAR, IMAGE, CONFIG }; |
6af905c1 | 419 | |
ae0be2dd DM |
420 | for backupspec in backupspec_list { |
421 | let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?; | |
bcd879cf | 422 | |
eb1804c5 DM |
423 | use std::os::unix::fs::FileTypeExt; |
424 | ||
425 | let metadata = match std::fs::metadata(filename) { | |
426 | Ok(m) => m, | |
ae0be2dd DM |
427 | Err(err) => bail!("unable to access '{}' - {}", filename, err), |
428 | }; | |
eb1804c5 | 429 | let file_type = metadata.file_type(); |
23bb8780 | 430 | |
ec8a9bb9 | 431 | let extension = Path::new(target).extension().map(|s| s.to_str().unwrap()).unwrap(); |
bcd879cf | 432 | |
ec8a9bb9 DM |
433 | match extension { |
434 | "pxar" => { | |
435 | if !file_type.is_dir() { | |
436 | bail!("got unexpected file type (expected directory)"); | |
437 | } | |
438 | upload_list.push((BackupType::PXAR, filename.to_owned(), target.to_owned(), 0)); | |
439 | } | |
440 | "img" => { | |
eb1804c5 | 441 | |
ec8a9bb9 DM |
442 | if !(file_type.is_file() || file_type.is_block_device()) { |
443 | bail!("got unexpected file type (expected file or block device)"); | |
444 | } | |
eb1804c5 | 445 | |
ec8a9bb9 | 446 | let size = tools::image_size(&PathBuf::from(filename))?; |
23bb8780 | 447 | |
ec8a9bb9 | 448 | if size == 0 { bail!("got zero-sized file '{}'", filename); } |
ae0be2dd | 449 | |
ec8a9bb9 DM |
450 | upload_list.push((BackupType::IMAGE, filename.to_owned(), target.to_owned(), size)); |
451 | } | |
452 | "conf" => { | |
453 | if !file_type.is_file() { | |
454 | bail!("got unexpected file type (expected regular file)"); | |
455 | } | |
456 | upload_list.push((BackupType::CONFIG, filename.to_owned(), target.to_owned(), metadata.len())); | |
457 | } | |
458 | _ => { | |
459 | bail!("got unknown archive extension '{}'", extension); | |
460 | } | |
ae0be2dd DM |
461 | } |
462 | } | |
463 | ||
cdebd467 | 464 | let backup_time = Local.timestamp(Local::now().timestamp(), 0); |
ae0be2dd | 465 | |
c4ff3dce | 466 | let client = HttpClient::new(repo.host(), repo.user())?; |
d0a03d40 DM |
467 | record_repository(&repo); |
468 | ||
cdebd467 DM |
469 | println!("Starting backup"); |
470 | println!("Client name: {}", tools::nodename()); | |
471 | println!("Start Time: {}", backup_time.to_rfc3339()); | |
51144821 | 472 | |
6d0983db DM |
473 | let crypt_config = match keyfile { |
474 | None => None, | |
475 | Some(path) => { | |
ab44acff | 476 | let (key, _) = load_and_decrtypt_key(&path, get_encryption_key_password)?; |
6d0983db DM |
477 | Some(Arc::new(CryptConfig::new(key)?)) |
478 | } | |
479 | }; | |
f98ac774 | 480 | |
39e60bd6 | 481 | let client = client.start_backup(repo.store(), "host", &backup_id, verbose).wait()?; |
c4ff3dce | 482 | |
6af905c1 DM |
483 | for (backup_type, filename, target, size) in upload_list { |
484 | match backup_type { | |
ec8a9bb9 DM |
485 | BackupType::CONFIG => { |
486 | println!("Upload config file '{}' to '{:?}' as {}", filename, repo, target); | |
9f46c7de | 487 | client.upload_blob_from_file(&filename, &target, crypt_config.clone(), true).wait()?; |
ec8a9bb9 | 488 | } |
6af905c1 DM |
489 | BackupType::PXAR => { |
490 | println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target); | |
f98ac774 DM |
491 | backup_directory( |
492 | &client, | |
493 | &filename, | |
494 | &target, | |
495 | chunk_size_opt, | |
496 | all_file_systems, | |
497 | verbose, | |
498 | crypt_config.clone(), | |
499 | )?; | |
6af905c1 DM |
500 | } |
501 | BackupType::IMAGE => { | |
502 | println!("Upload image '{}' to '{:?}' as {}", filename, repo, target); | |
f98ac774 DM |
503 | backup_image( |
504 | &client, | |
505 | &filename, | |
506 | &target, | |
507 | size, | |
508 | chunk_size_opt, | |
509 | verbose, | |
510 | crypt_config.clone(), | |
511 | )?; | |
6af905c1 DM |
512 | } |
513 | } | |
4818c8b6 DM |
514 | } |
515 | ||
9f46c7de DM |
516 | if let Some(crypt_config) = crypt_config { |
517 | let path = master_pubkey_path()?; | |
518 | if path.exists() { | |
519 | let pem_data = proxmox_backup::tools::file_get_contents(&path)?; | |
520 | let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?; | |
521 | let enc_key = crypt_config.generate_rsa_encoded_key(rsa)?; | |
045e8a56 | 522 | let target = "rsa-encrypted.key"; |
9f46c7de DM |
523 | println!("Upload RSA encoded key to '{:?}' as {}", repo, target); |
524 | client.upload_blob_from_data(enc_key, target, None, false).wait()?; | |
525 | ||
045e8a56 | 526 | // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t |
9f46c7de DM |
527 | /* |
528 | let mut buffer2 = vec![0u8; rsa.size() as usize]; | |
529 | let pem_data = proxmox_backup::tools::file_get_contents("master-private.pem")?; | |
530 | let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?; | |
531 | let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?; | |
532 | println!("TEST {} {:?}", len, buffer2); | |
533 | */ | |
534 | } | |
535 | } | |
536 | ||
c4ff3dce DM |
537 | client.finish().wait()?; |
538 | ||
cdebd467 | 539 | let end_time = Local.timestamp(Local::now().timestamp(), 0); |
3ec3ec3f DM |
540 | let elapsed = end_time.signed_duration_since(backup_time); |
541 | println!("Duration: {}", elapsed); | |
542 | ||
cdebd467 | 543 | println!("End Time: {}", end_time.to_rfc3339()); |
3d5c11e5 | 544 | |
ff5d3707 | 545 | Ok(Value::Null) |
f98ea63d DM |
546 | } |
547 | ||
d0a03d40 | 548 | fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
f98ea63d DM |
549 | |
550 | let mut result = vec![]; | |
551 | ||
552 | let data: Vec<&str> = arg.splitn(2, ':').collect(); | |
553 | ||
bff11030 | 554 | if data.len() != 2 { |
8968258b DM |
555 | result.push(String::from("root.pxar:/")); |
556 | result.push(String::from("etc.pxar:/etc")); | |
bff11030 DM |
557 | return result; |
558 | } | |
f98ea63d | 559 | |
496a6784 | 560 | let files = tools::complete_file_name(data[1], param); |
f98ea63d DM |
561 | |
562 | for file in files { | |
563 | result.push(format!("{}:{}", data[0], file)); | |
564 | } | |
565 | ||
566 | result | |
ff5d3707 | 567 | } |
568 | ||
9f912493 DM |
569 | fn restore( |
570 | param: Value, | |
571 | _info: &ApiMethod, | |
dd5495d6 | 572 | _rpcenv: &mut dyn RpcEnvironment, |
9f912493 DM |
573 | ) -> Result<Value, Error> { |
574 | ||
575 | let repo_url = tools::required_string_param(¶m, "repository")?; | |
edd3c8c6 | 576 | let repo: BackupRepository = repo_url.parse()?; |
9f912493 | 577 | |
d5c34d98 DM |
578 | let archive_name = tools::required_string_param(¶m, "archive-name")?; |
579 | ||
45cdce06 | 580 | let mut client = HttpClient::new(repo.host(), repo.user())?; |
d0a03d40 | 581 | |
d0a03d40 | 582 | record_repository(&repo); |
d5c34d98 | 583 | |
9f912493 | 584 | let path = tools::required_string_param(¶m, "snapshot")?; |
9f912493 | 585 | |
d5c34d98 | 586 | let query; |
9f912493 | 587 | |
d5c34d98 DM |
588 | if path.matches('/').count() == 1 { |
589 | let group = BackupGroup::parse(path)?; | |
9f912493 | 590 | |
9e391bb7 DM |
591 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); |
592 | let result = client.get(&path, Some(json!({ | |
d5c34d98 DM |
593 | "backup-type": group.backup_type(), |
594 | "backup-id": group.backup_id(), | |
9e391bb7 | 595 | }))).wait()?; |
9f912493 | 596 | |
d5c34d98 DM |
597 | let list = result["data"].as_array().unwrap(); |
598 | if list.len() == 0 { | |
599 | bail!("backup group '{}' does not contain any snapshots:", path); | |
600 | } | |
9f912493 | 601 | |
d5c34d98 DM |
602 | query = tools::json_object_to_query(json!({ |
603 | "backup-type": group.backup_type(), | |
604 | "backup-id": group.backup_id(), | |
605 | "backup-time": list[0]["backup-time"].as_i64().unwrap(), | |
606 | "archive-name": archive_name, | |
607 | }))?; | |
608 | } else { | |
609 | let snapshot = BackupDir::parse(path)?; | |
9f912493 | 610 | |
d5c34d98 | 611 | query = tools::json_object_to_query(json!({ |
9f912493 DM |
612 | "backup-type": snapshot.group().backup_type(), |
613 | "backup-id": snapshot.group().backup_id(), | |
614 | "backup-time": snapshot.backup_time().timestamp(), | |
d5c34d98 | 615 | "archive-name": archive_name, |
9f912493 | 616 | }))?; |
d5c34d98 | 617 | } |
9f912493 | 618 | |
d5c34d98 | 619 | let target = tools::required_string_param(¶m, "target")?; |
2ae7d196 | 620 | |
8968258b DM |
621 | if archive_name.ends_with(".pxar") { |
622 | let path = format!("api2/json/admin/datastore/{}/pxar?{}", repo.store(), query); | |
2ae7d196 | 623 | |
d5c34d98 DM |
624 | println!("DOWNLOAD FILE {} to {}", path, target); |
625 | ||
626 | let target = PathBuf::from(target); | |
5defa71b | 627 | let writer = PxarDecodeWriter::new(&target, true)?; |
5a2df000 | 628 | client.download(&path, Box::new(writer)).wait()?; |
d5c34d98 DM |
629 | } else { |
630 | bail!("unknown file extensions - unable to download '{}'", archive_name); | |
9f912493 DM |
631 | } |
632 | ||
633 | Ok(Value::Null) | |
634 | } | |
635 | ||
83b7db02 DM |
636 | fn prune( |
637 | mut param: Value, | |
638 | _info: &ApiMethod, | |
dd5495d6 | 639 | _rpcenv: &mut dyn RpcEnvironment, |
83b7db02 DM |
640 | ) -> Result<Value, Error> { |
641 | ||
642 | let repo_url = tools::required_string_param(¶m, "repository")?; | |
edd3c8c6 | 643 | let repo: BackupRepository = repo_url.parse()?; |
83b7db02 | 644 | |
45cdce06 | 645 | let mut client = HttpClient::new(repo.host(), repo.user())?; |
83b7db02 | 646 | |
d0a03d40 | 647 | let path = format!("api2/json/admin/datastore/{}/prune", repo.store()); |
83b7db02 DM |
648 | |
649 | param.as_object_mut().unwrap().remove("repository"); | |
650 | ||
5a2df000 | 651 | let result = client.post(&path, Some(param)).wait()?; |
83b7db02 | 652 | |
d0a03d40 DM |
653 | record_repository(&repo); |
654 | ||
83b7db02 DM |
655 | Ok(result) |
656 | } | |
657 | ||
5a2df000 | 658 | // like get, but simply ignore errors and return Null instead |
b2388518 | 659 | fn try_get(repo: &BackupRepository, url: &str) -> Value { |
024f11bb | 660 | |
45cdce06 DM |
661 | let client = match HttpClient::new(repo.host(), repo.user()) { |
662 | Ok(v) => v, | |
663 | _ => return Value::Null, | |
664 | }; | |
b2388518 | 665 | |
9e391bb7 | 666 | let mut resp = match client.get(url, None).wait() { |
b2388518 DM |
667 | Ok(v) => v, |
668 | _ => return Value::Null, | |
669 | }; | |
670 | ||
671 | if let Some(map) = resp.as_object_mut() { | |
672 | if let Some(data) = map.remove("data") { | |
673 | return data; | |
674 | } | |
675 | } | |
676 | Value::Null | |
677 | } | |
678 | ||
679 | fn extract_repo(param: &HashMap<String, String>) -> Option<BackupRepository> { | |
024f11bb DM |
680 | |
681 | let repo_url = match param.get("repository") { | |
682 | Some(v) => v, | |
b2388518 | 683 | _ => return None, |
024f11bb DM |
684 | }; |
685 | ||
686 | let repo: BackupRepository = match repo_url.parse() { | |
687 | Ok(v) => v, | |
b2388518 | 688 | _ => return None, |
024f11bb DM |
689 | }; |
690 | ||
b2388518 DM |
691 | Some(repo) |
692 | } | |
024f11bb | 693 | |
b2388518 | 694 | fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
024f11bb | 695 | |
b2388518 DM |
696 | let mut result = vec![]; |
697 | ||
698 | let repo = match extract_repo(param) { | |
699 | Some(v) => v, | |
024f11bb DM |
700 | _ => return result, |
701 | }; | |
702 | ||
b2388518 DM |
703 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
704 | ||
705 | let data = try_get(&repo, &path); | |
706 | ||
707 | if let Some(list) = data.as_array() { | |
024f11bb | 708 | for item in list { |
98f0b972 DM |
709 | if let (Some(backup_id), Some(backup_type)) = |
710 | (item["backup-id"].as_str(), item["backup-type"].as_str()) | |
711 | { | |
712 | result.push(format!("{}/{}", backup_type, backup_id)); | |
024f11bb DM |
713 | } |
714 | } | |
715 | } | |
716 | ||
717 | result | |
718 | } | |
719 | ||
b2388518 DM |
720 | fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
721 | ||
722 | let mut result = vec![]; | |
723 | ||
724 | let repo = match extract_repo(param) { | |
725 | Some(v) => v, | |
726 | _ => return result, | |
727 | }; | |
728 | ||
729 | if arg.matches('/').count() < 2 { | |
730 | let groups = complete_backup_group(arg, param); | |
731 | for group in groups { | |
732 | result.push(group.to_string()); | |
733 | result.push(format!("{}/", group)); | |
734 | } | |
735 | return result; | |
736 | } | |
737 | ||
738 | let mut parts = arg.split('/'); | |
739 | let query = tools::json_object_to_query(json!({ | |
740 | "backup-type": parts.next().unwrap(), | |
741 | "backup-id": parts.next().unwrap(), | |
742 | })).unwrap(); | |
743 | ||
744 | let path = format!("api2/json/admin/datastore/{}/snapshots?{}", repo.store(), query); | |
745 | ||
746 | let data = try_get(&repo, &path); | |
747 | ||
748 | if let Some(list) = data.as_array() { | |
749 | for item in list { | |
750 | if let (Some(backup_id), Some(backup_type), Some(backup_time)) = | |
751 | (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64()) | |
752 | { | |
753 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time); | |
754 | result.push(snapshot.relative_path().to_str().unwrap().to_owned()); | |
755 | } | |
756 | } | |
757 | } | |
758 | ||
759 | result | |
760 | } | |
761 | ||
08dc340a DM |
762 | fn complete_archive_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
763 | ||
764 | let mut result = vec![]; | |
765 | ||
766 | let repo = match extract_repo(param) { | |
767 | Some(v) => v, | |
768 | _ => return result, | |
769 | }; | |
770 | ||
771 | let snapshot = match param.get("snapshot") { | |
772 | Some(path) => { | |
773 | match BackupDir::parse(path) { | |
774 | Ok(v) => v, | |
775 | _ => return result, | |
776 | } | |
777 | } | |
778 | _ => return result, | |
779 | }; | |
780 | ||
781 | let query = tools::json_object_to_query(json!({ | |
782 | "backup-type": snapshot.group().backup_type(), | |
783 | "backup-id": snapshot.group().backup_id(), | |
784 | "backup-time": snapshot.backup_time().timestamp(), | |
785 | })).unwrap(); | |
786 | ||
787 | let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query); | |
788 | ||
789 | let data = try_get(&repo, &path); | |
790 | ||
791 | if let Some(list) = data.as_array() { | |
792 | for item in list { | |
793 | if let Some(filename) = item.as_str() { | |
794 | result.push(filename.to_owned()); | |
795 | } | |
796 | } | |
797 | } | |
798 | ||
6899dbfb | 799 | strip_server_file_expenstions(result) |
08dc340a DM |
800 | } |
801 | ||
49811347 DM |
802 | fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
803 | ||
804 | let mut result = vec![]; | |
805 | ||
806 | let mut size = 64; | |
807 | loop { | |
808 | result.push(size.to_string()); | |
809 | size = size * 2; | |
810 | if size > 4096 { break; } | |
811 | } | |
812 | ||
813 | result | |
814 | } | |
815 | ||
826f309b | 816 | fn get_encryption_key_password() -> Result<Vec<u8>, Error> { |
ff5d3707 | 817 | |
f2401311 DM |
818 | // fixme: implement other input methods |
819 | ||
820 | use std::env::VarError::*; | |
821 | match std::env::var("PBS_ENCRYPTION_PASSWORD") { | |
826f309b | 822 | Ok(p) => return Ok(p.as_bytes().to_vec()), |
f2401311 DM |
823 | Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"), |
824 | Err(NotPresent) => { | |
825 | // Try another method | |
826 | } | |
827 | } | |
828 | ||
829 | // If we're on a TTY, query the user for a password | |
830 | if crate::tools::tty::stdin_isatty() { | |
826f309b | 831 | return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?); |
f2401311 DM |
832 | } |
833 | ||
834 | bail!("no password input mechanism available"); | |
835 | } | |
836 | ||
ac716234 DM |
837 | fn key_create( |
838 | param: Value, | |
839 | _info: &ApiMethod, | |
840 | _rpcenv: &mut dyn RpcEnvironment, | |
841 | ) -> Result<Value, Error> { | |
842 | ||
9b06db45 DM |
843 | let path = tools::required_string_param(¶m, "path")?; |
844 | let path = PathBuf::from(path); | |
ac716234 | 845 | |
181f097a | 846 | let kdf = param["kdf"].as_str().unwrap_or("scrypt"); |
ac716234 DM |
847 | |
848 | let key = proxmox::sys::linux::random_data(32)?; | |
849 | ||
181f097a DM |
850 | if kdf == "scrypt" { |
851 | // always read passphrase from tty | |
852 | if !crate::tools::tty::stdin_isatty() { | |
853 | bail!("unable to read passphrase - no tty"); | |
854 | } | |
ac716234 | 855 | |
181f097a DM |
856 | let password = crate::tools::tty::read_password("Encryption Key Password: ")?; |
857 | ||
ab44acff | 858 | let key_config = encrypt_key_with_passphrase(&key, &password)?; |
37c5a175 | 859 | |
ab44acff | 860 | store_key_config(&path, false, key_config)?; |
181f097a DM |
861 | |
862 | Ok(Value::Null) | |
863 | } else if kdf == "none" { | |
864 | let created = Local.timestamp(Local::now().timestamp(), 0); | |
865 | ||
866 | store_key_config(&path, false, KeyConfig { | |
867 | kdf: None, | |
868 | created, | |
ab44acff | 869 | modified: created, |
181f097a DM |
870 | data: key, |
871 | })?; | |
872 | ||
873 | Ok(Value::Null) | |
874 | } else { | |
875 | unreachable!(); | |
876 | } | |
ac716234 DM |
877 | } |
878 | ||
9f46c7de DM |
879 | fn master_pubkey_path() -> Result<PathBuf, Error> { |
880 | let base = BaseDirectories::with_prefix("proxmox-backup")?; | |
881 | ||
882 | // usually $HOME/.config/proxmox-backup/master-public.pem | |
883 | let path = base.place_config_file("master-public.pem")?; | |
884 | ||
885 | Ok(path) | |
886 | } | |
887 | ||
3ea8bfc9 DM |
888 | fn key_import_master_pubkey( |
889 | param: Value, | |
890 | _info: &ApiMethod, | |
891 | _rpcenv: &mut dyn RpcEnvironment, | |
892 | ) -> Result<Value, Error> { | |
893 | ||
894 | let path = tools::required_string_param(¶m, "path")?; | |
895 | let path = PathBuf::from(path); | |
896 | ||
897 | let pem_data = proxmox_backup::tools::file_get_contents(&path)?; | |
898 | ||
899 | if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) { | |
900 | bail!("Unable to decode PEM data - {}", err); | |
901 | } | |
902 | ||
9f46c7de | 903 | let target_path = master_pubkey_path()?; |
3ea8bfc9 DM |
904 | |
905 | proxmox_backup::tools::file_set_contents(&target_path, &pem_data, None)?; | |
906 | ||
907 | println!("Imported public master key to {:?}", target_path); | |
908 | ||
909 | Ok(Value::Null) | |
910 | } | |
911 | ||
37c5a175 DM |
912 | fn key_create_master_key( |
913 | _param: Value, | |
914 | _info: &ApiMethod, | |
915 | _rpcenv: &mut dyn RpcEnvironment, | |
916 | ) -> Result<Value, Error> { | |
917 | ||
918 | // we need a TTY to query the new password | |
919 | if !crate::tools::tty::stdin_isatty() { | |
920 | bail!("unable to create master key - no tty"); | |
921 | } | |
922 | ||
923 | let rsa = openssl::rsa::Rsa::generate(4096)?; | |
924 | let pkey = openssl::pkey::PKey::from_rsa(rsa)?; | |
925 | ||
926 | let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?; | |
927 | let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?; | |
928 | ||
929 | if new_pw != verify_pw { | |
930 | bail!("Password verification fail!"); | |
931 | } | |
932 | ||
933 | if new_pw.len() < 5 { | |
934 | bail!("Password is too short!"); | |
935 | } | |
936 | ||
937 | let pub_key: Vec<u8> = pkey.public_key_to_pem()?; | |
938 | let filename_pub = "master-public.pem"; | |
939 | println!("Writing public master key to {}", filename_pub); | |
940 | proxmox_backup::tools::file_set_contents(filename_pub, pub_key.as_slice(), None)?; | |
941 | ||
942 | let cipher = openssl::symm::Cipher::aes_256_cbc(); | |
943 | let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?; | |
944 | ||
945 | let filename_priv = "master-private.pem"; | |
946 | println!("Writing private master key to {}", filename_priv); | |
947 | proxmox_backup::tools::file_set_contents(filename_priv, priv_key.as_slice(), None)?; | |
948 | ||
949 | Ok(Value::Null) | |
950 | } | |
ac716234 DM |
951 | |
952 | fn key_change_passphrase( | |
953 | param: Value, | |
954 | _info: &ApiMethod, | |
955 | _rpcenv: &mut dyn RpcEnvironment, | |
956 | ) -> Result<Value, Error> { | |
957 | ||
9b06db45 DM |
958 | let path = tools::required_string_param(¶m, "path")?; |
959 | let path = PathBuf::from(path); | |
ac716234 | 960 | |
181f097a DM |
961 | let kdf = param["kdf"].as_str().unwrap_or("scrypt"); |
962 | ||
ac716234 DM |
963 | // we need a TTY to query the new password |
964 | if !crate::tools::tty::stdin_isatty() { | |
965 | bail!("unable to change passphrase - no tty"); | |
966 | } | |
967 | ||
ab44acff | 968 | let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?; |
ac716234 | 969 | |
181f097a | 970 | if kdf == "scrypt" { |
ac716234 | 971 | |
181f097a DM |
972 | let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?; |
973 | let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?; | |
ac716234 | 974 | |
181f097a DM |
975 | if new_pw != verify_pw { |
976 | bail!("Password verification fail!"); | |
977 | } | |
978 | ||
979 | if new_pw.len() < 5 { | |
980 | bail!("Password is too short!"); | |
981 | } | |
ac716234 | 982 | |
ab44acff DM |
983 | let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?; |
984 | new_key_config.created = created; // keep original value | |
985 | ||
986 | store_key_config(&path, true, new_key_config)?; | |
ac716234 | 987 | |
181f097a DM |
988 | Ok(Value::Null) |
989 | } else if kdf == "none" { | |
ab44acff | 990 | let modified = Local.timestamp(Local::now().timestamp(), 0); |
181f097a DM |
991 | |
992 | store_key_config(&path, true, KeyConfig { | |
993 | kdf: None, | |
ab44acff DM |
994 | created, // keep original value |
995 | modified, | |
6d0983db | 996 | data: key.to_vec(), |
181f097a DM |
997 | })?; |
998 | ||
999 | Ok(Value::Null) | |
1000 | } else { | |
1001 | unreachable!(); | |
1002 | } | |
f2401311 DM |
1003 | } |
1004 | ||
1005 | fn key_mgmt_cli() -> CliCommandMap { | |
1006 | ||
181f097a DM |
1007 | let kdf_schema: Arc<Schema> = Arc::new( |
1008 | StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.") | |
1009 | .format(Arc::new(ApiStringFormat::Enum(&["scrypt", "none"]))) | |
1010 | .default("scrypt") | |
1011 | .into() | |
1012 | ); | |
1013 | ||
f2401311 DM |
1014 | let key_create_cmd_def = CliCommand::new( |
1015 | ApiMethod::new( | |
1016 | key_create, | |
1017 | ObjectSchema::new("Create a new encryption key.") | |
9b06db45 | 1018 | .required("path", StringSchema::new("File system path.")) |
181f097a | 1019 | .optional("kdf", kdf_schema.clone()) |
f2401311 | 1020 | )) |
9b06db45 DM |
1021 | .arg_param(vec!["path"]) |
1022 | .completion_cb("path", tools::complete_file_name); | |
f2401311 | 1023 | |
ac716234 DM |
1024 | let key_change_passphrase_cmd_def = CliCommand::new( |
1025 | ApiMethod::new( | |
1026 | key_change_passphrase, | |
1027 | ObjectSchema::new("Change the passphrase required to decrypt the key.") | |
9b06db45 | 1028 | .required("path", StringSchema::new("File system path.")) |
181f097a | 1029 | .optional("kdf", kdf_schema.clone()) |
9b06db45 DM |
1030 | )) |
1031 | .arg_param(vec!["path"]) | |
1032 | .completion_cb("path", tools::complete_file_name); | |
ac716234 | 1033 | |
37c5a175 DM |
1034 | let key_create_master_key_cmd_def = CliCommand::new( |
1035 | ApiMethod::new( | |
1036 | key_create_master_key, | |
1037 | ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.") | |
1038 | )); | |
1039 | ||
3ea8bfc9 DM |
1040 | let key_import_master_pubkey_cmd_def = CliCommand::new( |
1041 | ApiMethod::new( | |
1042 | key_import_master_pubkey, | |
1043 | ObjectSchema::new("Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.") | |
1044 | .required("path", StringSchema::new("File system path.")) | |
1045 | )) | |
1046 | .arg_param(vec!["path"]) | |
1047 | .completion_cb("path", tools::complete_file_name); | |
1048 | ||
f2401311 | 1049 | let cmd_def = CliCommandMap::new() |
ac716234 | 1050 | .insert("create".to_owned(), key_create_cmd_def.into()) |
37c5a175 | 1051 | .insert("create-master-key".to_owned(), key_create_master_key_cmd_def.into()) |
3ea8bfc9 | 1052 | .insert("import-master-pubkey".to_owned(), key_import_master_pubkey_cmd_def.into()) |
ac716234 | 1053 | .insert("change-passphrase".to_owned(), key_change_passphrase_cmd_def.into()); |
f2401311 DM |
1054 | |
1055 | cmd_def | |
1056 | } | |
1057 | ||
1058 | ||
1059 | fn main() { | |
33d64b81 | 1060 | |
25f1650b DM |
1061 | let backup_source_schema: Arc<Schema> = Arc::new( |
1062 | StringSchema::new("Backup source specification ([<label>:<path>]).") | |
1063 | .format(Arc::new(ApiStringFormat::Pattern(&BACKUPSPEC_REGEX))) | |
1064 | .into() | |
1065 | ); | |
1066 | ||
597a9203 | 1067 | let backup_cmd_def = CliCommand::new( |
ff5d3707 | 1068 | ApiMethod::new( |
bcd879cf | 1069 | create_backup, |
597a9203 | 1070 | ObjectSchema::new("Create (host) backup.") |
f2401311 | 1071 | .required("repository", REPO_URL_SCHEMA.clone()) |
ae0be2dd DM |
1072 | .required( |
1073 | "backupspec", | |
1074 | ArraySchema::new( | |
74cdb521 | 1075 | "List of backup source specifications ([<label.ext>:<path>] ...)", |
25f1650b | 1076 | backup_source_schema, |
ae0be2dd DM |
1077 | ).min_length(1) |
1078 | ) | |
6d0983db DM |
1079 | .optional( |
1080 | "keyfile", | |
1081 | StringSchema::new("Path to encryption key. All data will be encrypted using this key.")) | |
219ef0e6 DM |
1082 | .optional( |
1083 | "verbose", | |
1084 | BooleanSchema::new("Verbose output.").default(false)) | |
fba30411 DM |
1085 | .optional( |
1086 | "host-id", | |
1087 | StringSchema::new("Use specified ID for the backup group name ('host/<id>'). The default is the system hostname.")) | |
2d9d143a DM |
1088 | .optional( |
1089 | "chunk-size", | |
1090 | IntegerSchema::new("Chunk size in KB. Must be a power of 2.") | |
1091 | .minimum(64) | |
1092 | .maximum(4096) | |
1093 | .default(4096) | |
1094 | ) | |
ff5d3707 | 1095 | )) |
ae0be2dd | 1096 | .arg_param(vec!["repository", "backupspec"]) |
d0a03d40 | 1097 | .completion_cb("repository", complete_repository) |
49811347 | 1098 | .completion_cb("backupspec", complete_backup_source) |
6d0983db | 1099 | .completion_cb("keyfile", tools::complete_file_name) |
49811347 | 1100 | .completion_cb("chunk-size", complete_chunk_size); |
f8838fe9 | 1101 | |
41c039e1 DM |
1102 | let list_cmd_def = CliCommand::new( |
1103 | ApiMethod::new( | |
812c6f87 DM |
1104 | list_backup_groups, |
1105 | ObjectSchema::new("List backup groups.") | |
f2401311 | 1106 | .required("repository", REPO_URL_SCHEMA.clone()) |
41c039e1 | 1107 | )) |
d0a03d40 DM |
1108 | .arg_param(vec!["repository"]) |
1109 | .completion_cb("repository", complete_repository); | |
41c039e1 | 1110 | |
184f17af DM |
1111 | let snapshots_cmd_def = CliCommand::new( |
1112 | ApiMethod::new( | |
1113 | list_snapshots, | |
1114 | ObjectSchema::new("List backup snapshots.") | |
f2401311 | 1115 | .required("repository", REPO_URL_SCHEMA.clone()) |
184f17af DM |
1116 | .required("group", StringSchema::new("Backup group.")) |
1117 | )) | |
d0a03d40 | 1118 | .arg_param(vec!["repository", "group"]) |
024f11bb | 1119 | .completion_cb("group", complete_backup_group) |
d0a03d40 | 1120 | .completion_cb("repository", complete_repository); |
184f17af | 1121 | |
6f62c924 DM |
1122 | let forget_cmd_def = CliCommand::new( |
1123 | ApiMethod::new( | |
1124 | forget_snapshots, | |
1125 | ObjectSchema::new("Forget (remove) backup snapshots.") | |
f2401311 | 1126 | .required("repository", REPO_URL_SCHEMA.clone()) |
6f62c924 DM |
1127 | .required("snapshot", StringSchema::new("Snapshot path.")) |
1128 | )) | |
d0a03d40 | 1129 | .arg_param(vec!["repository", "snapshot"]) |
b2388518 DM |
1130 | .completion_cb("repository", complete_repository) |
1131 | .completion_cb("snapshot", complete_group_or_snapshot); | |
6f62c924 | 1132 | |
8cc0d6af DM |
1133 | let garbage_collect_cmd_def = CliCommand::new( |
1134 | ApiMethod::new( | |
1135 | start_garbage_collection, | |
1136 | ObjectSchema::new("Start garbage collection for a specific repository.") | |
f2401311 | 1137 | .required("repository", REPO_URL_SCHEMA.clone()) |
8cc0d6af | 1138 | )) |
d0a03d40 DM |
1139 | .arg_param(vec!["repository"]) |
1140 | .completion_cb("repository", complete_repository); | |
8cc0d6af | 1141 | |
9f912493 DM |
1142 | let restore_cmd_def = CliCommand::new( |
1143 | ApiMethod::new( | |
1144 | restore, | |
1145 | ObjectSchema::new("Restore backup repository.") | |
f2401311 | 1146 | .required("repository", REPO_URL_SCHEMA.clone()) |
d5c34d98 DM |
1147 | .required("snapshot", StringSchema::new("Group/Snapshot path.")) |
1148 | .required("archive-name", StringSchema::new("Backup archive name.")) | |
9f912493 DM |
1149 | .required("target", StringSchema::new("Target directory path.")) |
1150 | )) | |
d0a03d40 | 1151 | .arg_param(vec!["repository", "snapshot", "archive-name", "target"]) |
b2388518 | 1152 | .completion_cb("repository", complete_repository) |
08dc340a DM |
1153 | .completion_cb("snapshot", complete_group_or_snapshot) |
1154 | .completion_cb("archive-name", complete_archive_name) | |
1155 | .completion_cb("target", tools::complete_file_name); | |
9f912493 | 1156 | |
83b7db02 DM |
1157 | let prune_cmd_def = CliCommand::new( |
1158 | ApiMethod::new( | |
1159 | prune, | |
1160 | proxmox_backup::api2::admin::datastore::add_common_prune_prameters( | |
1161 | ObjectSchema::new("Prune backup repository.") | |
f2401311 | 1162 | .required("repository", REPO_URL_SCHEMA.clone()) |
83b7db02 DM |
1163 | ) |
1164 | )) | |
d0a03d40 DM |
1165 | .arg_param(vec!["repository"]) |
1166 | .completion_cb("repository", complete_repository); | |
9f912493 | 1167 | |
41c039e1 | 1168 | let cmd_def = CliCommandMap::new() |
597a9203 | 1169 | .insert("backup".to_owned(), backup_cmd_def.into()) |
6f62c924 | 1170 | .insert("forget".to_owned(), forget_cmd_def.into()) |
8cc0d6af | 1171 | .insert("garbage-collect".to_owned(), garbage_collect_cmd_def.into()) |
83b7db02 | 1172 | .insert("list".to_owned(), list_cmd_def.into()) |
184f17af | 1173 | .insert("prune".to_owned(), prune_cmd_def.into()) |
9f912493 | 1174 | .insert("restore".to_owned(), restore_cmd_def.into()) |
f2401311 DM |
1175 | .insert("snapshots".to_owned(), snapshots_cmd_def.into()) |
1176 | .insert("key".to_owned(), key_mgmt_cli().into()); | |
a914a774 | 1177 | |
5a2df000 DM |
1178 | hyper::rt::run(futures::future::lazy(move || { |
1179 | run_cli_command(cmd_def.into()); | |
1180 | Ok(()) | |
1181 | })); | |
496a6784 | 1182 | |
ff5d3707 | 1183 | } |