]>
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 | ||
f8100e96 | 890 | if server_archive_name.ends_with(".blob") { |
0d986280 DM |
891 | let mut tmpfile = client.download(&server_archive_name, tmpfile).wait()?; |
892 | tmpfile.seek(SeekFrom::Start(0))?; | |
893 | let mut reader = DataBlobReader::new(tmpfile, crypt_config)?; | |
f8100e96 | 894 | |
bf125261 | 895 | if let Some(target) = target { |
0d986280 DM |
896 | let mut writer = std::fs::OpenOptions::new() |
897 | .write(true) | |
898 | .create(true) | |
899 | .create_new(true) | |
900 | .open(target) | |
901 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?; | |
902 | std::io::copy(&mut reader, &mut writer)?; | |
bf125261 DM |
903 | } else { |
904 | let stdout = std::io::stdout(); | |
905 | let mut writer = stdout.lock(); | |
0d986280 | 906 | std::io::copy(&mut reader, &mut writer) |
bf125261 DM |
907 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; |
908 | } | |
f8100e96 DM |
909 | |
910 | } else if server_archive_name.ends_with(".didx") { | |
afb4cd28 | 911 | let tmpfile = client.download(&server_archive_name, tmpfile).wait()?; |
86eda3eb | 912 | |
afb4cd28 DM |
913 | let index = DynamicIndexReader::new(tmpfile) |
914 | .map_err(|err| format_err!("unable to read dynamic index '{}' - {}", archive_name, err))?; | |
86eda3eb | 915 | |
f4bf7dfc DM |
916 | let most_used = index.find_most_used_chunks(8); |
917 | ||
918 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
919 | ||
afb4cd28 | 920 | let mut reader = BufferedDynamicReader::new(index, chunk_reader); |
86eda3eb | 921 | |
bf125261 | 922 | if let Some(target) = target { |
86eda3eb | 923 | |
47651f95 | 924 | let feature_flags = pxar::flags::DEFAULT; |
bf125261 DM |
925 | let mut decoder = pxar::SequentialDecoder::new(&mut reader, feature_flags, |path| { |
926 | if verbose { | |
927 | println!("{:?}", path); | |
928 | } | |
929 | Ok(()) | |
930 | }); | |
6a879109 CE |
931 | decoder.set_allow_existing_dirs(allow_existing_dirs); |
932 | ||
bf125261 | 933 | |
fa7e957c | 934 | decoder.restore(Path::new(target), &Vec::new())?; |
bf125261 DM |
935 | } else { |
936 | let stdout = std::io::stdout(); | |
937 | let mut writer = stdout.lock(); | |
afb4cd28 | 938 | |
bf125261 DM |
939 | std::io::copy(&mut reader, &mut writer) |
940 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
941 | } | |
afb4cd28 DM |
942 | } else if server_archive_name.ends_with(".fidx") { |
943 | let tmpfile = client.download(&server_archive_name, tmpfile).wait()?; | |
944 | ||
945 | let index = FixedIndexReader::new(tmpfile) | |
946 | .map_err(|err| format_err!("unable to read fixed index '{}' - {}", archive_name, err))?; | |
7dcbe051 | 947 | |
f4bf7dfc DM |
948 | let most_used = index.find_most_used_chunks(8); |
949 | ||
950 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used); | |
951 | ||
afb4cd28 DM |
952 | let mut reader = BufferedFixedReader::new(index, chunk_reader); |
953 | ||
bf125261 DM |
954 | if let Some(target) = target { |
955 | let mut writer = std::fs::OpenOptions::new() | |
956 | .write(true) | |
957 | .create(true) | |
958 | .create_new(true) | |
959 | .open(target) | |
960 | .map_err(|err| format_err!("unable to create target file {:?} - {}", target, err))?; | |
961 | ||
962 | std::io::copy(&mut reader, &mut writer) | |
963 | .map_err(|err| format_err!("unable to store data - {}", err))?; | |
964 | } else { | |
965 | let stdout = std::io::stdout(); | |
966 | let mut writer = stdout.lock(); | |
afb4cd28 | 967 | |
bf125261 DM |
968 | std::io::copy(&mut reader, &mut writer) |
969 | .map_err(|err| format_err!("unable to pipe data - {}", err))?; | |
970 | } | |
45db6f89 | 971 | } else { |
f8100e96 | 972 | bail!("unknown archive file extension (expected .pxar of .img)"); |
3031e44c | 973 | } |
fef44d4f DM |
974 | |
975 | Ok(Value::Null) | |
45db6f89 DM |
976 | } |
977 | ||
ec34f7eb DM |
978 | fn upload_log( |
979 | param: Value, | |
980 | _info: &ApiMethod, | |
981 | _rpcenv: &mut dyn RpcEnvironment, | |
982 | ) -> Result<Value, Error> { | |
983 | ||
984 | let logfile = tools::required_string_param(¶m, "logfile")?; | |
985 | let repo = extract_repository_from_value(¶m)?; | |
986 | ||
987 | let snapshot = tools::required_string_param(¶m, "snapshot")?; | |
988 | let snapshot = BackupDir::parse(snapshot)?; | |
989 | ||
990 | let mut client = HttpClient::new(repo.host(), repo.user())?; | |
991 | ||
992 | let keyfile = param["keyfile"].as_str().map(|p| PathBuf::from(p)); | |
993 | ||
994 | let crypt_config = match keyfile { | |
995 | None => None, | |
996 | Some(path) => { | |
997 | let (key, _created) = load_and_decrtypt_key(&path, get_encryption_key_password)?; | |
998 | let crypt_config = CryptConfig::new(key)?; | |
9025312a | 999 | Some(Arc::new(crypt_config)) |
ec34f7eb DM |
1000 | } |
1001 | }; | |
1002 | ||
e18a6c9e | 1003 | let data = file_get_contents(logfile)?; |
ec34f7eb | 1004 | |
9025312a | 1005 | let blob = DataBlob::encode(&data, crypt_config, true)?; |
ec34f7eb DM |
1006 | |
1007 | let raw_data = blob.into_inner(); | |
1008 | ||
1009 | let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store()); | |
1010 | ||
1011 | let args = json!({ | |
1012 | "backup-type": snapshot.group().backup_type(), | |
1013 | "backup-id": snapshot.group().backup_id(), | |
1014 | "backup-time": snapshot.backup_time().timestamp(), | |
1015 | }); | |
1016 | ||
1017 | let body = hyper::Body::from(raw_data); | |
1018 | ||
1019 | let result = client.upload("application/octet-stream", body, &path, Some(args)).wait()?; | |
1020 | ||
1021 | Ok(result) | |
1022 | } | |
1023 | ||
83b7db02 | 1024 | fn prune( |
ea7a7ef2 | 1025 | mut param: Value, |
83b7db02 | 1026 | _info: &ApiMethod, |
dd5495d6 | 1027 | _rpcenv: &mut dyn RpcEnvironment, |
83b7db02 DM |
1028 | ) -> Result<Value, Error> { |
1029 | ||
2665cef7 | 1030 | let repo = extract_repository_from_value(¶m)?; |
83b7db02 | 1031 | |
45cdce06 | 1032 | let mut client = HttpClient::new(repo.host(), repo.user())?; |
83b7db02 | 1033 | |
d0a03d40 | 1034 | let path = format!("api2/json/admin/datastore/{}/prune", repo.store()); |
83b7db02 | 1035 | |
9fdc3ef4 DM |
1036 | let group = tools::required_string_param(¶m, "group")?; |
1037 | let group = BackupGroup::parse(group)?; | |
1038 | ||
ea7a7ef2 DM |
1039 | param.as_object_mut().unwrap().remove("repository"); |
1040 | param.as_object_mut().unwrap().remove("group"); | |
1041 | ||
1042 | param["backup-type"] = group.backup_type().into(); | |
1043 | param["backup-id"] = group.backup_id().into(); | |
83b7db02 | 1044 | |
43a406fd | 1045 | let _result = client.post(&path, Some(param)).wait()?; |
83b7db02 | 1046 | |
d0a03d40 DM |
1047 | record_repository(&repo); |
1048 | ||
43a406fd | 1049 | Ok(Value::Null) |
83b7db02 DM |
1050 | } |
1051 | ||
34a816cc DM |
1052 | fn status( |
1053 | param: Value, | |
1054 | _info: &ApiMethod, | |
1055 | _rpcenv: &mut dyn RpcEnvironment, | |
1056 | ) -> Result<Value, Error> { | |
1057 | ||
1058 | let repo = extract_repository_from_value(¶m)?; | |
1059 | ||
1060 | let output_format = param["output-format"].as_str().unwrap_or("text").to_owned(); | |
1061 | ||
1062 | let client = HttpClient::new(repo.host(), repo.user())?; | |
1063 | ||
1064 | let path = format!("api2/json/admin/datastore/{}/status", repo.store()); | |
1065 | ||
1066 | let result = client.get(&path, None).wait()?; | |
1067 | let data = &result["data"]; | |
1068 | ||
1069 | record_repository(&repo); | |
1070 | ||
1071 | if output_format == "text" { | |
1072 | let total = data["total"].as_u64().unwrap(); | |
1073 | let used = data["used"].as_u64().unwrap(); | |
1074 | let avail = data["avail"].as_u64().unwrap(); | |
1075 | let roundup = total/200; | |
1076 | ||
1077 | println!( | |
1078 | "total: {} used: {} ({} %) available: {}", | |
1079 | total, | |
1080 | used, | |
1081 | ((used+roundup)*100)/total, | |
1082 | avail, | |
1083 | ); | |
1084 | } else { | |
f6ede796 | 1085 | format_and_print_result(data, &output_format); |
34a816cc DM |
1086 | } |
1087 | ||
1088 | Ok(Value::Null) | |
1089 | } | |
1090 | ||
5a2df000 | 1091 | // like get, but simply ignore errors and return Null instead |
b2388518 | 1092 | fn try_get(repo: &BackupRepository, url: &str) -> Value { |
024f11bb | 1093 | |
45cdce06 DM |
1094 | let client = match HttpClient::new(repo.host(), repo.user()) { |
1095 | Ok(v) => v, | |
1096 | _ => return Value::Null, | |
1097 | }; | |
b2388518 | 1098 | |
9e391bb7 | 1099 | let mut resp = match client.get(url, None).wait() { |
b2388518 DM |
1100 | Ok(v) => v, |
1101 | _ => return Value::Null, | |
1102 | }; | |
1103 | ||
1104 | if let Some(map) = resp.as_object_mut() { | |
1105 | if let Some(data) = map.remove("data") { | |
1106 | return data; | |
1107 | } | |
1108 | } | |
1109 | Value::Null | |
1110 | } | |
1111 | ||
b2388518 | 1112 | fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
024f11bb | 1113 | |
b2388518 DM |
1114 | let mut result = vec![]; |
1115 | ||
2665cef7 | 1116 | let repo = match extract_repository_from_map(param) { |
b2388518 | 1117 | Some(v) => v, |
024f11bb DM |
1118 | _ => return result, |
1119 | }; | |
1120 | ||
b2388518 DM |
1121 | let path = format!("api2/json/admin/datastore/{}/groups", repo.store()); |
1122 | ||
1123 | let data = try_get(&repo, &path); | |
1124 | ||
1125 | if let Some(list) = data.as_array() { | |
024f11bb | 1126 | for item in list { |
98f0b972 DM |
1127 | if let (Some(backup_id), Some(backup_type)) = |
1128 | (item["backup-id"].as_str(), item["backup-type"].as_str()) | |
1129 | { | |
1130 | result.push(format!("{}/{}", backup_type, backup_id)); | |
024f11bb DM |
1131 | } |
1132 | } | |
1133 | } | |
1134 | ||
1135 | result | |
1136 | } | |
1137 | ||
b2388518 DM |
1138 | fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
1139 | ||
b2388518 DM |
1140 | if arg.matches('/').count() < 2 { |
1141 | let groups = complete_backup_group(arg, param); | |
543a260f | 1142 | let mut result = vec![]; |
b2388518 DM |
1143 | for group in groups { |
1144 | result.push(group.to_string()); | |
1145 | result.push(format!("{}/", group)); | |
1146 | } | |
1147 | return result; | |
1148 | } | |
1149 | ||
543a260f DM |
1150 | complete_backup_snapshot(arg, param) |
1151 | } | |
b2388518 | 1152 | |
3fb53e07 | 1153 | fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
543a260f DM |
1154 | |
1155 | let mut result = vec![]; | |
1156 | ||
1157 | let repo = match extract_repository_from_map(param) { | |
1158 | Some(v) => v, | |
1159 | _ => return result, | |
1160 | }; | |
1161 | ||
1162 | let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store()); | |
b2388518 DM |
1163 | |
1164 | let data = try_get(&repo, &path); | |
1165 | ||
1166 | if let Some(list) = data.as_array() { | |
1167 | for item in list { | |
1168 | if let (Some(backup_id), Some(backup_type), Some(backup_time)) = | |
1169 | (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64()) | |
1170 | { | |
1171 | let snapshot = BackupDir::new(backup_type, backup_id, backup_time); | |
1172 | result.push(snapshot.relative_path().to_str().unwrap().to_owned()); | |
1173 | } | |
1174 | } | |
1175 | } | |
1176 | ||
1177 | result | |
1178 | } | |
1179 | ||
45db6f89 | 1180 | fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> { |
08dc340a DM |
1181 | |
1182 | let mut result = vec![]; | |
1183 | ||
2665cef7 | 1184 | let repo = match extract_repository_from_map(param) { |
08dc340a DM |
1185 | Some(v) => v, |
1186 | _ => return result, | |
1187 | }; | |
1188 | ||
1189 | let snapshot = match param.get("snapshot") { | |
1190 | Some(path) => { | |
1191 | match BackupDir::parse(path) { | |
1192 | Ok(v) => v, | |
1193 | _ => return result, | |
1194 | } | |
1195 | } | |
1196 | _ => return result, | |
1197 | }; | |
1198 | ||
1199 | let query = tools::json_object_to_query(json!({ | |
1200 | "backup-type": snapshot.group().backup_type(), | |
1201 | "backup-id": snapshot.group().backup_id(), | |
1202 | "backup-time": snapshot.backup_time().timestamp(), | |
1203 | })).unwrap(); | |
1204 | ||
1205 | let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query); | |
1206 | ||
1207 | let data = try_get(&repo, &path); | |
1208 | ||
1209 | if let Some(list) = data.as_array() { | |
1210 | for item in list { | |
c4f025eb | 1211 | if let Some(filename) = item["filename"].as_str() { |
08dc340a DM |
1212 | result.push(filename.to_owned()); |
1213 | } | |
1214 | } | |
1215 | } | |
1216 | ||
45db6f89 DM |
1217 | result |
1218 | } | |
1219 | ||
1220 | fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> { | |
1221 | ||
52c171e4 DM |
1222 | complete_server_file_name(arg, param) |
1223 | .iter().map(|v| strip_server_file_expenstion(&v)).collect() | |
08dc340a DM |
1224 | } |
1225 | ||
49811347 DM |
1226 | fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> { |
1227 | ||
1228 | let mut result = vec![]; | |
1229 | ||
1230 | let mut size = 64; | |
1231 | loop { | |
1232 | result.push(size.to_string()); | |
1233 | size = size * 2; | |
1234 | if size > 4096 { break; } | |
1235 | } | |
1236 | ||
1237 | result | |
1238 | } | |
1239 | ||
826f309b | 1240 | fn get_encryption_key_password() -> Result<Vec<u8>, Error> { |
ff5d3707 | 1241 | |
f2401311 DM |
1242 | // fixme: implement other input methods |
1243 | ||
1244 | use std::env::VarError::*; | |
1245 | match std::env::var("PBS_ENCRYPTION_PASSWORD") { | |
826f309b | 1246 | Ok(p) => return Ok(p.as_bytes().to_vec()), |
f2401311 DM |
1247 | Err(NotUnicode(_)) => bail!("PBS_ENCRYPTION_PASSWORD contains bad characters"), |
1248 | Err(NotPresent) => { | |
1249 | // Try another method | |
1250 | } | |
1251 | } | |
1252 | ||
1253 | // If we're on a TTY, query the user for a password | |
1254 | if crate::tools::tty::stdin_isatty() { | |
826f309b | 1255 | return Ok(crate::tools::tty::read_password("Encryption Key Password: ")?); |
f2401311 DM |
1256 | } |
1257 | ||
1258 | bail!("no password input mechanism available"); | |
1259 | } | |
1260 | ||
ac716234 DM |
1261 | fn key_create( |
1262 | param: Value, | |
1263 | _info: &ApiMethod, | |
1264 | _rpcenv: &mut dyn RpcEnvironment, | |
1265 | ) -> Result<Value, Error> { | |
1266 | ||
9b06db45 DM |
1267 | let path = tools::required_string_param(¶m, "path")?; |
1268 | let path = PathBuf::from(path); | |
ac716234 | 1269 | |
181f097a | 1270 | let kdf = param["kdf"].as_str().unwrap_or("scrypt"); |
ac716234 DM |
1271 | |
1272 | let key = proxmox::sys::linux::random_data(32)?; | |
1273 | ||
181f097a DM |
1274 | if kdf == "scrypt" { |
1275 | // always read passphrase from tty | |
1276 | if !crate::tools::tty::stdin_isatty() { | |
1277 | bail!("unable to read passphrase - no tty"); | |
1278 | } | |
ac716234 | 1279 | |
181f097a DM |
1280 | let password = crate::tools::tty::read_password("Encryption Key Password: ")?; |
1281 | ||
ab44acff | 1282 | let key_config = encrypt_key_with_passphrase(&key, &password)?; |
37c5a175 | 1283 | |
ab44acff | 1284 | store_key_config(&path, false, key_config)?; |
181f097a DM |
1285 | |
1286 | Ok(Value::Null) | |
1287 | } else if kdf == "none" { | |
1288 | let created = Local.timestamp(Local::now().timestamp(), 0); | |
1289 | ||
1290 | store_key_config(&path, false, KeyConfig { | |
1291 | kdf: None, | |
1292 | created, | |
ab44acff | 1293 | modified: created, |
181f097a DM |
1294 | data: key, |
1295 | })?; | |
1296 | ||
1297 | Ok(Value::Null) | |
1298 | } else { | |
1299 | unreachable!(); | |
1300 | } | |
ac716234 DM |
1301 | } |
1302 | ||
9f46c7de DM |
1303 | fn master_pubkey_path() -> Result<PathBuf, Error> { |
1304 | let base = BaseDirectories::with_prefix("proxmox-backup")?; | |
1305 | ||
1306 | // usually $HOME/.config/proxmox-backup/master-public.pem | |
1307 | let path = base.place_config_file("master-public.pem")?; | |
1308 | ||
1309 | Ok(path) | |
1310 | } | |
1311 | ||
3ea8bfc9 DM |
1312 | fn key_import_master_pubkey( |
1313 | param: Value, | |
1314 | _info: &ApiMethod, | |
1315 | _rpcenv: &mut dyn RpcEnvironment, | |
1316 | ) -> Result<Value, Error> { | |
1317 | ||
1318 | let path = tools::required_string_param(¶m, "path")?; | |
1319 | let path = PathBuf::from(path); | |
1320 | ||
e18a6c9e | 1321 | let pem_data = file_get_contents(&path)?; |
3ea8bfc9 DM |
1322 | |
1323 | if let Err(err) = openssl::pkey::PKey::public_key_from_pem(&pem_data) { | |
1324 | bail!("Unable to decode PEM data - {}", err); | |
1325 | } | |
1326 | ||
9f46c7de | 1327 | let target_path = master_pubkey_path()?; |
3ea8bfc9 | 1328 | |
e18a6c9e | 1329 | file_set_contents(&target_path, &pem_data, None)?; |
3ea8bfc9 DM |
1330 | |
1331 | println!("Imported public master key to {:?}", target_path); | |
1332 | ||
1333 | Ok(Value::Null) | |
1334 | } | |
1335 | ||
37c5a175 DM |
1336 | fn key_create_master_key( |
1337 | _param: Value, | |
1338 | _info: &ApiMethod, | |
1339 | _rpcenv: &mut dyn RpcEnvironment, | |
1340 | ) -> Result<Value, Error> { | |
1341 | ||
1342 | // we need a TTY to query the new password | |
1343 | if !crate::tools::tty::stdin_isatty() { | |
1344 | bail!("unable to create master key - no tty"); | |
1345 | } | |
1346 | ||
1347 | let rsa = openssl::rsa::Rsa::generate(4096)?; | |
1348 | let pkey = openssl::pkey::PKey::from_rsa(rsa)?; | |
1349 | ||
1350 | let new_pw = String::from_utf8(crate::tools::tty::read_password("Master Key Password: ")?)?; | |
1351 | let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?; | |
1352 | ||
1353 | if new_pw != verify_pw { | |
1354 | bail!("Password verification fail!"); | |
1355 | } | |
1356 | ||
1357 | if new_pw.len() < 5 { | |
1358 | bail!("Password is too short!"); | |
1359 | } | |
1360 | ||
1361 | let pub_key: Vec<u8> = pkey.public_key_to_pem()?; | |
1362 | let filename_pub = "master-public.pem"; | |
1363 | println!("Writing public master key to {}", filename_pub); | |
e18a6c9e | 1364 | file_set_contents(filename_pub, pub_key.as_slice(), None)?; |
37c5a175 DM |
1365 | |
1366 | let cipher = openssl::symm::Cipher::aes_256_cbc(); | |
1367 | let priv_key: Vec<u8> = pkey.private_key_to_pem_pkcs8_passphrase(cipher, new_pw.as_bytes())?; | |
1368 | ||
1369 | let filename_priv = "master-private.pem"; | |
1370 | println!("Writing private master key to {}", filename_priv); | |
e18a6c9e | 1371 | file_set_contents(filename_priv, priv_key.as_slice(), None)?; |
37c5a175 DM |
1372 | |
1373 | Ok(Value::Null) | |
1374 | } | |
ac716234 DM |
1375 | |
1376 | fn key_change_passphrase( | |
1377 | param: Value, | |
1378 | _info: &ApiMethod, | |
1379 | _rpcenv: &mut dyn RpcEnvironment, | |
1380 | ) -> Result<Value, Error> { | |
1381 | ||
9b06db45 DM |
1382 | let path = tools::required_string_param(¶m, "path")?; |
1383 | let path = PathBuf::from(path); | |
ac716234 | 1384 | |
181f097a DM |
1385 | let kdf = param["kdf"].as_str().unwrap_or("scrypt"); |
1386 | ||
ac716234 DM |
1387 | // we need a TTY to query the new password |
1388 | if !crate::tools::tty::stdin_isatty() { | |
1389 | bail!("unable to change passphrase - no tty"); | |
1390 | } | |
1391 | ||
ab44acff | 1392 | let (key, created) = load_and_decrtypt_key(&path, get_encryption_key_password)?; |
ac716234 | 1393 | |
181f097a | 1394 | if kdf == "scrypt" { |
ac716234 | 1395 | |
181f097a DM |
1396 | let new_pw = String::from_utf8(crate::tools::tty::read_password("New Password: ")?)?; |
1397 | let verify_pw = String::from_utf8(crate::tools::tty::read_password("Verify Password: ")?)?; | |
ac716234 | 1398 | |
181f097a DM |
1399 | if new_pw != verify_pw { |
1400 | bail!("Password verification fail!"); | |
1401 | } | |
1402 | ||
1403 | if new_pw.len() < 5 { | |
1404 | bail!("Password is too short!"); | |
1405 | } | |
ac716234 | 1406 | |
ab44acff DM |
1407 | let mut new_key_config = encrypt_key_with_passphrase(&key, new_pw.as_bytes())?; |
1408 | new_key_config.created = created; // keep original value | |
1409 | ||
1410 | store_key_config(&path, true, new_key_config)?; | |
ac716234 | 1411 | |
181f097a DM |
1412 | Ok(Value::Null) |
1413 | } else if kdf == "none" { | |
ab44acff | 1414 | let modified = Local.timestamp(Local::now().timestamp(), 0); |
181f097a DM |
1415 | |
1416 | store_key_config(&path, true, KeyConfig { | |
1417 | kdf: None, | |
ab44acff DM |
1418 | created, // keep original value |
1419 | modified, | |
6d0983db | 1420 | data: key.to_vec(), |
181f097a DM |
1421 | })?; |
1422 | ||
1423 | Ok(Value::Null) | |
1424 | } else { | |
1425 | unreachable!(); | |
1426 | } | |
f2401311 DM |
1427 | } |
1428 | ||
1429 | fn key_mgmt_cli() -> CliCommandMap { | |
1430 | ||
181f097a DM |
1431 | let kdf_schema: Arc<Schema> = Arc::new( |
1432 | StringSchema::new("Key derivation function. Choose 'none' to store the key unecrypted.") | |
1433 | .format(Arc::new(ApiStringFormat::Enum(&["scrypt", "none"]))) | |
1434 | .default("scrypt") | |
1435 | .into() | |
1436 | ); | |
1437 | ||
f2401311 DM |
1438 | let key_create_cmd_def = CliCommand::new( |
1439 | ApiMethod::new( | |
1440 | key_create, | |
1441 | ObjectSchema::new("Create a new encryption key.") | |
9b06db45 | 1442 | .required("path", StringSchema::new("File system path.")) |
181f097a | 1443 | .optional("kdf", kdf_schema.clone()) |
f2401311 | 1444 | )) |
9b06db45 DM |
1445 | .arg_param(vec!["path"]) |
1446 | .completion_cb("path", tools::complete_file_name); | |
f2401311 | 1447 | |
ac716234 DM |
1448 | let key_change_passphrase_cmd_def = CliCommand::new( |
1449 | ApiMethod::new( | |
1450 | key_change_passphrase, | |
1451 | ObjectSchema::new("Change the passphrase required to decrypt the key.") | |
9b06db45 | 1452 | .required("path", StringSchema::new("File system path.")) |
181f097a | 1453 | .optional("kdf", kdf_schema.clone()) |
9b06db45 DM |
1454 | )) |
1455 | .arg_param(vec!["path"]) | |
1456 | .completion_cb("path", tools::complete_file_name); | |
ac716234 | 1457 | |
37c5a175 DM |
1458 | let key_create_master_key_cmd_def = CliCommand::new( |
1459 | ApiMethod::new( | |
1460 | key_create_master_key, | |
1461 | ObjectSchema::new("Create a new 4096 bit RSA master pub/priv key pair.") | |
1462 | )); | |
1463 | ||
3ea8bfc9 DM |
1464 | let key_import_master_pubkey_cmd_def = CliCommand::new( |
1465 | ApiMethod::new( | |
1466 | key_import_master_pubkey, | |
1467 | ObjectSchema::new("Import a new RSA public key and use it as master key. The key is expected to be in '.pem' format.") | |
1468 | .required("path", StringSchema::new("File system path.")) | |
1469 | )) | |
1470 | .arg_param(vec!["path"]) | |
1471 | .completion_cb("path", tools::complete_file_name); | |
1472 | ||
f2401311 | 1473 | let cmd_def = CliCommandMap::new() |
ac716234 | 1474 | .insert("create".to_owned(), key_create_cmd_def.into()) |
37c5a175 | 1475 | .insert("create-master-key".to_owned(), key_create_master_key_cmd_def.into()) |
3ea8bfc9 | 1476 | .insert("import-master-pubkey".to_owned(), key_import_master_pubkey_cmd_def.into()) |
ac716234 | 1477 | .insert("change-passphrase".to_owned(), key_change_passphrase_cmd_def.into()); |
f2401311 DM |
1478 | |
1479 | cmd_def | |
1480 | } | |
1481 | ||
f2401311 | 1482 | fn main() { |
33d64b81 | 1483 | |
25f1650b DM |
1484 | let backup_source_schema: Arc<Schema> = Arc::new( |
1485 | StringSchema::new("Backup source specification ([<label>:<path>]).") | |
1486 | .format(Arc::new(ApiStringFormat::Pattern(&BACKUPSPEC_REGEX))) | |
1487 | .into() | |
1488 | ); | |
1489 | ||
597a9203 | 1490 | let backup_cmd_def = CliCommand::new( |
ff5d3707 | 1491 | ApiMethod::new( |
bcd879cf | 1492 | create_backup, |
597a9203 | 1493 | ObjectSchema::new("Create (host) backup.") |
ae0be2dd DM |
1494 | .required( |
1495 | "backupspec", | |
1496 | ArraySchema::new( | |
74cdb521 | 1497 | "List of backup source specifications ([<label.ext>:<path>] ...)", |
25f1650b | 1498 | backup_source_schema, |
ae0be2dd DM |
1499 | ).min_length(1) |
1500 | ) | |
2665cef7 | 1501 | .optional("repository", REPO_URL_SCHEMA.clone()) |
2eeaacb9 DM |
1502 | .optional( |
1503 | "include-dev", | |
1504 | ArraySchema::new( | |
1505 | "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.", | |
1506 | StringSchema::new("Path to file.").into() | |
1507 | ) | |
1508 | ) | |
6d0983db DM |
1509 | .optional( |
1510 | "keyfile", | |
1511 | StringSchema::new("Path to encryption key. All data will be encrypted using this key.")) | |
219ef0e6 DM |
1512 | .optional( |
1513 | "verbose", | |
1514 | BooleanSchema::new("Verbose output.").default(false)) | |
5b72c9b4 DM |
1515 | .optional( |
1516 | "skip-lost-and-found", | |
1517 | BooleanSchema::new("Skip lost+found directory").default(false)) | |
fba30411 | 1518 | .optional( |
bbf9e7e9 DM |
1519 | "backup-type", |
1520 | BACKUP_TYPE_SCHEMA.clone() | |
1521 | ) | |
1522 | .optional( | |
1523 | "backup-id", | |
1524 | BACKUP_ID_SCHEMA.clone() | |
1525 | ) | |
ca5d0b61 DM |
1526 | .optional( |
1527 | "backup-time", | |
bbf9e7e9 | 1528 | BACKUP_TIME_SCHEMA.clone() |
ca5d0b61 | 1529 | ) |
2d9d143a DM |
1530 | .optional( |
1531 | "chunk-size", | |
1532 | IntegerSchema::new("Chunk size in KB. Must be a power of 2.") | |
1533 | .minimum(64) | |
1534 | .maximum(4096) | |
1535 | .default(4096) | |
1536 | ) | |
ff5d3707 | 1537 | )) |
2665cef7 | 1538 | .arg_param(vec!["backupspec"]) |
d0a03d40 | 1539 | .completion_cb("repository", complete_repository) |
49811347 | 1540 | .completion_cb("backupspec", complete_backup_source) |
6d0983db | 1541 | .completion_cb("keyfile", tools::complete_file_name) |
49811347 | 1542 | .completion_cb("chunk-size", complete_chunk_size); |
f8838fe9 | 1543 | |
ec34f7eb DM |
1544 | let upload_log_cmd_def = CliCommand::new( |
1545 | ApiMethod::new( | |
1546 | upload_log, | |
1547 | ObjectSchema::new("Upload backup log file.") | |
1548 | .required("snapshot", StringSchema::new("Snapshot path.")) | |
1549 | .required("logfile", StringSchema::new("The path to the log file you want to upload.")) | |
1550 | .optional("repository", REPO_URL_SCHEMA.clone()) | |
1551 | .optional( | |
1552 | "keyfile", | |
1553 | StringSchema::new("Path to encryption key. All data will be encrypted using this key.")) | |
1554 | )) | |
1555 | .arg_param(vec!["snapshot", "logfile"]) | |
543a260f | 1556 | .completion_cb("snapshot", complete_backup_snapshot) |
ec34f7eb DM |
1557 | .completion_cb("logfile", tools::complete_file_name) |
1558 | .completion_cb("keyfile", tools::complete_file_name) | |
1559 | .completion_cb("repository", complete_repository); | |
1560 | ||
41c039e1 DM |
1561 | let list_cmd_def = CliCommand::new( |
1562 | ApiMethod::new( | |
812c6f87 DM |
1563 | list_backup_groups, |
1564 | ObjectSchema::new("List backup groups.") | |
2665cef7 | 1565 | .optional("repository", REPO_URL_SCHEMA.clone()) |
34a816cc | 1566 | .optional("output-format", OUTPUT_FORMAT.clone()) |
41c039e1 | 1567 | )) |
d0a03d40 | 1568 | .completion_cb("repository", complete_repository); |
41c039e1 | 1569 | |
184f17af DM |
1570 | let snapshots_cmd_def = CliCommand::new( |
1571 | ApiMethod::new( | |
1572 | list_snapshots, | |
1573 | ObjectSchema::new("List backup snapshots.") | |
15c847f1 | 1574 | .optional("group", StringSchema::new("Backup group.")) |
2665cef7 | 1575 | .optional("repository", REPO_URL_SCHEMA.clone()) |
34a816cc | 1576 | .optional("output-format", OUTPUT_FORMAT.clone()) |
184f17af | 1577 | )) |
2665cef7 | 1578 | .arg_param(vec!["group"]) |
024f11bb | 1579 | .completion_cb("group", complete_backup_group) |
d0a03d40 | 1580 | .completion_cb("repository", complete_repository); |
184f17af | 1581 | |
6f62c924 DM |
1582 | let forget_cmd_def = CliCommand::new( |
1583 | ApiMethod::new( | |
1584 | forget_snapshots, | |
1585 | ObjectSchema::new("Forget (remove) backup snapshots.") | |
6f62c924 | 1586 | .required("snapshot", StringSchema::new("Snapshot path.")) |
2665cef7 | 1587 | .optional("repository", REPO_URL_SCHEMA.clone()) |
6f62c924 | 1588 | )) |
2665cef7 | 1589 | .arg_param(vec!["snapshot"]) |
b2388518 | 1590 | .completion_cb("repository", complete_repository) |
543a260f | 1591 | .completion_cb("snapshot", complete_backup_snapshot); |
6f62c924 | 1592 | |
8cc0d6af DM |
1593 | let garbage_collect_cmd_def = CliCommand::new( |
1594 | ApiMethod::new( | |
1595 | start_garbage_collection, | |
1596 | ObjectSchema::new("Start garbage collection for a specific repository.") | |
2665cef7 | 1597 | .optional("repository", REPO_URL_SCHEMA.clone()) |
8cc0d6af | 1598 | )) |
d0a03d40 | 1599 | .completion_cb("repository", complete_repository); |
8cc0d6af | 1600 | |
9f912493 DM |
1601 | let restore_cmd_def = CliCommand::new( |
1602 | ApiMethod::new( | |
1603 | restore, | |
1604 | ObjectSchema::new("Restore backup repository.") | |
d5c34d98 DM |
1605 | .required("snapshot", StringSchema::new("Group/Snapshot path.")) |
1606 | .required("archive-name", StringSchema::new("Backup archive name.")) | |
bf125261 DM |
1607 | .required("target", StringSchema::new(r###"Target directory path. Use '-' to write to stdandard output. |
1608 | ||
1609 | We do not extraxt '.pxar' archives when writing to stdandard output. | |
1610 | ||
1611 | "### | |
1612 | )) | |
46d5aa0a DM |
1613 | .optional( |
1614 | "allow-existing-dirs", | |
1615 | BooleanSchema::new("Do not fail if directories already exists.").default(false)) | |
2665cef7 | 1616 | .optional("repository", REPO_URL_SCHEMA.clone()) |
86eda3eb DM |
1617 | .optional("keyfile", StringSchema::new("Path to encryption key.")) |
1618 | .optional( | |
1619 | "verbose", | |
1620 | BooleanSchema::new("Verbose output.").default(false) | |
1621 | ) | |
9f912493 | 1622 | )) |
2665cef7 | 1623 | .arg_param(vec!["snapshot", "archive-name", "target"]) |
b2388518 | 1624 | .completion_cb("repository", complete_repository) |
08dc340a DM |
1625 | .completion_cb("snapshot", complete_group_or_snapshot) |
1626 | .completion_cb("archive-name", complete_archive_name) | |
1627 | .completion_cb("target", tools::complete_file_name); | |
9f912493 | 1628 | |
52c171e4 DM |
1629 | let files_cmd_def = CliCommand::new( |
1630 | ApiMethod::new( | |
1631 | list_snapshot_files, | |
1632 | ObjectSchema::new("List snapshot files.") | |
1633 | .required("snapshot", StringSchema::new("Snapshot path.")) | |
cec17a3e | 1634 | .optional("repository", REPO_URL_SCHEMA.clone()) |
52c171e4 DM |
1635 | .optional("output-format", OUTPUT_FORMAT.clone()) |
1636 | )) | |
1637 | .arg_param(vec!["snapshot"]) | |
1638 | .completion_cb("repository", complete_repository) | |
543a260f | 1639 | .completion_cb("snapshot", complete_backup_snapshot); |
52c171e4 | 1640 | |
9049a8cf DM |
1641 | let catalog_cmd_def = CliCommand::new( |
1642 | ApiMethod::new( | |
1643 | dump_catalog, | |
1644 | ObjectSchema::new("Dump catalog.") | |
1645 | .required("snapshot", StringSchema::new("Snapshot path.")) | |
1646 | .optional("repository", REPO_URL_SCHEMA.clone()) | |
1647 | )) | |
1648 | .arg_param(vec!["snapshot"]) | |
1649 | .completion_cb("repository", complete_repository) | |
1650 | .completion_cb("snapshot", complete_backup_snapshot); | |
1651 | ||
83b7db02 DM |
1652 | let prune_cmd_def = CliCommand::new( |
1653 | ApiMethod::new( | |
1654 | prune, | |
1655 | proxmox_backup::api2::admin::datastore::add_common_prune_prameters( | |
1656 | ObjectSchema::new("Prune backup repository.") | |
9fdc3ef4 | 1657 | .required("group", StringSchema::new("Backup group.")) |
2665cef7 | 1658 | .optional("repository", REPO_URL_SCHEMA.clone()) |
83b7db02 DM |
1659 | ) |
1660 | )) | |
9fdc3ef4 DM |
1661 | .arg_param(vec!["group"]) |
1662 | .completion_cb("group", complete_backup_group) | |
d0a03d40 | 1663 | .completion_cb("repository", complete_repository); |
9f912493 | 1664 | |
34a816cc DM |
1665 | let status_cmd_def = CliCommand::new( |
1666 | ApiMethod::new( | |
1667 | status, | |
1668 | ObjectSchema::new("Get repository status.") | |
1669 | .optional("repository", REPO_URL_SCHEMA.clone()) | |
1670 | .optional("output-format", OUTPUT_FORMAT.clone()) | |
1671 | )) | |
1672 | .completion_cb("repository", complete_repository); | |
1673 | ||
e240d8be DM |
1674 | let login_cmd_def = CliCommand::new( |
1675 | ApiMethod::new( | |
1676 | api_login, | |
1677 | ObjectSchema::new("Try to login. If successful, store ticket.") | |
1678 | .optional("repository", REPO_URL_SCHEMA.clone()) | |
1679 | )) | |
1680 | .completion_cb("repository", complete_repository); | |
1681 | ||
1682 | let logout_cmd_def = CliCommand::new( | |
1683 | ApiMethod::new( | |
1684 | api_logout, | |
1685 | ObjectSchema::new("Logout (delete stored ticket).") | |
1686 | .optional("repository", REPO_URL_SCHEMA.clone()) | |
1687 | )) | |
1688 | .completion_cb("repository", complete_repository); | |
1689 | ||
41c039e1 | 1690 | let cmd_def = CliCommandMap::new() |
597a9203 | 1691 | .insert("backup".to_owned(), backup_cmd_def.into()) |
ec34f7eb | 1692 | .insert("upload-log".to_owned(), upload_log_cmd_def.into()) |
6f62c924 | 1693 | .insert("forget".to_owned(), forget_cmd_def.into()) |
9049a8cf | 1694 | .insert("catalog".to_owned(), catalog_cmd_def.into()) |
8cc0d6af | 1695 | .insert("garbage-collect".to_owned(), garbage_collect_cmd_def.into()) |
83b7db02 | 1696 | .insert("list".to_owned(), list_cmd_def.into()) |
e240d8be DM |
1697 | .insert("login".to_owned(), login_cmd_def.into()) |
1698 | .insert("logout".to_owned(), logout_cmd_def.into()) | |
184f17af | 1699 | .insert("prune".to_owned(), prune_cmd_def.into()) |
9f912493 | 1700 | .insert("restore".to_owned(), restore_cmd_def.into()) |
f2401311 | 1701 | .insert("snapshots".to_owned(), snapshots_cmd_def.into()) |
52c171e4 | 1702 | .insert("files".to_owned(), files_cmd_def.into()) |
34a816cc | 1703 | .insert("status".to_owned(), status_cmd_def.into()) |
f2401311 | 1704 | .insert("key".to_owned(), key_mgmt_cli().into()); |
a914a774 | 1705 | |
5a2df000 DM |
1706 | hyper::rt::run(futures::future::lazy(move || { |
1707 | run_cli_command(cmd_def.into()); | |
1708 | Ok(()) | |
1709 | })); | |
496a6784 | 1710 | |
ff5d3707 | 1711 | } |