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