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