]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-manager.rs
src/api2/config/network.rs: improve network api
[proxmox-backup.git] / src / bin / proxmox-backup-manager.rs
CommitLineData
550e0d88 1use std::path::PathBuf;
331b869d 2use std::collections::HashMap;
ea0b8b6e 3
f7d4e4b5 4use anyhow::{bail, format_err, Error};
9894469e 5use serde_json::{json, Value};
9894469e 6
9e165b5c 7use proxmox::api::{api, cli::*, RpcEnvironment, ApiHandler};
769f8c99 8
550e0d88 9use proxmox_backup::configdir;
769f8c99 10use proxmox_backup::tools;
f357390c 11use proxmox_backup::config::{self, remote::{self, Remote}};
9894469e 12use proxmox_backup::api2::{self, types::* };
769f8c99
DM
13use proxmox_backup::client::*;
14use proxmox_backup::tools::ticket::*;
15use proxmox_backup::auth_helpers::*;
16
769f8c99
DM
17async fn view_task_result(
18 client: HttpClient,
19 result: Value,
20 output_format: &str,
21) -> Result<(), Error> {
22 let data = &result["data"];
23 if output_format == "text" {
24 if let Some(upid) = data.as_str() {
25 display_task_log(client, upid, true).await?;
26 }
27 } else {
28 format_and_print_result(&data, &output_format);
29 }
30
31 Ok(())
32}
211fabd7 33
47d47121
DM
34fn connect() -> Result<HttpClient, Error> {
35
36 let uid = nix::unistd::Uid::current();
37
d59dbeca 38 let mut options = HttpClientOptions::new()
5030b7ce 39 .prefix(Some("proxmox-backup".to_string()))
d59dbeca
DM
40 .verify_cert(false); // not required for connection to localhost
41
47d47121
DM
42 let client = if uid.is_root() {
43 let ticket = assemble_rsa_ticket(private_auth_key(), "PBS", Some("root@pam"), None)?;
d59dbeca
DM
44 options = options.password(Some(ticket));
45 HttpClient::new("localhost", "root@pam", options)?
47d47121 46 } else {
d59dbeca
DM
47 options = options.ticket_cache(true).interactive(true);
48 HttpClient::new("localhost", "root@pam", options)?
47d47121
DM
49 };
50
51 Ok(client)
52}
53
9894469e
DM
54#[api(
55 input: {
56 properties: {
57 "output-format": {
58 schema: OUTPUT_FORMAT,
59 optional: true,
60 },
61 }
62 }
63)]
64/// List configured remotes.
9e165b5c 65fn list_remotes(param: Value, rpcenv: &mut dyn RpcEnvironment) -> Result<Value, Error> {
688fbe07 66
ac3faaf5 67 let output_format = get_output_format(&param);
9894469e 68
9e165b5c
DM
69 let info = &api2::config::remote::API_METHOD_LIST_REMOTES;
70 let mut data = match info.handler {
71 ApiHandler::Sync(handler) => (handler)(param, info, rpcenv)?,
72 _ => unreachable!(),
73 };
9894469e 74
ac3faaf5 75 let options = default_table_format_options()
93fbb4ef
DM
76 .column(ColumnConfig::new("name"))
77 .column(ColumnConfig::new("host"))
78 .column(ColumnConfig::new("userid"))
79 .column(ColumnConfig::new("fingerprint"))
80 .column(ColumnConfig::new("comment"));
9894469e 81
9e165b5c 82 format_and_print_result_full(&mut data, info.returns, &output_format, &options);
9894469e
DM
83
84 Ok(Value::Null)
85}
86
87fn remote_commands() -> CommandLineInterface {
688fbe07
DM
88
89 let cmd_def = CliCommandMap::new()
9894469e 90 .insert("list", CliCommand::new(&&API_METHOD_LIST_REMOTES))
688fbe07
DM
91 .insert(
92 "create",
93 // fixme: howto handle password parameter?
f357390c 94 CliCommand::new(&api2::config::remote::API_METHOD_CREATE_REMOTE)
688fbe07
DM
95 .arg_param(&["name"])
96 )
08195ac8
DM
97 .insert(
98 "update",
f357390c 99 CliCommand::new(&api2::config::remote::API_METHOD_UPDATE_REMOTE)
08195ac8 100 .arg_param(&["name"])
f357390c 101 .completion_cb("name", config::remote::complete_remote_name)
08195ac8 102 )
688fbe07
DM
103 .insert(
104 "remove",
f357390c 105 CliCommand::new(&api2::config::remote::API_METHOD_DELETE_REMOTE)
688fbe07 106 .arg_param(&["name"])
f357390c 107 .completion_cb("name", config::remote::complete_remote_name)
688fbe07
DM
108 );
109
110 cmd_def.into()
111}
112
579728c6
DM
113#[api(
114 input: {
115 properties: {
116 "output-format": {
117 schema: OUTPUT_FORMAT,
118 optional: true,
119 },
120 }
121 }
122)]
123/// List configured users.
124fn list_users(param: Value, rpcenv: &mut dyn RpcEnvironment) -> Result<Value, Error> {
125
126 let output_format = get_output_format(&param);
127
685e1334 128 let info = &api2::access::user::API_METHOD_LIST_USERS;
579728c6
DM
129 let mut data = match info.handler {
130 ApiHandler::Sync(handler) => (handler)(param, info, rpcenv)?,
131 _ => unreachable!(),
132 };
133
134 let options = default_table_format_options()
135 .column(ColumnConfig::new("userid"))
136 .column(ColumnConfig::new("enable"))
137 .column(ColumnConfig::new("expire"))
138 .column(ColumnConfig::new("firstname"))
139 .column(ColumnConfig::new("lastname"))
140 .column(ColumnConfig::new("email"))
141 .column(ColumnConfig::new("comment"));
142
143 format_and_print_result_full(&mut data, info.returns, &output_format, &options);
144
145 Ok(Value::Null)
146}
147
148fn user_commands() -> CommandLineInterface {
149
150 let cmd_def = CliCommandMap::new()
151 .insert("list", CliCommand::new(&&API_METHOD_LIST_USERS))
152 .insert(
153 "create",
154 // fixme: howto handle password parameter?
685e1334 155 CliCommand::new(&api2::access::user::API_METHOD_CREATE_USER)
579728c6
DM
156 .arg_param(&["userid"])
157 )
158 .insert(
159 "update",
685e1334 160 CliCommand::new(&api2::access::user::API_METHOD_UPDATE_USER)
579728c6
DM
161 .arg_param(&["userid"])
162 .completion_cb("userid", config::user::complete_user_name)
163 )
164 .insert(
165 "remove",
685e1334 166 CliCommand::new(&api2::access::user::API_METHOD_DELETE_USER)
579728c6
DM
167 .arg_param(&["userid"])
168 .completion_cb("userid", config::user::complete_user_name)
169 );
170
171 cmd_def.into()
172}
173
ed3e60ae
DM
174#[api(
175 input: {
176 properties: {
177 "output-format": {
178 schema: OUTPUT_FORMAT,
179 optional: true,
180 },
181 }
182 }
183)]
184/// Access Control list.
185fn list_acls(param: Value, rpcenv: &mut dyn RpcEnvironment) -> Result<Value, Error> {
186
187 let output_format = get_output_format(&param);
188
189 let info = &api2::access::acl::API_METHOD_READ_ACL;
190 let mut data = match info.handler {
191 ApiHandler::Sync(handler) => (handler)(param, info, rpcenv)?,
192 _ => unreachable!(),
193 };
194
195 fn render_ugid(value: &Value, record: &Value) -> Result<String, Error> {
196 if value.is_null() { return Ok(String::new()); }
197 let ugid = value.as_str().unwrap();
198 let ugid_type = record["ugid_type"].as_str().unwrap();
199
200 if ugid_type == "user" {
201 Ok(ugid.to_string())
202 } else if ugid_type == "group" {
203 Ok(format!("@{}", ugid))
204 } else {
205 bail!("render_ugid: got unknown ugid_type");
206 }
207 }
208
209 let options = default_table_format_options()
210 .column(ColumnConfig::new("ugid").renderer(render_ugid))
211 .column(ColumnConfig::new("path"))
212 .column(ColumnConfig::new("propagate"))
213 .column(ColumnConfig::new("roleid"));
214
215 format_and_print_result_full(&mut data, info.returns, &output_format, &options);
216
217 Ok(Value::Null)
218}
219
220fn acl_commands() -> CommandLineInterface {
221
222 let cmd_def = CliCommandMap::new()
9765092e
DM
223 .insert("list", CliCommand::new(&&API_METHOD_LIST_ACLS))
224 .insert(
225 "update",
226 CliCommand::new(&api2::access::acl::API_METHOD_UPDATE_ACL)
227 .arg_param(&["path", "role"])
228 .completion_cb("userid", config::user::complete_user_name)
229 .completion_cb("path", config::datastore::complete_acl_path)
230
231 );
ed3e60ae
DM
232
233 cmd_def.into()
234}
235
ca0e5347
DM
236fn network_commands() -> CommandLineInterface {
237
238 let cmd_def = CliCommandMap::new()
df6bb03d
DM
239 .insert("list", CliCommand::new(&api2::config::network::API_METHOD_LIST_NETWORK_DEVICES))
240 .insert("update",
241 CliCommand::new(&api2::config::network::API_METHOD_UPDATE_INTERFACE)
242 .arg_param(&["name"])
243 .completion_cb("name", config::network::complete_interface_name)
244 )
245 .insert("remove",
246 CliCommand::new(&api2::config::network::API_METHOD_DELETE_INTERFACE)
247 .arg_param(&["name"])
248 .completion_cb("name", config::network::complete_interface_name)
249 );
ca0e5347
DM
250
251 cmd_def.into()
252}
253
9f6ab1fc 254fn datastore_commands() -> CommandLineInterface {
ea0b8b6e 255
6460764d 256 let cmd_def = CliCommandMap::new()
688fbe07 257 .insert("list", CliCommand::new(&api2::config::datastore::API_METHOD_LIST_DATASTORES))
6460764d 258 .insert("create",
688fbe07 259 CliCommand::new(&api2::config::datastore::API_METHOD_CREATE_DATASTORE)
49fddd98 260 .arg_param(&["name", "path"])
48ef3c33 261 )
ddc52662
DM
262 .insert("update",
263 CliCommand::new(&api2::config::datastore::API_METHOD_UPDATE_DATASTORE)
264 .arg_param(&["name"])
3be839c6 265 .completion_cb("name", config::datastore::complete_datastore_name)
ddc52662 266 )
6460764d 267 .insert("remove",
688fbe07 268 CliCommand::new(&api2::config::datastore::API_METHOD_DELETE_DATASTORE)
49fddd98 269 .arg_param(&["name"])
07b4694a 270 .completion_cb("name", config::datastore::complete_datastore_name)
48ef3c33 271 );
211fabd7 272
8f62336b 273 cmd_def.into()
211fabd7
DM
274}
275
691c89a0 276
769f8c99
DM
277#[api(
278 input: {
279 properties: {
280 store: {
281 schema: DATASTORE_SCHEMA,
282 },
283 "output-format": {
284 schema: OUTPUT_FORMAT,
285 optional: true,
286 },
287 }
288 }
289)]
290/// Start garbage collection for a specific datastore.
291async fn start_garbage_collection(param: Value) -> Result<Value, Error> {
691c89a0 292
ac3faaf5 293 let output_format = get_output_format(&param);
691c89a0 294
769f8c99
DM
295 let store = tools::required_string_param(&param, "store")?;
296
47d47121 297 let mut client = connect()?;
769f8c99
DM
298
299 let path = format!("api2/json/admin/datastore/{}/gc", store);
300
301 let result = client.post(&path, None).await?;
302
303 view_task_result(client, result, &output_format).await?;
304
305 Ok(Value::Null)
306}
307
308#[api(
309 input: {
310 properties: {
311 store: {
312 schema: DATASTORE_SCHEMA,
313 },
314 "output-format": {
315 schema: OUTPUT_FORMAT,
316 optional: true,
317 },
318 }
319 }
320)]
321/// Show garbage collection status for a specific datastore.
322async fn garbage_collection_status(param: Value) -> Result<Value, Error> {
323
ac3faaf5 324 let output_format = get_output_format(&param);
769f8c99
DM
325
326 let store = tools::required_string_param(&param, "store")?;
327
47d47121 328 let client = connect()?;
769f8c99
DM
329
330 let path = format!("api2/json/admin/datastore/{}/gc", store);
331
9894469e
DM
332 let mut result = client.get(&path, None).await?;
333 let mut data = result["data"].take();
334 let schema = api2::admin::datastore::API_RETURN_SCHEMA_GARBAGE_COLLECTION_STATUS;
335
ac3faaf5 336 let options = default_table_format_options();
9894469e
DM
337
338 format_and_print_result_full(&mut data, schema, &output_format, &options);
769f8c99
DM
339
340 Ok(Value::Null)
341}
342
343fn garbage_collection_commands() -> CommandLineInterface {
691c89a0
DM
344
345 let cmd_def = CliCommandMap::new()
346 .insert("status",
769f8c99 347 CliCommand::new(&API_METHOD_GARBAGE_COLLECTION_STATUS)
49fddd98 348 .arg_param(&["store"])
9ac1045c 349 .completion_cb("store", config::datastore::complete_datastore_name)
48ef3c33 350 )
691c89a0 351 .insert("start",
769f8c99 352 CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
49fddd98 353 .arg_param(&["store"])
9ac1045c 354 .completion_cb("store", config::datastore::complete_datastore_name)
48ef3c33 355 );
691c89a0
DM
356
357 cmd_def.into()
358}
359
47d47121
DM
360#[api(
361 input: {
362 properties: {
363 limit: {
364 description: "The maximal number of tasks to list.",
365 type: Integer,
366 optional: true,
367 minimum: 1,
368 maximum: 1000,
369 default: 50,
370 },
371 "output-format": {
372 schema: OUTPUT_FORMAT,
373 optional: true,
374 },
375 all: {
376 type: Boolean,
377 description: "Also list stopped tasks.",
378 optional: true,
379 }
380 }
381 }
382)]
383/// List running server tasks.
384async fn task_list(param: Value) -> Result<Value, Error> {
385
ac3faaf5 386 let output_format = get_output_format(&param);
47d47121
DM
387
388 let client = connect()?;
389
390 let limit = param["limit"].as_u64().unwrap_or(50) as usize;
391 let running = !param["all"].as_bool().unwrap_or(false);
392 let args = json!({
393 "running": running,
394 "start": 0,
395 "limit": limit,
396 });
9894469e 397 let mut result = client.get("api2/json/nodes/localhost/tasks", Some(args)).await?;
47d47121 398
9894469e
DM
399 let mut data = result["data"].take();
400 let schema = api2::node::tasks::API_RETURN_SCHEMA_LIST_TASKS;
47d47121 401
ac3faaf5 402 let options = default_table_format_options()
4939255f
DM
403 .column(ColumnConfig::new("starttime").right_align(false).renderer(tools::format::render_epoch))
404 .column(ColumnConfig::new("endtime").right_align(false).renderer(tools::format::render_epoch))
93fbb4ef 405 .column(ColumnConfig::new("upid"))
4939255f 406 .column(ColumnConfig::new("status").renderer(tools::format::render_task_status));
9894469e
DM
407
408 format_and_print_result_full(&mut data, schema, &output_format, &options);
47d47121
DM
409
410 Ok(Value::Null)
411}
412
413#[api(
414 input: {
415 properties: {
416 upid: {
417 schema: UPID_SCHEMA,
418 },
419 }
420 }
421)]
422/// Display the task log.
423async fn task_log(param: Value) -> Result<Value, Error> {
424
425 let upid = tools::required_string_param(&param, "upid")?;
426
427 let client = connect()?;
428
429 display_task_log(client, upid, true).await?;
430
431 Ok(Value::Null)
432}
433
434#[api(
435 input: {
436 properties: {
437 upid: {
438 schema: UPID_SCHEMA,
439 },
440 }
441 }
442)]
443/// Try to stop a specific task.
444async fn task_stop(param: Value) -> Result<Value, Error> {
445
446 let upid_str = tools::required_string_param(&param, "upid")?;
447
448 let mut client = connect()?;
449
450 let path = format!("api2/json/nodes/localhost/tasks/{}", upid_str);
451 let _ = client.delete(&path, None).await?;
452
453 Ok(Value::Null)
454}
455
456fn task_mgmt_cli() -> CommandLineInterface {
457
458 let task_log_cmd_def = CliCommand::new(&API_METHOD_TASK_LOG)
459 .arg_param(&["upid"]);
460
461 let task_stop_cmd_def = CliCommand::new(&API_METHOD_TASK_STOP)
462 .arg_param(&["upid"]);
463
464 let cmd_def = CliCommandMap::new()
465 .insert("list", CliCommand::new(&API_METHOD_TASK_LIST))
466 .insert("log", task_log_cmd_def)
467 .insert("stop", task_stop_cmd_def);
468
469 cmd_def.into()
470}
471
e739a8d8
DM
472fn x509name_to_string(name: &openssl::x509::X509NameRef) -> Result<String, Error> {
473 let mut parts = Vec::new();
474 for entry in name.entries() {
475 parts.push(format!("{} = {}", entry.object().nid().short_name()?, entry.data().as_utf8()?));
476 }
477 Ok(parts.join(", "))
478}
479
480#[api]
481/// Diplay node certificate information.
482fn cert_info() -> Result<(), Error> {
483
484 let cert_path = PathBuf::from(configdir!("/proxy.pem"));
485
486 let cert_pem = proxmox::tools::fs::file_get_contents(&cert_path)?;
487
488 let cert = openssl::x509::X509::from_pem(&cert_pem)?;
489
490 println!("Subject: {}", x509name_to_string(cert.subject_name())?);
491
492 if let Some(san) = cert.subject_alt_names() {
493 for name in san.iter() {
494 if let Some(v) = name.dnsname() {
495 println!(" DNS:{}", v);
496 } else if let Some(v) = name.ipaddress() {
497 println!(" IP:{:?}", v);
498 } else if let Some(v) = name.email() {
499 println!(" EMAIL:{}", v);
500 } else if let Some(v) = name.uri() {
501 println!(" URI:{}", v);
502 }
503 }
504 }
505
506 println!("Issuer: {}", x509name_to_string(cert.issuer_name())?);
507 println!("Validity:");
508 println!(" Not Before: {}", cert.not_before());
509 println!(" Not After : {}", cert.not_after());
510
511 let fp = cert.digest(openssl::hash::MessageDigest::sha256())?;
512 let fp_string = proxmox::tools::digest_to_hex(&fp);
513 let fp_string = fp_string.as_bytes().chunks(2).map(|v| std::str::from_utf8(v).unwrap())
514 .collect::<Vec<&str>>().join(":");
515
516 println!("Fingerprint (sha256): {}", fp_string);
517
518 let pubkey = cert.public_key()?;
519 println!("Public key type: {}", openssl::nid::Nid::from_raw(pubkey.id().as_raw()).long_name()?);
520 println!("Public key bits: {}", pubkey.bits());
521
522 Ok(())
523}
524
550e0d88
DM
525#[api(
526 input: {
527 properties: {
528 force: {
529 description: "Force generation of new SSL certifate.",
530 type: Boolean,
531 optional:true,
532 },
533 }
534 },
535)]
536/// Update node certificates and generate all needed files/directories.
537fn update_certs(force: Option<bool>) -> Result<(), Error> {
538
550e0d88
DM
539 config::create_configdir()?;
540
541 if let Err(err) = generate_auth_key() {
542 bail!("unable to generate auth key - {}", err);
543 }
544
545 if let Err(err) = generate_csrf_key() {
546 bail!("unable to generate csrf key - {}", err);
547 }
548
f8fd5095 549 config::update_self_signed_cert(force.unwrap_or(false))?;
550e0d88
DM
550
551 Ok(())
552}
553
554fn cert_mgmt_cli() -> CommandLineInterface {
555
550e0d88 556 let cmd_def = CliCommandMap::new()
e739a8d8
DM
557 .insert("info", CliCommand::new(&API_METHOD_CERT_INFO))
558 .insert("update", CliCommand::new(&API_METHOD_UPDATE_CERTS));
550e0d88
DM
559
560 cmd_def.into()
561}
562
4b4eba0b 563// fixme: avoid API redefinition
0eb0e024
DM
564#[api(
565 input: {
566 properties: {
eb506c83 567 "local-store": {
0eb0e024
DM
568 schema: DATASTORE_SCHEMA,
569 },
570 remote: {
167971ed 571 schema: REMOTE_ID_SCHEMA,
0eb0e024
DM
572 },
573 "remote-store": {
574 schema: DATASTORE_SCHEMA,
575 },
4b4eba0b
DM
576 delete: {
577 description: "Delete vanished backups. This remove the local copy if the remote backup was deleted.",
578 type: Boolean,
579 optional: true,
580 default: true,
581 },
0eb0e024
DM
582 "output-format": {
583 schema: OUTPUT_FORMAT,
584 optional: true,
585 },
586 }
587 }
588)]
eb506c83
DM
589/// Sync datastore from another repository
590async fn pull_datastore(
0eb0e024
DM
591 remote: String,
592 remote_store: String,
eb506c83 593 local_store: String,
4b4eba0b 594 delete: Option<bool>,
ac3faaf5 595 param: Value,
0eb0e024
DM
596) -> Result<Value, Error> {
597
ac3faaf5 598 let output_format = get_output_format(&param);
0eb0e024
DM
599
600 let mut client = connect()?;
601
4b4eba0b 602 let mut args = json!({
eb506c83 603 "store": local_store,
94609e23 604 "remote": remote,
0eb0e024 605 "remote-store": remote_store,
0eb0e024
DM
606 });
607
4b4eba0b
DM
608 if let Some(delete) = delete {
609 args["delete"] = delete.into();
610 }
611
eb506c83 612 let result = client.post("api2/json/pull", Some(args)).await?;
0eb0e024
DM
613
614 view_task_result(client, result, &output_format).await?;
615
616 Ok(Value::Null)
617}
618
211fabd7
DM
619fn main() {
620
6460764d 621 let cmd_def = CliCommandMap::new()
ed3e60ae 622 .insert("acl", acl_commands())
48ef3c33 623 .insert("datastore", datastore_commands())
ca0e5347 624 .insert("network", network_commands())
579728c6 625 .insert("user", user_commands())
f357390c 626 .insert("remote", remote_commands())
47d47121 627 .insert("garbage-collection", garbage_collection_commands())
550e0d88 628 .insert("cert", cert_mgmt_cli())
0eb0e024
DM
629 .insert("task", task_mgmt_cli())
630 .insert(
eb506c83
DM
631 "pull",
632 CliCommand::new(&API_METHOD_PULL_DATASTORE)
633 .arg_param(&["remote", "remote-store", "local-store"])
634 .completion_cb("local-store", config::datastore::complete_datastore_name)
f357390c 635 .completion_cb("remote", config::remote::complete_remote_name)
331b869d 636 .completion_cb("remote-store", complete_remote_datastore_name)
0eb0e024 637 );
34d3ba52 638
d08bc483 639 proxmox_backup::tools::runtime::main(run_async_cli_command(cmd_def));
ea0b8b6e 640}
331b869d
DM
641
642// shell completion helper
643pub fn complete_remote_datastore_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
644
645 let mut list = Vec::new();
646
9ea4bce4 647 let _ = proxmox::try_block!({
331b869d 648 let remote = param.get("remote").ok_or_else(|| format_err!("no remote"))?;
f357390c 649 let (remote_config, _digest) = remote::config()?;
331b869d
DM
650
651 let remote: Remote = remote_config.lookup("remote", &remote)?;
652
d59dbeca
DM
653 let options = HttpClientOptions::new()
654 .password(Some(remote.password.clone()))
655 .fingerprint(remote.fingerprint.clone());
656
331b869d
DM
657 let client = HttpClient::new(
658 &remote.host,
659 &remote.userid,
d59dbeca 660 options,
331b869d
DM
661 )?;
662
03ac286c 663 let result = crate::tools::runtime::block_on(client.get("api2/json/admin/datastore", None))?;
331b869d
DM
664
665 if let Some(data) = result["data"].as_array() {
666 for item in data {
667 if let Some(store) = item["store"].as_str() {
668 list.push(store.to_owned());
669 }
670 }
671 }
672
673 Ok(())
674 }).map_err(|_err: Error| { /* ignore */ });
675
676 list
677}