]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-manager.rs
start ACL api
[proxmox-backup.git] / src / bin / proxmox-backup-manager.rs
CommitLineData
550e0d88 1use std::path::PathBuf;
331b869d 2use std::collections::HashMap;
ea0b8b6e 3
9894469e
DM
4use failure::*;
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()
223 .insert("list", CliCommand::new(&&API_METHOD_LIST_ACLS));
224
225 cmd_def.into()
226}
227
9f6ab1fc 228fn datastore_commands() -> CommandLineInterface {
ea0b8b6e 229
6460764d 230 let cmd_def = CliCommandMap::new()
688fbe07 231 .insert("list", CliCommand::new(&api2::config::datastore::API_METHOD_LIST_DATASTORES))
6460764d 232 .insert("create",
688fbe07 233 CliCommand::new(&api2::config::datastore::API_METHOD_CREATE_DATASTORE)
49fddd98 234 .arg_param(&["name", "path"])
48ef3c33 235 )
ddc52662
DM
236 .insert("update",
237 CliCommand::new(&api2::config::datastore::API_METHOD_UPDATE_DATASTORE)
238 .arg_param(&["name"])
3be839c6 239 .completion_cb("name", config::datastore::complete_datastore_name)
ddc52662 240 )
6460764d 241 .insert("remove",
688fbe07 242 CliCommand::new(&api2::config::datastore::API_METHOD_DELETE_DATASTORE)
49fddd98 243 .arg_param(&["name"])
07b4694a 244 .completion_cb("name", config::datastore::complete_datastore_name)
48ef3c33 245 );
211fabd7 246
8f62336b 247 cmd_def.into()
211fabd7
DM
248}
249
691c89a0 250
769f8c99
DM
251#[api(
252 input: {
253 properties: {
254 store: {
255 schema: DATASTORE_SCHEMA,
256 },
257 "output-format": {
258 schema: OUTPUT_FORMAT,
259 optional: true,
260 },
261 }
262 }
263)]
264/// Start garbage collection for a specific datastore.
265async fn start_garbage_collection(param: Value) -> Result<Value, Error> {
691c89a0 266
ac3faaf5 267 let output_format = get_output_format(&param);
691c89a0 268
769f8c99
DM
269 let store = tools::required_string_param(&param, "store")?;
270
47d47121 271 let mut client = connect()?;
769f8c99
DM
272
273 let path = format!("api2/json/admin/datastore/{}/gc", store);
274
275 let result = client.post(&path, None).await?;
276
277 view_task_result(client, result, &output_format).await?;
278
279 Ok(Value::Null)
280}
281
282#[api(
283 input: {
284 properties: {
285 store: {
286 schema: DATASTORE_SCHEMA,
287 },
288 "output-format": {
289 schema: OUTPUT_FORMAT,
290 optional: true,
291 },
292 }
293 }
294)]
295/// Show garbage collection status for a specific datastore.
296async fn garbage_collection_status(param: Value) -> Result<Value, Error> {
297
ac3faaf5 298 let output_format = get_output_format(&param);
769f8c99
DM
299
300 let store = tools::required_string_param(&param, "store")?;
301
47d47121 302 let client = connect()?;
769f8c99
DM
303
304 let path = format!("api2/json/admin/datastore/{}/gc", store);
305
9894469e
DM
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;
309
ac3faaf5 310 let options = default_table_format_options();
9894469e
DM
311
312 format_and_print_result_full(&mut data, schema, &output_format, &options);
769f8c99
DM
313
314 Ok(Value::Null)
315}
316
317fn garbage_collection_commands() -> CommandLineInterface {
691c89a0
DM
318
319 let cmd_def = CliCommandMap::new()
320 .insert("status",
769f8c99 321 CliCommand::new(&API_METHOD_GARBAGE_COLLECTION_STATUS)
49fddd98 322 .arg_param(&["store"])
9ac1045c 323 .completion_cb("store", config::datastore::complete_datastore_name)
48ef3c33 324 )
691c89a0 325 .insert("start",
769f8c99 326 CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
49fddd98 327 .arg_param(&["store"])
9ac1045c 328 .completion_cb("store", config::datastore::complete_datastore_name)
48ef3c33 329 );
691c89a0
DM
330
331 cmd_def.into()
332}
333
47d47121
DM
334#[api(
335 input: {
336 properties: {
337 limit: {
338 description: "The maximal number of tasks to list.",
339 type: Integer,
340 optional: true,
341 minimum: 1,
342 maximum: 1000,
343 default: 50,
344 },
345 "output-format": {
346 schema: OUTPUT_FORMAT,
347 optional: true,
348 },
349 all: {
350 type: Boolean,
351 description: "Also list stopped tasks.",
352 optional: true,
353 }
354 }
355 }
356)]
357/// List running server tasks.
358async fn task_list(param: Value) -> Result<Value, Error> {
359
ac3faaf5 360 let output_format = get_output_format(&param);
47d47121
DM
361
362 let client = connect()?;
363
364 let limit = param["limit"].as_u64().unwrap_or(50) as usize;
365 let running = !param["all"].as_bool().unwrap_or(false);
366 let args = json!({
367 "running": running,
368 "start": 0,
369 "limit": limit,
370 });
9894469e 371 let mut result = client.get("api2/json/nodes/localhost/tasks", Some(args)).await?;
47d47121 372
9894469e
DM
373 let mut data = result["data"].take();
374 let schema = api2::node::tasks::API_RETURN_SCHEMA_LIST_TASKS;
47d47121 375
ac3faaf5 376 let options = default_table_format_options()
4939255f
DM
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))
93fbb4ef 379 .column(ColumnConfig::new("upid"))
4939255f 380 .column(ColumnConfig::new("status").renderer(tools::format::render_task_status));
9894469e
DM
381
382 format_and_print_result_full(&mut data, schema, &output_format, &options);
47d47121
DM
383
384 Ok(Value::Null)
385}
386
387#[api(
388 input: {
389 properties: {
390 upid: {
391 schema: UPID_SCHEMA,
392 },
393 }
394 }
395)]
396/// Display the task log.
397async fn task_log(param: Value) -> Result<Value, Error> {
398
399 let upid = tools::required_string_param(&param, "upid")?;
400
401 let client = connect()?;
402
403 display_task_log(client, upid, true).await?;
404
405 Ok(Value::Null)
406}
407
408#[api(
409 input: {
410 properties: {
411 upid: {
412 schema: UPID_SCHEMA,
413 },
414 }
415 }
416)]
417/// Try to stop a specific task.
418async fn task_stop(param: Value) -> Result<Value, Error> {
419
420 let upid_str = tools::required_string_param(&param, "upid")?;
421
422 let mut client = connect()?;
423
424 let path = format!("api2/json/nodes/localhost/tasks/{}", upid_str);
425 let _ = client.delete(&path, None).await?;
426
427 Ok(Value::Null)
428}
429
430fn task_mgmt_cli() -> CommandLineInterface {
431
432 let task_log_cmd_def = CliCommand::new(&API_METHOD_TASK_LOG)
433 .arg_param(&["upid"]);
434
435 let task_stop_cmd_def = CliCommand::new(&API_METHOD_TASK_STOP)
436 .arg_param(&["upid"]);
437
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);
442
443 cmd_def.into()
444}
445
e739a8d8
DM
446fn 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()?));
450 }
451 Ok(parts.join(", "))
452}
453
454#[api]
455/// Diplay node certificate information.
456fn cert_info() -> Result<(), Error> {
457
458 let cert_path = PathBuf::from(configdir!("/proxy.pem"));
459
460 let cert_pem = proxmox::tools::fs::file_get_contents(&cert_path)?;
461
462 let cert = openssl::x509::X509::from_pem(&cert_pem)?;
463
464 println!("Subject: {}", x509name_to_string(cert.subject_name())?);
465
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);
476 }
477 }
478 }
479
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());
484
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(":");
489
490 println!("Fingerprint (sha256): {}", fp_string);
491
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());
495
496 Ok(())
497}
498
550e0d88
DM
499#[api(
500 input: {
501 properties: {
502 force: {
503 description: "Force generation of new SSL certifate.",
504 type: Boolean,
505 optional:true,
506 },
507 }
508 },
509)]
510/// Update node certificates and generate all needed files/directories.
511fn update_certs(force: Option<bool>) -> Result<(), Error> {
512
550e0d88
DM
513 config::create_configdir()?;
514
515 if let Err(err) = generate_auth_key() {
516 bail!("unable to generate auth key - {}", err);
517 }
518
519 if let Err(err) = generate_csrf_key() {
520 bail!("unable to generate csrf key - {}", err);
521 }
522
f8fd5095 523 config::update_self_signed_cert(force.unwrap_or(false))?;
550e0d88
DM
524
525 Ok(())
526}
527
528fn cert_mgmt_cli() -> CommandLineInterface {
529
550e0d88 530 let cmd_def = CliCommandMap::new()
e739a8d8
DM
531 .insert("info", CliCommand::new(&API_METHOD_CERT_INFO))
532 .insert("update", CliCommand::new(&API_METHOD_UPDATE_CERTS));
550e0d88
DM
533
534 cmd_def.into()
535}
536
4b4eba0b 537// fixme: avoid API redefinition
0eb0e024
DM
538#[api(
539 input: {
540 properties: {
eb506c83 541 "local-store": {
0eb0e024
DM
542 schema: DATASTORE_SCHEMA,
543 },
544 remote: {
167971ed 545 schema: REMOTE_ID_SCHEMA,
0eb0e024
DM
546 },
547 "remote-store": {
548 schema: DATASTORE_SCHEMA,
549 },
4b4eba0b
DM
550 delete: {
551 description: "Delete vanished backups. This remove the local copy if the remote backup was deleted.",
552 type: Boolean,
553 optional: true,
554 default: true,
555 },
0eb0e024
DM
556 "output-format": {
557 schema: OUTPUT_FORMAT,
558 optional: true,
559 },
560 }
561 }
562)]
eb506c83
DM
563/// Sync datastore from another repository
564async fn pull_datastore(
0eb0e024
DM
565 remote: String,
566 remote_store: String,
eb506c83 567 local_store: String,
4b4eba0b 568 delete: Option<bool>,
ac3faaf5 569 param: Value,
0eb0e024
DM
570) -> Result<Value, Error> {
571
ac3faaf5 572 let output_format = get_output_format(&param);
0eb0e024
DM
573
574 let mut client = connect()?;
575
4b4eba0b 576 let mut args = json!({
eb506c83 577 "store": local_store,
94609e23 578 "remote": remote,
0eb0e024 579 "remote-store": remote_store,
0eb0e024
DM
580 });
581
4b4eba0b
DM
582 if let Some(delete) = delete {
583 args["delete"] = delete.into();
584 }
585
eb506c83 586 let result = client.post("api2/json/pull", Some(args)).await?;
0eb0e024
DM
587
588 view_task_result(client, result, &output_format).await?;
589
590 Ok(Value::Null)
591}
592
211fabd7
DM
593fn main() {
594
6460764d 595 let cmd_def = CliCommandMap::new()
ed3e60ae 596 .insert("acl", acl_commands())
48ef3c33 597 .insert("datastore", datastore_commands())
579728c6 598 .insert("user", user_commands())
f357390c 599 .insert("remote", remote_commands())
47d47121 600 .insert("garbage-collection", garbage_collection_commands())
550e0d88 601 .insert("cert", cert_mgmt_cli())
0eb0e024
DM
602 .insert("task", task_mgmt_cli())
603 .insert(
eb506c83
DM
604 "pull",
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)
f357390c 608 .completion_cb("remote", config::remote::complete_remote_name)
331b869d 609 .completion_cb("remote-store", complete_remote_datastore_name)
0eb0e024 610 );
34d3ba52 611
d08bc483 612 proxmox_backup::tools::runtime::main(run_async_cli_command(cmd_def));
ea0b8b6e 613}
331b869d
DM
614
615// shell completion helper
616pub fn complete_remote_datastore_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
617
618 let mut list = Vec::new();
619
9ea4bce4 620 let _ = proxmox::try_block!({
331b869d 621 let remote = param.get("remote").ok_or_else(|| format_err!("no remote"))?;
f357390c 622 let (remote_config, _digest) = remote::config()?;
331b869d
DM
623
624 let remote: Remote = remote_config.lookup("remote", &remote)?;
625
d59dbeca
DM
626 let options = HttpClientOptions::new()
627 .password(Some(remote.password.clone()))
628 .fingerprint(remote.fingerprint.clone());
629
331b869d
DM
630 let client = HttpClient::new(
631 &remote.host,
632 &remote.userid,
d59dbeca 633 options,
331b869d
DM
634 )?;
635
03ac286c 636 let result = crate::tools::runtime::block_on(client.get("api2/json/admin/datastore", None))?;
331b869d
DM
637
638 if let Some(data) = result["data"].as_array() {
639 for item in data {
640 if let Some(store) = item["store"].as_str() {
641 list.push(store.to_owned());
642 }
643 }
644 }
645
646 Ok(())
647 }).map_err(|_err: Error| { /* ignore */ });
648
649 list
650}