1 use std
::path
::PathBuf
;
2 use std
::collections
::HashMap
;
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
));
228 fn datastore_commands() -> CommandLineInterface
{
230 let cmd_def
= CliCommandMap
::new()
231 .insert("list", CliCommand
::new(&api2
::config
::datastore
::API_METHOD_LIST_DATASTORES
))
233 CliCommand
::new(&api2
::config
::datastore
::API_METHOD_CREATE_DATASTORE
)
234 .arg_param(&["name", "path"])
237 CliCommand
::new(&api2
::config
::datastore
::API_METHOD_UPDATE_DATASTORE
)
238 .arg_param(&["name"])
239 .completion_cb("name", config
::datastore
::complete_datastore_name
)
242 CliCommand
::new(&api2
::config
::datastore
::API_METHOD_DELETE_DATASTORE
)
243 .arg_param(&["name"])
244 .completion_cb("name", config
::datastore
::complete_datastore_name
)
255 schema
: DATASTORE_SCHEMA
,
258 schema
: OUTPUT_FORMAT
,
264 /// Start garbage collection for a specific datastore.
265 async
fn start_garbage_collection(param
: Value
) -> Result
<Value
, Error
> {
267 let output_format
= get_output_format(¶m
);
269 let store
= tools
::required_string_param(¶m
, "store")?
;
271 let mut client
= connect()?
;
273 let path
= format
!("api2/json/admin/datastore/{}/gc", store
);
275 let result
= client
.post(&path
, None
).await?
;
277 view_task_result(client
, result
, &output_format
).await?
;
286 schema
: DATASTORE_SCHEMA
,
289 schema
: OUTPUT_FORMAT
,
295 /// Show garbage collection status for a specific datastore.
296 async
fn garbage_collection_status(param
: Value
) -> Result
<Value
, Error
> {
298 let output_format
= get_output_format(¶m
);
300 let store
= tools
::required_string_param(¶m
, "store")?
;
302 let client
= connect()?
;
304 let path
= format
!("api2/json/admin/datastore/{}/gc", store
);
306 let mut result
= client
.get(&path
, None
).await?
;
307 let mut data
= result
["data"].take();
308 let schema
= api2
::admin
::datastore
::API_RETURN_SCHEMA_GARBAGE_COLLECTION_STATUS
;
310 let options
= default_table_format_options();
312 format_and_print_result_full(&mut data
, schema
, &output_format
, &options
);
317 fn garbage_collection_commands() -> CommandLineInterface
{
319 let cmd_def
= CliCommandMap
::new()
321 CliCommand
::new(&API_METHOD_GARBAGE_COLLECTION_STATUS
)
322 .arg_param(&["store"])
323 .completion_cb("store", config
::datastore
::complete_datastore_name
)
326 CliCommand
::new(&API_METHOD_START_GARBAGE_COLLECTION
)
327 .arg_param(&["store"])
328 .completion_cb("store", config
::datastore
::complete_datastore_name
)
338 description
: "The maximal number of tasks to list.",
346 schema
: OUTPUT_FORMAT
,
351 description
: "Also list stopped tasks.",
357 /// List running server tasks.
358 async
fn task_list(param
: Value
) -> Result
<Value
, Error
> {
360 let output_format
= get_output_format(¶m
);
362 let client
= connect()?
;
364 let limit
= param
["limit"].as_u64().unwrap_or(50) as usize;
365 let running
= !param
["all"].as_bool().unwrap_or(false);
371 let mut result
= client
.get("api2/json/nodes/localhost/tasks", Some(args
)).await?
;
373 let mut data
= result
["data"].take();
374 let schema
= api2
::node
::tasks
::API_RETURN_SCHEMA_LIST_TASKS
;
376 let options
= default_table_format_options()
377 .column(ColumnConfig
::new("starttime").right_align(false).renderer(tools
::format
::render_epoch
))
378 .column(ColumnConfig
::new("endtime").right_align(false).renderer(tools
::format
::render_epoch
))
379 .column(ColumnConfig
::new("upid"))
380 .column(ColumnConfig
::new("status").renderer(tools
::format
::render_task_status
));
382 format_and_print_result_full(&mut data
, schema
, &output_format
, &options
);
396 /// Display the task log.
397 async
fn task_log(param
: Value
) -> Result
<Value
, Error
> {
399 let upid
= tools
::required_string_param(¶m
, "upid")?
;
401 let client
= connect()?
;
403 display_task_log(client
, upid
, true).await?
;
417 /// Try to stop a specific task.
418 async
fn task_stop(param
: Value
) -> Result
<Value
, Error
> {
420 let upid_str
= tools
::required_string_param(¶m
, "upid")?
;
422 let mut client
= connect()?
;
424 let path
= format
!("api2/json/nodes/localhost/tasks/{}", upid_str
);
425 let _
= client
.delete(&path
, None
).await?
;
430 fn task_mgmt_cli() -> CommandLineInterface
{
432 let task_log_cmd_def
= CliCommand
::new(&API_METHOD_TASK_LOG
)
433 .arg_param(&["upid"]);
435 let task_stop_cmd_def
= CliCommand
::new(&API_METHOD_TASK_STOP
)
436 .arg_param(&["upid"]);
438 let cmd_def
= CliCommandMap
::new()
439 .insert("list", CliCommand
::new(&API_METHOD_TASK_LIST
))
440 .insert("log", task_log_cmd_def
)
441 .insert("stop", task_stop_cmd_def
);
446 fn x509name_to_string(name
: &openssl
::x509
::X509NameRef
) -> Result
<String
, Error
> {
447 let mut parts
= Vec
::new();
448 for entry
in name
.entries() {
449 parts
.push(format
!("{} = {}", entry
.object().nid().short_name()?
, entry
.data().as_utf8()?
));
455 /// Diplay node certificate information.
456 fn cert_info() -> Result
<(), Error
> {
458 let cert_path
= PathBuf
::from(configdir
!("/proxy.pem"));
460 let cert_pem
= proxmox
::tools
::fs
::file_get_contents(&cert_path
)?
;
462 let cert
= openssl
::x509
::X509
::from_pem(&cert_pem
)?
;
464 println
!("Subject: {}", x509name_to_string(cert
.subject_name())?
);
466 if let Some(san
) = cert
.subject_alt_names() {
467 for name
in san
.iter() {
468 if let Some(v
) = name
.dnsname() {
469 println
!(" DNS:{}", v
);
470 } else if let Some(v
) = name
.ipaddress() {
471 println
!(" IP:{:?}", v
);
472 } else if let Some(v
) = name
.email() {
473 println
!(" EMAIL:{}", v
);
474 } else if let Some(v
) = name
.uri() {
475 println
!(" URI:{}", v
);
480 println
!("Issuer: {}", x509name_to_string(cert
.issuer_name())?
);
481 println
!("Validity:");
482 println
!(" Not Before: {}", cert
.not_before());
483 println
!(" Not After : {}", cert
.not_after());
485 let fp
= cert
.digest(openssl
::hash
::MessageDigest
::sha256())?
;
486 let fp_string
= proxmox
::tools
::digest_to_hex(&fp
);
487 let fp_string
= fp_string
.as_bytes().chunks(2).map(|v
| std
::str::from_utf8(v
).unwrap())
488 .collect
::<Vec
<&str>>().join(":");
490 println
!("Fingerprint (sha256): {}", fp_string
);
492 let pubkey
= cert
.public_key()?
;
493 println
!("Public key type: {}", openssl
::nid
::Nid
::from_raw(pubkey
.id().as_raw()).long_name()?
);
494 println
!("Public key bits: {}", pubkey
.bits());
503 description
: "Force generation of new SSL certifate.",
510 /// Update node certificates and generate all needed files/directories.
511 fn update_certs(force
: Option
<bool
>) -> Result
<(), Error
> {
513 config
::create_configdir()?
;
515 if let Err(err
) = generate_auth_key() {
516 bail
!("unable to generate auth key - {}", err
);
519 if let Err(err
) = generate_csrf_key() {
520 bail
!("unable to generate csrf key - {}", err
);
523 config
::update_self_signed_cert(force
.unwrap_or(false))?
;
528 fn cert_mgmt_cli() -> CommandLineInterface
{
530 let cmd_def
= CliCommandMap
::new()
531 .insert("info", CliCommand
::new(&API_METHOD_CERT_INFO
))
532 .insert("update", CliCommand
::new(&API_METHOD_UPDATE_CERTS
));
537 // fixme: avoid API redefinition
542 schema
: DATASTORE_SCHEMA
,
545 schema
: REMOTE_ID_SCHEMA
,
548 schema
: DATASTORE_SCHEMA
,
551 description
: "Delete vanished backups. This remove the local copy if the remote backup was deleted.",
557 schema
: OUTPUT_FORMAT
,
563 /// Sync datastore from another repository
564 async
fn pull_datastore(
566 remote_store
: String
,
568 delete
: Option
<bool
>,
570 ) -> Result
<Value
, Error
> {
572 let output_format
= get_output_format(¶m
);
574 let mut client
= connect()?
;
576 let mut args
= json
!({
577 "store": local_store
,
579 "remote-store": remote_store
,
582 if let Some(delete
) = delete
{
583 args
["delete"] = delete
.into();
586 let result
= client
.post("api2/json/pull", Some(args
)).await?
;
588 view_task_result(client
, result
, &output_format
).await?
;
595 let cmd_def
= CliCommandMap
::new()
596 .insert("acl", acl_commands())
597 .insert("datastore", datastore_commands())
598 .insert("user", user_commands())
599 .insert("remote", remote_commands())
600 .insert("garbage-collection", garbage_collection_commands())
601 .insert("cert", cert_mgmt_cli())
602 .insert("task", task_mgmt_cli())
605 CliCommand
::new(&API_METHOD_PULL_DATASTORE
)
606 .arg_param(&["remote", "remote-store", "local-store"])
607 .completion_cb("local-store", config
::datastore
::complete_datastore_name
)
608 .completion_cb("remote", config
::remote
::complete_remote_name
)
609 .completion_cb("remote-store", complete_remote_datastore_name
)
612 proxmox_backup
::tools
::runtime
::main(run_async_cli_command(cmd_def
));
615 // shell completion helper
616 pub fn complete_remote_datastore_name(_arg
: &str, param
: &HashMap
<String
, String
>) -> Vec
<String
> {
618 let mut list
= Vec
::new();
620 let _
= proxmox
::try_block
!({
621 let remote
= param
.get("remote").ok_or_else(|| format_err
!("no remote"))?
;
622 let (remote_config
, _digest
) = remote
::config()?
;
624 let remote
: Remote
= remote_config
.lookup("remote", &remote
)?
;
626 let options
= HttpClientOptions
::new()
627 .password(Some(remote
.password
.clone()))
628 .fingerprint(remote
.fingerprint
.clone());
630 let client
= HttpClient
::new(
636 let result
= crate::tools
::runtime
::block_on(client
.get("api2/json/admin/datastore", None
))?
;
638 if let Some(data
) = result
["data"].as_array() {
640 if let Some(store
) = item
["store"].as_str() {
641 list
.push(store
.to_owned());
647 }).map_err(|_err
: Error
| { /* ignore */ }
);