]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-backup-api.rs
api daemons: periodically unpark a tokio thread to ensure progress
[proxmox-backup.git] / src / bin / proxmox-backup-api.rs
CommitLineData
6680878b
DM
1use std::future::Future;
2use std::pin::Pin;
3
f7d4e4b5 4use anyhow::{bail, Error};
e76ac3a4 5use futures::*;
7fa9a37c 6use http::request::Parts;
9531d2c5 7use http::HeaderMap;
7fa9a37c 8use http::Response;
608806e8 9use hyper::{Body, Method, StatusCode};
e76ac3a4 10
6ef1b649
WB
11use proxmox_lang::try_block;
12use proxmox_router::{RpcEnvironmentType, UserInformation};
25877d05 13use proxmox_sys::fs::CreateOptions;
e76ac3a4 14
9531d2c5
TL
15use proxmox_rest_server::{
16 daemon, ApiConfig, AuthError, RestEnvironment, RestServer, ServerAdapter,
17};
8bca935f 18
6c30068e 19use proxmox_backup::auth_helpers::*;
a8f268af 20use proxmox_backup::config;
9531d2c5 21use proxmox_backup::server::auth::check_pbs_auth;
886e5ce8 22
d973aa82 23fn main() {
d91a0f9f
DM
24 pbs_tools::setup_libc_malloc_opts();
25
ac7513e3
DM
26 proxmox_backup::tools::setup_safe_path_env();
27
9a1b24b6 28 if let Err(err) = proxmox_async::runtime::main(run()) {
aa5a4060
DM
29 eprintln!("Error: {}", err);
30 std::process::exit(-1);
31 }
32}
33
608806e8 34struct ProxmoxBackupApiAdapter;
7fa9a37c 35
608806e8 36impl ServerAdapter for ProxmoxBackupApiAdapter {
608806e8
DM
37 fn get_index(
38 &self,
39 _env: RestEnvironment,
40 _parts: Parts,
41 ) -> Pin<Box<dyn Future<Output = Response<Body>> + Send>> {
42 Box::pin(async move {
608806e8
DM
43 let index = "<center><h1>Proxmox Backup API Server</h1></center>";
44
45 Response::builder()
46 .status(StatusCode::OK)
47 .header(hyper::header::CONTENT_TYPE, "text/html")
48 .body(index.into())
49 .unwrap()
50 })
51 }
52
53 fn check_auth<'a>(
54 &'a self,
55 headers: &'a HeaderMap,
56 method: &'a Method,
9531d2c5
TL
57 ) -> Pin<
58 Box<
59 dyn Future<Output = Result<(String, Box<dyn UserInformation + Sync + Send>), AuthError>>
60 + Send
61 + 'a,
62 >,
63 > {
64 Box::pin(async move { check_pbs_auth(headers, method).await })
608806e8 65 }
7fa9a37c
DM
66}
67
e76ac3a4 68async fn run() -> Result<(), Error> {
d96d8273
DM
69 if let Err(err) = syslog::init(
70 syslog::Facility::LOG_DAEMON,
71 log::LevelFilter::Info,
9531d2c5
TL
72 Some("proxmox-backup-api"),
73 ) {
aa5a4060 74 bail!("unable to inititialize syslog - {}", err);
a8f268af
DM
75 }
76
77 config::create_configdir()?;
d96d8273 78
22be470d
DM
79 config::update_self_signed_cert(false)?;
80
6c76aa43 81 proxmox_backup::server::create_run_dir()?;
bf013be1 82 proxmox_backup::server::create_state_dir()?;
4bc84a65 83 proxmox_backup::server::create_active_operations_dir()?;
1298618a 84 proxmox_backup::server::jobstate::create_jobstate_dir()?;
cafd51bf 85 proxmox_backup::tape::create_tape_status_dir()?;
cd44fb8d
DM
86 proxmox_backup::tape::create_drive_state_dir()?;
87 proxmox_backup::tape::create_changer_state_dir()?;
a0cd0f9c 88 proxmox_backup::tape::create_drive_lock_dir()?;
eaeda365 89
39a90ca6 90 if let Err(err) = generate_auth_key() {
aa5a4060 91 bail!("unable to generate auth key - {}", err);
8d04280b 92 }
d01e2420 93 let _ = private_auth_key(); // load with lazy_static
8d04280b 94
39a90ca6 95 if let Err(err) = generate_csrf_key() {
aa5a4060 96 bail!("unable to generate csrf key - {}", err);
39a90ca6 97 }
d01e2420 98 let _ = csrf_secret(); // load with lazy_static
39a90ca6 99
fd6d2438 100 let mut config = ApiConfig::new(
af06decd 101 pbs_buildcfg::JS_DIR,
26858dba
SR
102 &proxmox_backup::api2::ROUTER,
103 RpcEnvironmentType::PRIVILEGED,
608806e8 104 ProxmoxBackupApiAdapter,
26858dba 105 )?;
eaeda365 106
fd6d2438 107 let backup_user = pbs_config::backup_user()?;
9531d2c5
TL
108 let mut commando_sock = proxmox_rest_server::CommandSocket::new(
109 proxmox_rest_server::our_ctrl_sock(),
110 backup_user.gid,
111 );
a68768cf 112
9531d2c5
TL
113 let dir_opts = CreateOptions::new()
114 .owner(backup_user.uid)
115 .group(backup_user.gid);
116 let file_opts = CreateOptions::new()
117 .owner(backup_user.uid)
118 .group(backup_user.gid);
fd6d2438 119
0d5d15c9 120 config.enable_access_log(
fd6d2438 121 pbs_buildcfg::API_ACCESS_LOG_FN,
36b7085e
DM
122 Some(dir_opts.clone()),
123 Some(file_opts.clone()),
124 &mut commando_sock,
125 )?;
126
127 config.enable_auth_log(
128 pbs_buildcfg::API_AUTH_LOG_FN,
0a33fba4
DM
129 Some(dir_opts.clone()),
130 Some(file_opts.clone()),
fd6d2438
DM
131 &mut commando_sock,
132 )?;
8e7e2223 133
9bc17e8d 134 let rest_server = RestServer::new(config);
9531d2c5
TL
135 proxmox_rest_server::init_worker_tasks(
136 pbs_buildcfg::PROXMOX_BACKUP_LOG_DIR_M!().into(),
137 file_opts.clone(),
138 )?;
886e5ce8 139
5e7bc50a 140 // http server future:
e9b9f33a
FE
141 let server = daemon::create_daemon(
142 ([127, 0, 0, 1], 82).into(),
143 move |listener| {
144 let incoming = hyper::server::conn::AddrIncoming::from_listener(listener)?;
145
146 Ok(async {
147 daemon::systemd_notify(daemon::SystemdNotify::Ready)?;
148
149 hyper::Server::builder(incoming)
150 .serve(rest_server)
151 .with_graceful_shutdown(proxmox_rest_server::shutdown_future())
152 .map_err(Error::from)
153 .await
154 })
155 },
156 Some(pbs_buildcfg::PROXMOX_BACKUP_API_PID_FN),
157 );
5e7bc50a 158
b9700a9f 159 proxmox_rest_server::write_pid(pbs_buildcfg::PROXMOX_BACKUP_API_PID_FN)?;
d98c9a7a 160
e76ac3a4 161 let init_result: Result<(), Error> = try_block!({
b9700a9f 162 proxmox_rest_server::register_task_control_commands(&mut commando_sock)?;
a68768cf 163 commando_sock.spawn()?;
fd1b65cc
DM
164 proxmox_rest_server::catch_shutdown_signal()?;
165 proxmox_rest_server::catch_reload_signal()?;
e76ac3a4
WB
166 Ok(())
167 });
e3f41f21 168
e76ac3a4
WB
169 if let Err(err) = init_result {
170 bail!("unable to start daemon - {}", err);
171 }
d607b886 172
c2206e21
TL
173 // stop gap for https://github.com/tokio-rs/tokio/issues/4730 where the thread holding the
174 // IO-driver may block progress completely if it starts polling its own tasks (blocks).
175 // So, trigger a notify to parked threads, as we're immediately ready the woken up thread will
176 // acquire the IO driver, if blocked, before going to sleep, which allows progress again
177 // TODO: remove once tokio solves this at their level (see proposals in linked comments)
178 let rt_handle = tokio::runtime::Handle::current();
179 std::thread::spawn(move || loop {
180 rt_handle.spawn(std::future::ready(()));
181 std::thread::sleep(std::time::Duration::from_secs(3));
182 });
183
083ff3fd 184 server.await?;
a546a8a0 185 log::info!("server shutting down, waiting for active workers to complete");
fd6d2438 186 proxmox_rest_server::last_worker_future().await?;
e3f41f21 187
e76ac3a4 188 log::info!("done - exit server");
eaeda365 189
aa5a4060 190 Ok(())
d8d978eb 191}