]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-manager.rs
bump proxmox crate to 0.1.7
[proxmox-backup.git] / src / bin / proxmox-backup-manager.rs
CommitLineData
769f8c99 1use failure::*;
47d47121 2use serde_json::{json, Value};
550e0d88 3use std::path::PathBuf;
331b869d 4use std::collections::HashMap;
ea0b8b6e 5
769f8c99
DM
6use proxmox::api::{api, cli::*};
7
550e0d88 8use proxmox_backup::configdir;
769f8c99 9use proxmox_backup::tools;
f357390c 10use proxmox_backup::config::{self, remote::{self, Remote}};
769f8c99
DM
11use proxmox_backup::api2::types::*;
12use proxmox_backup::client::*;
13use proxmox_backup::tools::ticket::*;
14use proxmox_backup::auth_helpers::*;
15
769f8c99
DM
16async fn view_task_result(
17 client: HttpClient,
18 result: Value,
19 output_format: &str,
20) -> Result<(), Error> {
21 let data = &result["data"];
22 if output_format == "text" {
23 if let Some(upid) = data.as_str() {
24 display_task_log(client, upid, true).await?;
25 }
26 } else {
27 format_and_print_result(&data, &output_format);
28 }
29
30 Ok(())
31}
211fabd7 32
47d47121
DM
33fn connect() -> Result<HttpClient, Error> {
34
35 let uid = nix::unistd::Uid::current();
36
37 let client = if uid.is_root() {
38 let ticket = assemble_rsa_ticket(private_auth_key(), "PBS", Some("root@pam"), None)?;
39 HttpClient::new("localhost", "root@pam", Some(ticket))?
40 } else {
41 HttpClient::new("localhost", "root@pam", None)?
42 };
43
44 Ok(client)
45}
46
f357390c 47fn remote_commands() -> CommandLineInterface {
688fbe07
DM
48
49 use proxmox_backup::api2;
50
51 let cmd_def = CliCommandMap::new()
f357390c 52 .insert("list", CliCommand::new(&api2::config::remote::API_METHOD_LIST_REMOTES))
688fbe07
DM
53 .insert(
54 "create",
55 // fixme: howto handle password parameter?
f357390c 56 CliCommand::new(&api2::config::remote::API_METHOD_CREATE_REMOTE)
688fbe07
DM
57 .arg_param(&["name"])
58 )
08195ac8
DM
59 .insert(
60 "update",
f357390c 61 CliCommand::new(&api2::config::remote::API_METHOD_UPDATE_REMOTE)
08195ac8 62 .arg_param(&["name"])
f357390c 63 .completion_cb("name", config::remote::complete_remote_name)
08195ac8 64 )
688fbe07
DM
65 .insert(
66 "remove",
f357390c 67 CliCommand::new(&api2::config::remote::API_METHOD_DELETE_REMOTE)
688fbe07 68 .arg_param(&["name"])
f357390c 69 .completion_cb("name", config::remote::complete_remote_name)
688fbe07
DM
70 );
71
72 cmd_def.into()
73}
74
9f6ab1fc 75fn datastore_commands() -> CommandLineInterface {
ea0b8b6e 76
576e3bf2 77 use proxmox_backup::api2;
bf7f1039 78
6460764d 79 let cmd_def = CliCommandMap::new()
688fbe07 80 .insert("list", CliCommand::new(&api2::config::datastore::API_METHOD_LIST_DATASTORES))
6460764d 81 .insert("create",
688fbe07 82 CliCommand::new(&api2::config::datastore::API_METHOD_CREATE_DATASTORE)
49fddd98 83 .arg_param(&["name", "path"])
48ef3c33 84 )
ddc52662
DM
85 .insert("update",
86 CliCommand::new(&api2::config::datastore::API_METHOD_UPDATE_DATASTORE)
87 .arg_param(&["name"])
3be839c6 88 .completion_cb("name", config::datastore::complete_datastore_name)
ddc52662 89 )
6460764d 90 .insert("remove",
688fbe07 91 CliCommand::new(&api2::config::datastore::API_METHOD_DELETE_DATASTORE)
49fddd98 92 .arg_param(&["name"])
07b4694a 93 .completion_cb("name", config::datastore::complete_datastore_name)
48ef3c33 94 );
211fabd7 95
8f62336b 96 cmd_def.into()
211fabd7
DM
97}
98
691c89a0 99
769f8c99
DM
100#[api(
101 input: {
102 properties: {
103 store: {
104 schema: DATASTORE_SCHEMA,
105 },
106 "output-format": {
107 schema: OUTPUT_FORMAT,
108 optional: true,
109 },
110 }
111 }
112)]
113/// Start garbage collection for a specific datastore.
114async fn start_garbage_collection(param: Value) -> Result<Value, Error> {
691c89a0 115
769f8c99 116 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
691c89a0 117
769f8c99
DM
118 let store = tools::required_string_param(&param, "store")?;
119
47d47121 120 let mut client = connect()?;
769f8c99
DM
121
122 let path = format!("api2/json/admin/datastore/{}/gc", store);
123
124 let result = client.post(&path, None).await?;
125
126 view_task_result(client, result, &output_format).await?;
127
128 Ok(Value::Null)
129}
130
131#[api(
132 input: {
133 properties: {
134 store: {
135 schema: DATASTORE_SCHEMA,
136 },
137 "output-format": {
138 schema: OUTPUT_FORMAT,
139 optional: true,
140 },
141 }
142 }
143)]
144/// Show garbage collection status for a specific datastore.
145async fn garbage_collection_status(param: Value) -> Result<Value, Error> {
146
147 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
148
149 let store = tools::required_string_param(&param, "store")?;
150
47d47121 151 let client = connect()?;
769f8c99
DM
152
153 let path = format!("api2/json/admin/datastore/{}/gc", store);
154
155 let result = client.get(&path, None).await?;
156 let data = &result["data"];
157 if output_format == "text" {
158 format_and_print_result(&data, "json-pretty");
159 } else {
160 format_and_print_result(&data, &output_format);
161 }
162
163 Ok(Value::Null)
164}
165
166fn garbage_collection_commands() -> CommandLineInterface {
691c89a0
DM
167
168 let cmd_def = CliCommandMap::new()
169 .insert("status",
769f8c99 170 CliCommand::new(&API_METHOD_GARBAGE_COLLECTION_STATUS)
49fddd98 171 .arg_param(&["store"])
9ac1045c 172 .completion_cb("store", config::datastore::complete_datastore_name)
48ef3c33 173 )
691c89a0 174 .insert("start",
769f8c99 175 CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
49fddd98 176 .arg_param(&["store"])
9ac1045c 177 .completion_cb("store", config::datastore::complete_datastore_name)
48ef3c33 178 );
691c89a0
DM
179
180 cmd_def.into()
181}
182
47d47121
DM
183#[api(
184 input: {
185 properties: {
186 limit: {
187 description: "The maximal number of tasks to list.",
188 type: Integer,
189 optional: true,
190 minimum: 1,
191 maximum: 1000,
192 default: 50,
193 },
194 "output-format": {
195 schema: OUTPUT_FORMAT,
196 optional: true,
197 },
198 all: {
199 type: Boolean,
200 description: "Also list stopped tasks.",
201 optional: true,
202 }
203 }
204 }
205)]
206/// List running server tasks.
207async fn task_list(param: Value) -> Result<Value, Error> {
208
209 let output_format = param["output-format"].as_str().unwrap_or("text").to_owned();
210
211 let client = connect()?;
212
213 let limit = param["limit"].as_u64().unwrap_or(50) as usize;
214 let running = !param["all"].as_bool().unwrap_or(false);
215 let args = json!({
216 "running": running,
217 "start": 0,
218 "limit": limit,
219 });
220 let result = client.get("api2/json/nodes/localhost/tasks", Some(args)).await?;
221
222 let data = &result["data"];
223
224 if output_format == "text" {
225 for item in data.as_array().unwrap() {
226 println!(
227 "{} {}",
228 item["upid"].as_str().unwrap(),
229 item["status"].as_str().unwrap_or("running"),
230 );
231 }
232 } else {
233 format_and_print_result(data, &output_format);
234 }
235
236 Ok(Value::Null)
237}
238
239#[api(
240 input: {
241 properties: {
242 upid: {
243 schema: UPID_SCHEMA,
244 },
245 }
246 }
247)]
248/// Display the task log.
249async fn task_log(param: Value) -> Result<Value, Error> {
250
251 let upid = tools::required_string_param(&param, "upid")?;
252
253 let client = connect()?;
254
255 display_task_log(client, upid, true).await?;
256
257 Ok(Value::Null)
258}
259
260#[api(
261 input: {
262 properties: {
263 upid: {
264 schema: UPID_SCHEMA,
265 },
266 }
267 }
268)]
269/// Try to stop a specific task.
270async fn task_stop(param: Value) -> Result<Value, Error> {
271
272 let upid_str = tools::required_string_param(&param, "upid")?;
273
274 let mut client = connect()?;
275
276 let path = format!("api2/json/nodes/localhost/tasks/{}", upid_str);
277 let _ = client.delete(&path, None).await?;
278
279 Ok(Value::Null)
280}
281
282fn task_mgmt_cli() -> CommandLineInterface {
283
284 let task_log_cmd_def = CliCommand::new(&API_METHOD_TASK_LOG)
285 .arg_param(&["upid"]);
286
287 let task_stop_cmd_def = CliCommand::new(&API_METHOD_TASK_STOP)
288 .arg_param(&["upid"]);
289
290 let cmd_def = CliCommandMap::new()
291 .insert("list", CliCommand::new(&API_METHOD_TASK_LIST))
292 .insert("log", task_log_cmd_def)
293 .insert("stop", task_stop_cmd_def);
294
295 cmd_def.into()
296}
297
e739a8d8
DM
298fn x509name_to_string(name: &openssl::x509::X509NameRef) -> Result<String, Error> {
299 let mut parts = Vec::new();
300 for entry in name.entries() {
301 parts.push(format!("{} = {}", entry.object().nid().short_name()?, entry.data().as_utf8()?));
302 }
303 Ok(parts.join(", "))
304}
305
306#[api]
307/// Diplay node certificate information.
308fn cert_info() -> Result<(), Error> {
309
310 let cert_path = PathBuf::from(configdir!("/proxy.pem"));
311
312 let cert_pem = proxmox::tools::fs::file_get_contents(&cert_path)?;
313
314 let cert = openssl::x509::X509::from_pem(&cert_pem)?;
315
316 println!("Subject: {}", x509name_to_string(cert.subject_name())?);
317
318 if let Some(san) = cert.subject_alt_names() {
319 for name in san.iter() {
320 if let Some(v) = name.dnsname() {
321 println!(" DNS:{}", v);
322 } else if let Some(v) = name.ipaddress() {
323 println!(" IP:{:?}", v);
324 } else if let Some(v) = name.email() {
325 println!(" EMAIL:{}", v);
326 } else if let Some(v) = name.uri() {
327 println!(" URI:{}", v);
328 }
329 }
330 }
331
332 println!("Issuer: {}", x509name_to_string(cert.issuer_name())?);
333 println!("Validity:");
334 println!(" Not Before: {}", cert.not_before());
335 println!(" Not After : {}", cert.not_after());
336
337 let fp = cert.digest(openssl::hash::MessageDigest::sha256())?;
338 let fp_string = proxmox::tools::digest_to_hex(&fp);
339 let fp_string = fp_string.as_bytes().chunks(2).map(|v| std::str::from_utf8(v).unwrap())
340 .collect::<Vec<&str>>().join(":");
341
342 println!("Fingerprint (sha256): {}", fp_string);
343
344 let pubkey = cert.public_key()?;
345 println!("Public key type: {}", openssl::nid::Nid::from_raw(pubkey.id().as_raw()).long_name()?);
346 println!("Public key bits: {}", pubkey.bits());
347
348 Ok(())
349}
350
550e0d88
DM
351#[api(
352 input: {
353 properties: {
354 force: {
355 description: "Force generation of new SSL certifate.",
356 type: Boolean,
357 optional:true,
358 },
359 }
360 },
361)]
362/// Update node certificates and generate all needed files/directories.
363fn update_certs(force: Option<bool>) -> Result<(), Error> {
364
550e0d88
DM
365 config::create_configdir()?;
366
367 if let Err(err) = generate_auth_key() {
368 bail!("unable to generate auth key - {}", err);
369 }
370
371 if let Err(err) = generate_csrf_key() {
372 bail!("unable to generate csrf key - {}", err);
373 }
374
f8fd5095 375 config::update_self_signed_cert(force.unwrap_or(false))?;
550e0d88
DM
376
377 Ok(())
378}
379
380fn cert_mgmt_cli() -> CommandLineInterface {
381
550e0d88 382 let cmd_def = CliCommandMap::new()
e739a8d8
DM
383 .insert("info", CliCommand::new(&API_METHOD_CERT_INFO))
384 .insert("update", CliCommand::new(&API_METHOD_UPDATE_CERTS));
550e0d88
DM
385
386 cmd_def.into()
387}
388
4b4eba0b 389// fixme: avoid API redefinition
0eb0e024
DM
390#[api(
391 input: {
392 properties: {
eb506c83 393 "local-store": {
0eb0e024
DM
394 schema: DATASTORE_SCHEMA,
395 },
396 remote: {
167971ed 397 schema: REMOTE_ID_SCHEMA,
0eb0e024
DM
398 },
399 "remote-store": {
400 schema: DATASTORE_SCHEMA,
401 },
4b4eba0b
DM
402 delete: {
403 description: "Delete vanished backups. This remove the local copy if the remote backup was deleted.",
404 type: Boolean,
405 optional: true,
406 default: true,
407 },
0eb0e024
DM
408 "output-format": {
409 schema: OUTPUT_FORMAT,
410 optional: true,
411 },
412 }
413 }
414)]
eb506c83
DM
415/// Sync datastore from another repository
416async fn pull_datastore(
0eb0e024
DM
417 remote: String,
418 remote_store: String,
eb506c83 419 local_store: String,
4b4eba0b 420 delete: Option<bool>,
0eb0e024
DM
421 output_format: Option<String>,
422) -> Result<Value, Error> {
423
424 let output_format = output_format.unwrap_or("text".to_string());
425
426 let mut client = connect()?;
427
4b4eba0b 428 let mut args = json!({
eb506c83 429 "store": local_store,
94609e23 430 "remote": remote,
0eb0e024 431 "remote-store": remote_store,
0eb0e024
DM
432 });
433
4b4eba0b
DM
434 if let Some(delete) = delete {
435 args["delete"] = delete.into();
436 }
437
eb506c83 438 let result = client.post("api2/json/pull", Some(args)).await?;
0eb0e024
DM
439
440 view_task_result(client, result, &output_format).await?;
441
442 Ok(Value::Null)
443}
444
211fabd7
DM
445fn main() {
446
6460764d 447 let cmd_def = CliCommandMap::new()
48ef3c33 448 .insert("datastore", datastore_commands())
f357390c 449 .insert("remote", remote_commands())
47d47121 450 .insert("garbage-collection", garbage_collection_commands())
550e0d88 451 .insert("cert", cert_mgmt_cli())
0eb0e024
DM
452 .insert("task", task_mgmt_cli())
453 .insert(
eb506c83
DM
454 "pull",
455 CliCommand::new(&API_METHOD_PULL_DATASTORE)
456 .arg_param(&["remote", "remote-store", "local-store"])
457 .completion_cb("local-store", config::datastore::complete_datastore_name)
f357390c 458 .completion_cb("remote", config::remote::complete_remote_name)
331b869d 459 .completion_cb("remote-store", complete_remote_datastore_name)
0eb0e024 460 );
34d3ba52 461
3f06d6fb 462 proxmox_backup::tools::runtime::main(run_cli_command(cmd_def));
ea0b8b6e 463}
331b869d
DM
464
465// shell completion helper
466pub fn complete_remote_datastore_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
467
468 let mut list = Vec::new();
469
9ea4bce4 470 let _ = proxmox::try_block!({
331b869d 471 let remote = param.get("remote").ok_or_else(|| format_err!("no remote"))?;
f357390c 472 let (remote_config, _digest) = remote::config()?;
331b869d
DM
473
474 let remote: Remote = remote_config.lookup("remote", &remote)?;
475
476 let client = HttpClient::new(
477 &remote.host,
478 &remote.userid,
479 Some(remote.password)
480 )?;
481
482 let mut rt = tokio::runtime::Runtime::new().unwrap();
483 let result = rt.block_on(client.get("api2/json/admin/datastore", None))?;
484
485 if let Some(data) = result["data"].as_array() {
486 for item in data {
487 if let Some(store) = item["store"].as_str() {
488 list.push(store.to_owned());
489 }
490 }
491 }
492
493 Ok(())
494 }).map_err(|_err: Error| { /* ignore */ });
495
496 list
497}