1 use std
::path
::PathBuf
;
2 use std
::collections
::HashMap
;
4 use anyhow
::{bail, format_err, Error}
;
5 use serde_json
::{json, Value}
;
7 use proxmox
::api
::{api, cli::*, RpcEnvironment, ApiHandler}
;
9 use proxmox_backup
::configdir
;
10 use proxmox_backup
::tools
;
11 use proxmox_backup
::config
::{self, remote::{self, Remote}
};
12 use proxmox_backup
::api2
::{self, types::* }
;
13 use proxmox_backup
::client
::*;
14 use proxmox_backup
::tools
::ticket
::*;
15 use proxmox_backup
::auth_helpers
::*;
17 async
fn view_task_result(
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?
;
28 format_and_print_result(&data
, &output_format
);
34 fn connect() -> Result
<HttpClient
, Error
> {
36 let uid
= nix
::unistd
::Uid
::current();
38 let mut options
= HttpClientOptions
::new()
39 .prefix(Some("proxmox-backup".to_string()))
40 .verify_cert(false); // not required for connection to localhost
42 let client
= if uid
.is_root() {
43 let ticket
= assemble_rsa_ticket(private_auth_key(), "PBS", Some("root@pam"), None
)?
;
44 options
= options
.password(Some(ticket
));
45 HttpClient
::new("localhost", "root@pam", options
)?
47 options
= options
.ticket_cache(true).interactive(true);
48 HttpClient
::new("localhost", "root@pam", options
)?
58 schema
: OUTPUT_FORMAT
,
64 /// List configured remotes.
65 fn list_remotes(param
: Value
, rpcenv
: &mut dyn RpcEnvironment
) -> Result
<Value
, Error
> {
67 let output_format
= get_output_format(¶m
);
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
)?
,
75 let options
= default_table_format_options()
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"));
82 format_and_print_result_full(&mut data
, info
.returns
, &output_format
, &options
);
87 fn remote_commands() -> CommandLineInterface
{
89 let cmd_def
= CliCommandMap
::new()
90 .insert("list", CliCommand
::new(&&API_METHOD_LIST_REMOTES
))
93 // fixme: howto handle password parameter?
94 CliCommand
::new(&api2
::config
::remote
::API_METHOD_CREATE_REMOTE
)
99 CliCommand
::new(&api2
::config
::remote
::API_METHOD_UPDATE_REMOTE
)
100 .arg_param(&["name"])
101 .completion_cb("name", config
::remote
::complete_remote_name
)
105 CliCommand
::new(&api2
::config
::remote
::API_METHOD_DELETE_REMOTE
)
106 .arg_param(&["name"])
107 .completion_cb("name", config
::remote
::complete_remote_name
)
117 schema
: OUTPUT_FORMAT
,
123 /// List configured users.
124 fn list_users(param
: Value
, rpcenv
: &mut dyn RpcEnvironment
) -> Result
<Value
, Error
> {
126 let output_format
= get_output_format(¶m
);
128 let info
= &api2
::access
::user
::API_METHOD_LIST_USERS
;
129 let mut data
= match info
.handler
{
130 ApiHandler
::Sync(handler
) => (handler
)(param
, info
, rpcenv
)?
,
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"));
143 format_and_print_result_full(&mut data
, info
.returns
, &output_format
, &options
);
148 fn user_commands() -> CommandLineInterface
{
150 let cmd_def
= CliCommandMap
::new()
151 .insert("list", CliCommand
::new(&&API_METHOD_LIST_USERS
))
154 // fixme: howto handle password parameter?
155 CliCommand
::new(&api2
::access
::user
::API_METHOD_CREATE_USER
)
156 .arg_param(&["userid"])
160 CliCommand
::new(&api2
::access
::user
::API_METHOD_UPDATE_USER
)
161 .arg_param(&["userid"])
162 .completion_cb("userid", config
::user
::complete_user_name
)
166 CliCommand
::new(&api2
::access
::user
::API_METHOD_DELETE_USER
)
167 .arg_param(&["userid"])
168 .completion_cb("userid", config
::user
::complete_user_name
)
178 schema
: OUTPUT_FORMAT
,
184 /// Access Control list.
185 fn list_acls(param
: Value
, rpcenv
: &mut dyn RpcEnvironment
) -> Result
<Value
, Error
> {
187 let output_format
= get_output_format(¶m
);
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
)?
,
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();
200 if ugid_type
== "user" {
202 } else if ugid_type
== "group" {
203 Ok(format
!("@{}", ugid
))
205 bail
!("render_ugid: got unknown ugid_type");
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"));
215 format_and_print_result_full(&mut data
, info
.returns
, &output_format
, &options
);
220 fn acl_commands() -> CommandLineInterface
{
222 let cmd_def
= CliCommandMap
::new()
223 .insert("list", CliCommand
::new(&&API_METHOD_LIST_ACLS
))
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
)
240 schema
: OUTPUT_FORMAT
,
246 /// Network device list.
247 fn list_network_devices(param
: Value
, rpcenv
: &mut dyn RpcEnvironment
) -> Result
<Value
, Error
> {
249 let output_format
= get_output_format(¶m
);
251 let info
= &api2
::config
::network
::API_METHOD_LIST_NETWORK_DEVICES
;
252 let mut data
= match info
.handler
{
253 ApiHandler
::Sync(handler
) => (handler
)(param
, info
, rpcenv
)?
,
257 let options
= default_table_format_options()
258 .column(ColumnConfig
::new("name"))
259 .column(ColumnConfig
::new("auto"))
260 .column(ColumnConfig
::new("method_v4"))
261 .column(ColumnConfig
::new("method_v6"))
262 .column(ColumnConfig
::new("cidr_v4"))
263 .column(ColumnConfig
::new("gateway_v4"))
264 .column(ColumnConfig
::new("cidr_v6"))
265 .column(ColumnConfig
::new("gateway_v6"))
268 format_and_print_result_full(&mut data
, info
.returns
, &output_format
, &options
);
273 fn network_commands() -> CommandLineInterface
{
275 let cmd_def
= CliCommandMap
::new()
276 .insert("list", CliCommand
::new(&API_METHOD_LIST_NETWORK_DEVICES
))
278 CliCommand
::new(&api2
::config
::network
::API_METHOD_UPDATE_INTERFACE
)
279 .arg_param(&["name"])
280 .completion_cb("name", config
::network
::complete_interface_name
)
283 CliCommand
::new(&api2
::config
::network
::API_METHOD_DELETE_INTERFACE
)
284 .arg_param(&["name"])
285 .completion_cb("name", config
::network
::complete_interface_name
)
295 schema
: OUTPUT_FORMAT
,
302 fn list_datastores(param
: Value
, rpcenv
: &mut dyn RpcEnvironment
) -> Result
<Value
, Error
> {
304 let output_format
= get_output_format(¶m
);
306 let info
= &api2
::config
::datastore
::API_METHOD_LIST_DATASTORES
;
307 let mut data
= match info
.handler
{
308 ApiHandler
::Sync(handler
) => (handler
)(param
, info
, rpcenv
)?
,
312 let options
= default_table_format_options()
313 .column(ColumnConfig
::new("name"))
314 .column(ColumnConfig
::new("path"))
315 .column(ColumnConfig
::new("comment"));
317 format_and_print_result_full(&mut data
, info
.returns
, &output_format
, &options
);
322 fn datastore_commands() -> CommandLineInterface
{
324 let cmd_def
= CliCommandMap
::new()
325 .insert("list", CliCommand
::new(&API_METHOD_LIST_DATASTORES
))
327 CliCommand
::new(&api2
::config
::datastore
::API_METHOD_CREATE_DATASTORE
)
328 .arg_param(&["name", "path"])
331 CliCommand
::new(&api2
::config
::datastore
::API_METHOD_UPDATE_DATASTORE
)
332 .arg_param(&["name"])
333 .completion_cb("name", config
::datastore
::complete_datastore_name
)
336 CliCommand
::new(&api2
::config
::datastore
::API_METHOD_DELETE_DATASTORE
)
337 .arg_param(&["name"])
338 .completion_cb("name", config
::datastore
::complete_datastore_name
)
349 schema
: DATASTORE_SCHEMA
,
352 schema
: OUTPUT_FORMAT
,
358 /// Start garbage collection for a specific datastore.
359 async
fn start_garbage_collection(param
: Value
) -> Result
<Value
, Error
> {
361 let output_format
= get_output_format(¶m
);
363 let store
= tools
::required_string_param(¶m
, "store")?
;
365 let mut client
= connect()?
;
367 let path
= format
!("api2/json/admin/datastore/{}/gc", store
);
369 let result
= client
.post(&path
, None
).await?
;
371 view_task_result(client
, result
, &output_format
).await?
;
380 schema
: DATASTORE_SCHEMA
,
383 schema
: OUTPUT_FORMAT
,
389 /// Show garbage collection status for a specific datastore.
390 async
fn garbage_collection_status(param
: Value
) -> Result
<Value
, Error
> {
392 let output_format
= get_output_format(¶m
);
394 let store
= tools
::required_string_param(¶m
, "store")?
;
396 let client
= connect()?
;
398 let path
= format
!("api2/json/admin/datastore/{}/gc", store
);
400 let mut result
= client
.get(&path
, None
).await?
;
401 let mut data
= result
["data"].take();
402 let schema
= api2
::admin
::datastore
::API_RETURN_SCHEMA_GARBAGE_COLLECTION_STATUS
;
404 let options
= default_table_format_options();
406 format_and_print_result_full(&mut data
, schema
, &output_format
, &options
);
411 fn garbage_collection_commands() -> CommandLineInterface
{
413 let cmd_def
= CliCommandMap
::new()
415 CliCommand
::new(&API_METHOD_GARBAGE_COLLECTION_STATUS
)
416 .arg_param(&["store"])
417 .completion_cb("store", config
::datastore
::complete_datastore_name
)
420 CliCommand
::new(&API_METHOD_START_GARBAGE_COLLECTION
)
421 .arg_param(&["store"])
422 .completion_cb("store", config
::datastore
::complete_datastore_name
)
432 description
: "The maximal number of tasks to list.",
440 schema
: OUTPUT_FORMAT
,
445 description
: "Also list stopped tasks.",
451 /// List running server tasks.
452 async
fn task_list(param
: Value
) -> Result
<Value
, Error
> {
454 let output_format
= get_output_format(¶m
);
456 let client
= connect()?
;
458 let limit
= param
["limit"].as_u64().unwrap_or(50) as usize;
459 let running
= !param
["all"].as_bool().unwrap_or(false);
465 let mut result
= client
.get("api2/json/nodes/localhost/tasks", Some(args
)).await?
;
467 let mut data
= result
["data"].take();
468 let schema
= api2
::node
::tasks
::API_RETURN_SCHEMA_LIST_TASKS
;
470 let options
= default_table_format_options()
471 .column(ColumnConfig
::new("starttime").right_align(false).renderer(tools
::format
::render_epoch
))
472 .column(ColumnConfig
::new("endtime").right_align(false).renderer(tools
::format
::render_epoch
))
473 .column(ColumnConfig
::new("upid"))
474 .column(ColumnConfig
::new("status").renderer(tools
::format
::render_task_status
));
476 format_and_print_result_full(&mut data
, schema
, &output_format
, &options
);
490 /// Display the task log.
491 async
fn task_log(param
: Value
) -> Result
<Value
, Error
> {
493 let upid
= tools
::required_string_param(¶m
, "upid")?
;
495 let client
= connect()?
;
497 display_task_log(client
, upid
, true).await?
;
511 /// Try to stop a specific task.
512 async
fn task_stop(param
: Value
) -> Result
<Value
, Error
> {
514 let upid_str
= tools
::required_string_param(¶m
, "upid")?
;
516 let mut client
= connect()?
;
518 let path
= format
!("api2/json/nodes/localhost/tasks/{}", upid_str
);
519 let _
= client
.delete(&path
, None
).await?
;
524 fn task_mgmt_cli() -> CommandLineInterface
{
526 let task_log_cmd_def
= CliCommand
::new(&API_METHOD_TASK_LOG
)
527 .arg_param(&["upid"]);
529 let task_stop_cmd_def
= CliCommand
::new(&API_METHOD_TASK_STOP
)
530 .arg_param(&["upid"]);
532 let cmd_def
= CliCommandMap
::new()
533 .insert("list", CliCommand
::new(&API_METHOD_TASK_LIST
))
534 .insert("log", task_log_cmd_def
)
535 .insert("stop", task_stop_cmd_def
);
540 fn x509name_to_string(name
: &openssl
::x509
::X509NameRef
) -> Result
<String
, Error
> {
541 let mut parts
= Vec
::new();
542 for entry
in name
.entries() {
543 parts
.push(format
!("{} = {}", entry
.object().nid().short_name()?
, entry
.data().as_utf8()?
));
549 /// Diplay node certificate information.
550 fn cert_info() -> Result
<(), Error
> {
552 let cert_path
= PathBuf
::from(configdir
!("/proxy.pem"));
554 let cert_pem
= proxmox
::tools
::fs
::file_get_contents(&cert_path
)?
;
556 let cert
= openssl
::x509
::X509
::from_pem(&cert_pem
)?
;
558 println
!("Subject: {}", x509name_to_string(cert
.subject_name())?
);
560 if let Some(san
) = cert
.subject_alt_names() {
561 for name
in san
.iter() {
562 if let Some(v
) = name
.dnsname() {
563 println
!(" DNS:{}", v
);
564 } else if let Some(v
) = name
.ipaddress() {
565 println
!(" IP:{:?}", v
);
566 } else if let Some(v
) = name
.email() {
567 println
!(" EMAIL:{}", v
);
568 } else if let Some(v
) = name
.uri() {
569 println
!(" URI:{}", v
);
574 println
!("Issuer: {}", x509name_to_string(cert
.issuer_name())?
);
575 println
!("Validity:");
576 println
!(" Not Before: {}", cert
.not_before());
577 println
!(" Not After : {}", cert
.not_after());
579 let fp
= cert
.digest(openssl
::hash
::MessageDigest
::sha256())?
;
580 let fp_string
= proxmox
::tools
::digest_to_hex(&fp
);
581 let fp_string
= fp_string
.as_bytes().chunks(2).map(|v
| std
::str::from_utf8(v
).unwrap())
582 .collect
::<Vec
<&str>>().join(":");
584 println
!("Fingerprint (sha256): {}", fp_string
);
586 let pubkey
= cert
.public_key()?
;
587 println
!("Public key type: {}", openssl
::nid
::Nid
::from_raw(pubkey
.id().as_raw()).long_name()?
);
588 println
!("Public key bits: {}", pubkey
.bits());
597 description
: "Force generation of new SSL certifate.",
604 /// Update node certificates and generate all needed files/directories.
605 fn update_certs(force
: Option
<bool
>) -> Result
<(), Error
> {
607 config
::create_configdir()?
;
609 if let Err(err
) = generate_auth_key() {
610 bail
!("unable to generate auth key - {}", err
);
613 if let Err(err
) = generate_csrf_key() {
614 bail
!("unable to generate csrf key - {}", err
);
617 config
::update_self_signed_cert(force
.unwrap_or(false))?
;
622 fn cert_mgmt_cli() -> CommandLineInterface
{
624 let cmd_def
= CliCommandMap
::new()
625 .insert("info", CliCommand
::new(&API_METHOD_CERT_INFO
))
626 .insert("update", CliCommand
::new(&API_METHOD_UPDATE_CERTS
));
631 // fixme: avoid API redefinition
636 schema
: DATASTORE_SCHEMA
,
639 schema
: REMOTE_ID_SCHEMA
,
642 schema
: DATASTORE_SCHEMA
,
645 description
: "Delete vanished backups. This remove the local copy if the remote backup was deleted.",
651 schema
: OUTPUT_FORMAT
,
657 /// Sync datastore from another repository
658 async
fn pull_datastore(
660 remote_store
: String
,
662 delete
: Option
<bool
>,
664 ) -> Result
<Value
, Error
> {
666 let output_format
= get_output_format(¶m
);
668 let mut client
= connect()?
;
670 let mut args
= json
!({
671 "store": local_store
,
673 "remote-store": remote_store
,
676 if let Some(delete
) = delete
{
677 args
["delete"] = delete
.into();
680 let result
= client
.post("api2/json/pull", Some(args
)).await?
;
682 view_task_result(client
, result
, &output_format
).await?
;
689 let cmd_def
= CliCommandMap
::new()
690 .insert("acl", acl_commands())
691 .insert("datastore", datastore_commands())
692 .insert("network", network_commands())
693 .insert("user", user_commands())
694 .insert("remote", remote_commands())
695 .insert("garbage-collection", garbage_collection_commands())
696 .insert("cert", cert_mgmt_cli())
697 .insert("task", task_mgmt_cli())
700 CliCommand
::new(&API_METHOD_PULL_DATASTORE
)
701 .arg_param(&["remote", "remote-store", "local-store"])
702 .completion_cb("local-store", config
::datastore
::complete_datastore_name
)
703 .completion_cb("remote", config
::remote
::complete_remote_name
)
704 .completion_cb("remote-store", complete_remote_datastore_name
)
707 proxmox_backup
::tools
::runtime
::main(run_async_cli_command(cmd_def
));
710 // shell completion helper
711 pub fn complete_remote_datastore_name(_arg
: &str, param
: &HashMap
<String
, String
>) -> Vec
<String
> {
713 let mut list
= Vec
::new();
715 let _
= proxmox
::try_block
!({
716 let remote
= param
.get("remote").ok_or_else(|| format_err
!("no remote"))?
;
717 let (remote_config
, _digest
) = remote
::config()?
;
719 let remote
: Remote
= remote_config
.lookup("remote", &remote
)?
;
721 let options
= HttpClientOptions
::new()
722 .password(Some(remote
.password
.clone()))
723 .fingerprint(remote
.fingerprint
.clone());
725 let client
= HttpClient
::new(
731 let result
= crate::tools
::runtime
::block_on(client
.get("api2/json/admin/datastore", None
))?
;
733 if let Some(data
) = result
["data"].as_array() {
735 if let Some(store
) = item
["store"].as_str() {
736 list
.push(store
.to_owned());
742 }).map_err(|_err
: Error
| { /* ignore */ }
);