]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-manager.rs
WorkerTaskContext: add shutdown_requested() and fail_on_shutdown()
[proxmox-backup.git] / src / bin / proxmox-backup-manager.rs
CommitLineData
331b869d 1use std::collections::HashMap;
941342f7 2use std::io::{self, Write};
ea0b8b6e 3
b29d046e 4use anyhow::{format_err, Error};
9894469e 5use serde_json::{json, Value};
9894469e 6
380bd7df 7use proxmox::api::{api, cli::*, RpcEnvironment};
ae18c436 8use proxmox::tools::fs::CreateOptions;
769f8c99 9
2b7f8dd5 10use pbs_client::{connect_to_localhost, display_task_log, view_task_result};
4805edc4 11use pbs_tools::percent_encoding::percent_encode_component;
3c8c2827 12use pbs_tools::json::required_string_param;
6227654a
DM
13use pbs_api_types::{
14 DATASTORE_SCHEMA, UPID_SCHEMA, REMOTE_ID_SCHEMA, REMOVE_VANISHED_BACKUPS_SCHEMA,
15 IGNORE_VERIFIED_BACKUPS_SCHEMA, VERIFICATION_OUTDATED_AFTER_SCHEMA,
16};
4805edc4 17
b9700a9f
DM
18use proxmox_rest_server::wait_for_local_worker;
19
a220a456 20use proxmox_backup::config;
6227654a 21use proxmox_backup::api2;
769f8c99 22
a220a456
DM
23mod proxmox_backup_manager;
24use proxmox_backup_manager::*;
25
769f8c99
DM
26#[api(
27 input: {
28 properties: {
29 store: {
30 schema: DATASTORE_SCHEMA,
31 },
32 "output-format": {
33 schema: OUTPUT_FORMAT,
34 optional: true,
35 },
36 }
37 }
38)]
39/// Start garbage collection for a specific datastore.
40async fn start_garbage_collection(param: Value) -> Result<Value, Error> {
691c89a0 41
ac3faaf5 42 let output_format = get_output_format(&param);
691c89a0 43
3c8c2827 44 let store = required_string_param(&param, "store")?;
769f8c99 45
6b68e5d5 46 let mut client = connect_to_localhost()?;
769f8c99
DM
47
48 let path = format!("api2/json/admin/datastore/{}/gc", store);
49
50 let result = client.post(&path, None).await?;
51
e68269fc 52 view_task_result(&mut client, result, &output_format).await?;
769f8c99
DM
53
54 Ok(Value::Null)
55}
56
57#[api(
58 input: {
59 properties: {
60 store: {
61 schema: DATASTORE_SCHEMA,
62 },
63 "output-format": {
64 schema: OUTPUT_FORMAT,
65 optional: true,
66 },
67 }
68 }
69)]
70/// Show garbage collection status for a specific datastore.
71async fn garbage_collection_status(param: Value) -> Result<Value, Error> {
72
ac3faaf5 73 let output_format = get_output_format(&param);
769f8c99 74
3c8c2827 75 let store = required_string_param(&param, "store")?;
769f8c99 76
6b68e5d5 77 let client = connect_to_localhost()?;
769f8c99
DM
78
79 let path = format!("api2/json/admin/datastore/{}/gc", store);
80
9894469e
DM
81 let mut result = client.get(&path, None).await?;
82 let mut data = result["data"].take();
b2362a12 83 let return_type = &api2::admin::datastore::API_METHOD_GARBAGE_COLLECTION_STATUS.returns;
9894469e 84
ac3faaf5 85 let options = default_table_format_options();
9894469e 86
b2362a12 87 format_and_print_result_full(&mut data, return_type, &output_format, &options);
769f8c99
DM
88
89 Ok(Value::Null)
90}
91
92fn garbage_collection_commands() -> CommandLineInterface {
691c89a0
DM
93
94 let cmd_def = CliCommandMap::new()
95 .insert("status",
769f8c99 96 CliCommand::new(&API_METHOD_GARBAGE_COLLECTION_STATUS)
49fddd98 97 .arg_param(&["store"])
e7d4be9d 98 .completion_cb("store", pbs_config::datastore::complete_datastore_name)
48ef3c33 99 )
691c89a0 100 .insert("start",
769f8c99 101 CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
49fddd98 102 .arg_param(&["store"])
e7d4be9d 103 .completion_cb("store", pbs_config::datastore::complete_datastore_name)
48ef3c33 104 );
691c89a0
DM
105
106 cmd_def.into()
107}
108
47d47121
DM
109#[api(
110 input: {
111 properties: {
112 limit: {
113 description: "The maximal number of tasks to list.",
114 type: Integer,
115 optional: true,
116 minimum: 1,
117 maximum: 1000,
118 default: 50,
119 },
120 "output-format": {
121 schema: OUTPUT_FORMAT,
122 optional: true,
123 },
124 all: {
125 type: Boolean,
126 description: "Also list stopped tasks.",
127 optional: true,
128 }
129 }
130 }
131)]
132/// List running server tasks.
133async fn task_list(param: Value) -> Result<Value, Error> {
134
ac3faaf5 135 let output_format = get_output_format(&param);
47d47121 136
6b68e5d5 137 let client = connect_to_localhost()?;
47d47121
DM
138
139 let limit = param["limit"].as_u64().unwrap_or(50) as usize;
140 let running = !param["all"].as_bool().unwrap_or(false);
141 let args = json!({
142 "running": running,
143 "start": 0,
144 "limit": limit,
145 });
9894469e 146 let mut result = client.get("api2/json/nodes/localhost/tasks", Some(args)).await?;
47d47121 147
9894469e 148 let mut data = result["data"].take();
b2362a12 149 let return_type = &api2::node::tasks::API_METHOD_LIST_TASKS.returns;
47d47121 150
770a36e5 151 use pbs_tools::format::{render_epoch, render_task_status};
ac3faaf5 152 let options = default_table_format_options()
770a36e5
WB
153 .column(ColumnConfig::new("starttime").right_align(false).renderer(render_epoch))
154 .column(ColumnConfig::new("endtime").right_align(false).renderer(render_epoch))
93fbb4ef 155 .column(ColumnConfig::new("upid"))
770a36e5 156 .column(ColumnConfig::new("status").renderer(render_task_status));
9894469e 157
b2362a12 158 format_and_print_result_full(&mut data, return_type, &output_format, &options);
47d47121
DM
159
160 Ok(Value::Null)
161}
162
163#[api(
164 input: {
165 properties: {
166 upid: {
167 schema: UPID_SCHEMA,
168 },
169 }
170 }
171)]
172/// Display the task log.
173async fn task_log(param: Value) -> Result<Value, Error> {
174
3c8c2827 175 let upid = required_string_param(&param, "upid")?;
47d47121 176
e68269fc 177 let mut client = connect_to_localhost()?;
47d47121 178
e68269fc 179 display_task_log(&mut client, upid, true).await?;
47d47121
DM
180
181 Ok(Value::Null)
182}
183
184#[api(
185 input: {
186 properties: {
187 upid: {
188 schema: UPID_SCHEMA,
189 },
190 }
191 }
192)]
193/// Try to stop a specific task.
194async fn task_stop(param: Value) -> Result<Value, Error> {
195
3c8c2827 196 let upid_str = required_string_param(&param, "upid")?;
47d47121 197
6b68e5d5 198 let mut client = connect_to_localhost()?;
47d47121 199
4805edc4 200 let path = format!("api2/json/nodes/localhost/tasks/{}", percent_encode_component(upid_str));
47d47121
DM
201 let _ = client.delete(&path, None).await?;
202
203 Ok(Value::Null)
204}
205
206fn task_mgmt_cli() -> CommandLineInterface {
207
208 let task_log_cmd_def = CliCommand::new(&API_METHOD_TASK_LOG)
209 .arg_param(&["upid"]);
210
211 let task_stop_cmd_def = CliCommand::new(&API_METHOD_TASK_STOP)
212 .arg_param(&["upid"]);
213
214 let cmd_def = CliCommandMap::new()
215 .insert("list", CliCommand::new(&API_METHOD_TASK_LIST))
216 .insert("log", task_log_cmd_def)
217 .insert("stop", task_stop_cmd_def);
218
219 cmd_def.into()
220}
221
4b4eba0b 222// fixme: avoid API redefinition
0eb0e024
DM
223#[api(
224 input: {
225 properties: {
eb506c83 226 "local-store": {
0eb0e024
DM
227 schema: DATASTORE_SCHEMA,
228 },
229 remote: {
167971ed 230 schema: REMOTE_ID_SCHEMA,
0eb0e024
DM
231 },
232 "remote-store": {
233 schema: DATASTORE_SCHEMA,
234 },
40dc1031
DC
235 "remove-vanished": {
236 schema: REMOVE_VANISHED_BACKUPS_SCHEMA,
4b4eba0b 237 optional: true,
4b4eba0b 238 },
0eb0e024
DM
239 "output-format": {
240 schema: OUTPUT_FORMAT,
241 optional: true,
242 },
243 }
244 }
245)]
eb506c83
DM
246/// Sync datastore from another repository
247async fn pull_datastore(
0eb0e024
DM
248 remote: String,
249 remote_store: String,
eb506c83 250 local_store: String,
40dc1031 251 remove_vanished: Option<bool>,
ac3faaf5 252 param: Value,
0eb0e024
DM
253) -> Result<Value, Error> {
254
ac3faaf5 255 let output_format = get_output_format(&param);
0eb0e024 256
6b68e5d5 257 let mut client = connect_to_localhost()?;
0eb0e024 258
8c877436 259 let mut args = json!({
eb506c83 260 "store": local_store,
94609e23 261 "remote": remote,
0eb0e024 262 "remote-store": remote_store,
0eb0e024
DM
263 });
264
8c877436
DC
265 if let Some(remove_vanished) = remove_vanished {
266 args["remove-vanished"] = Value::from(remove_vanished);
267 }
268
eb506c83 269 let result = client.post("api2/json/pull", Some(args)).await?;
0eb0e024 270
e68269fc 271 view_task_result(&mut client, result, &output_format).await?;
0eb0e024
DM
272
273 Ok(Value::Null)
274}
275
355c055e
DM
276#[api(
277 input: {
278 properties: {
279 "store": {
280 schema: DATASTORE_SCHEMA,
281 },
60abf03f
HL
282 "ignore-verified": {
283 schema: IGNORE_VERIFIED_BACKUPS_SCHEMA,
284 optional: true,
285 },
286 "outdated-after": {
287 schema: VERIFICATION_OUTDATED_AFTER_SCHEMA,
288 optional: true,
289 },
355c055e
DM
290 "output-format": {
291 schema: OUTPUT_FORMAT,
292 optional: true,
293 },
294 }
295 }
296)]
297/// Verify backups
298async fn verify(
299 store: String,
60abf03f 300 mut param: Value,
355c055e
DM
301) -> Result<Value, Error> {
302
60abf03f 303 let output_format = extract_output_format(&mut param);
355c055e 304
6b68e5d5 305 let mut client = connect_to_localhost()?;
355c055e 306
60abf03f 307 let args = json!(param);
355c055e
DM
308
309 let path = format!("api2/json/admin/datastore/{}/verify", store);
310
311 let result = client.post(&path, Some(args)).await?;
312
e68269fc 313 view_task_result(&mut client, result, &output_format).await?;
355c055e
DM
314
315 Ok(Value::Null)
316}
317
9a556c8a
HL
318#[api()]
319/// System report
320async fn report() -> Result<Value, Error> {
941342f7
TL
321 let report = proxmox_backup::server::generate_report();
322 io::stdout().write_all(report.as_bytes())?;
9a556c8a
HL
323 Ok(Value::Null)
324}
325
c100fe91
ML
326#[api(
327 input: {
328 properties: {
329 verbose: {
330 type: Boolean,
331 optional: true,
332 default: false,
333 description: "Output verbose package information. It is ignored if output-format is specified.",
334 },
335 "output-format": {
336 schema: OUTPUT_FORMAT,
337 optional: true,
338 }
339 }
340 }
341)]
342/// List package versions for important Proxmox Backup Server packages.
343async fn get_versions(verbose: bool, param: Value) -> Result<Value, Error> {
294466ee 344 let output_format = get_output_format(&param);
c100fe91 345
5e293f13 346 let packages = crate::api2::node::apt::get_versions()?;
fc5a0120 347 let mut packages = json!(if verbose { &packages[..] } else { &packages[1..2] });
c100fe91 348
294466ee
TL
349 let options = default_table_format_options()
350 .disable_sort()
d1d74c43 351 .noborder(true) // just not helpful for version info which gets copy pasted often
294466ee
TL
352 .column(ColumnConfig::new("Package"))
353 .column(ColumnConfig::new("Version"))
354 .column(ColumnConfig::new("ExtraInfo").header("Extra Info"))
355 ;
b2362a12 356 let return_type = &crate::api2::node::apt::API_METHOD_GET_VERSIONS.returns;
294466ee 357
b2362a12 358 format_and_print_result_full(&mut packages, return_type, &output_format, &options);
c100fe91
ML
359
360 Ok(Value::Null)
361}
362
ae18c436 363async fn run() -> Result<(), Error> {
ac7513e3 364
6460764d 365 let cmd_def = CliCommandMap::new()
ed3e60ae 366 .insert("acl", acl_commands())
48ef3c33 367 .insert("datastore", datastore_commands())
8e40aa63 368 .insert("disk", disk_commands())
14627d67 369 .insert("dns", dns_commands())
ca0e5347 370 .insert("network", network_commands())
72e311c6 371 .insert("node", node_commands())
579728c6 372 .insert("user", user_commands())
0decd11e 373 .insert("openid", openid_commands())
f357390c 374 .insert("remote", remote_commands())
47d47121 375 .insert("garbage-collection", garbage_collection_commands())
72bd8293 376 .insert("acme", acme_mgmt_cli())
550e0d88 377 .insert("cert", cert_mgmt_cli())
2762481c 378 .insert("subscription", subscription_commands())
a3016d65 379 .insert("sync-job", sync_job_commands())
4a874665 380 .insert("verify-job", verify_job_commands())
0eb0e024
DM
381 .insert("task", task_mgmt_cli())
382 .insert(
eb506c83
DM
383 "pull",
384 CliCommand::new(&API_METHOD_PULL_DATASTORE)
385 .arg_param(&["remote", "remote-store", "local-store"])
e7d4be9d 386 .completion_cb("local-store", pbs_config::datastore::complete_datastore_name)
6afdda88 387 .completion_cb("remote", pbs_config::remote::complete_remote_name)
331b869d 388 .completion_cb("remote-store", complete_remote_datastore_name)
355c055e
DM
389 )
390 .insert(
391 "verify",
392 CliCommand::new(&API_METHOD_VERIFY)
393 .arg_param(&["store"])
e7d4be9d 394 .completion_cb("store", pbs_config::datastore::complete_datastore_name)
9a556c8a
HL
395 )
396 .insert("report",
397 CliCommand::new(&API_METHOD_REPORT)
c100fe91
ML
398 )
399 .insert("versions",
400 CliCommand::new(&API_METHOD_GET_VERSIONS)
0eb0e024 401 );
34d3ba52 402
ae18c436
DM
403 let backup_user = pbs_config::backup_user()?;
404 let file_opts = CreateOptions::new().owner(backup_user.uid).group(backup_user.gid);
405 proxmox_rest_server::init_worker_tasks(pbs_buildcfg::PROXMOX_BACKUP_LOG_DIR_M!().into(), file_opts.clone())?;
355c055e 406
ae18c436
DM
407 let mut commando_sock = proxmox_rest_server::CommandoSocket::new(proxmox_rest_server::our_ctrl_sock(), backup_user.gid);
408 proxmox_rest_server::register_task_control_commands(&mut commando_sock)?;
409 commando_sock.spawn()?;
355c055e 410
7b22acd0 411 let mut rpcenv = CliEnvironment::new();
e6dc35ac 412 rpcenv.set_auth_id(Some(String::from("root@pam")));
525008f7 413
ae18c436
DM
414 run_async_cli_command(cmd_def, rpcenv).await; // this call exit(-1) on error
415
416 Ok(())
417}
418
419fn main() -> Result<(), Error> {
420
421 proxmox_backup::tools::setup_safe_path_env();
422
423 pbs_runtime::main(run())
ea0b8b6e 424}
331b869d
DM
425
426// shell completion helper
427pub fn complete_remote_datastore_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
428
429 let mut list = Vec::new();
430
9ea4bce4 431 let _ = proxmox::try_block!({
331b869d 432 let remote = param.get("remote").ok_or_else(|| format_err!("no remote"))?;
331b869d 433
d420962f 434 let data = pbs_runtime::block_on(async move {
e0100d61
FG
435 crate::api2::config::remote::scan_remote_datastores(remote.clone()).await
436 })?;
331b869d 437
e0100d61
FG
438 for item in data {
439 list.push(item.store);
331b869d
DM
440 }
441
442 Ok(())
443 }).map_err(|_err: Error| { /* ignore */ });
444
445 list
446}