]> git.proxmox.com Git - proxmox-backup.git/commitdiff
daemon: simlify code (make it easier to use)
authorDietmar Maurer <dietmar@proxmox.com>
Wed, 29 Sep 2021 09:21:32 +0000 (11:21 +0200)
committerDietmar Maurer <dietmar@proxmox.com>
Wed, 29 Sep 2021 10:04:48 +0000 (12:04 +0200)
proxmox-rest-server/examples/minimal-rest-server.rs
proxmox-rest-server/src/daemon.rs
src/bin/proxmox-backup-api.rs
src/bin/proxmox-backup-proxy.rs

index 4d0dac351c2f16bc8ae2cfc8bc7e291e32af85bd..224770392c64f672380603561fa8431d6f5a5cbe 100644 (file)
@@ -2,13 +2,11 @@ use std::sync::{Arc, Mutex};
 use std::collections::HashMap;
 
 use anyhow::{bail, format_err, Error};
-use futures::{FutureExt, TryFutureExt};
 use lazy_static::lazy_static;
 
 use proxmox::api::{api, router::SubdirMap, Router, RpcEnvironmentType, UserInformation};
 use proxmox::list_subdirs_api_method;
 use proxmox_rest_server::{ApiAuth, ApiConfig, AuthError, RestServer};
-
 // Create a Dummy User info and auth system
 // Normally this would check and authenticate the user
 struct DummyUserInfo;
@@ -197,16 +195,17 @@ async fn run() -> Result<(), Error> {
     // the api to clients
     proxmox_rest_server::daemon::create_daemon(
         ([127, 0, 0, 1], 65000).into(),
-        move |listener, ready| {
+        move |listener| {
             let incoming = hyper::server::conn::AddrIncoming::from_listener(listener)?;
 
-            Ok(ready
-                .and_then(|_| hyper::Server::builder(incoming)
+            Ok(async move {
+
+                hyper::Server::builder(incoming)
                     .serve(rest_server)
-                    .map_err(Error::from)
-                )
-                .map_err(|err| eprintln!("ERR: {}", err))
-                .map(|test| println!("OK: {}", test.is_ok())))
+                    .await?;
+
+                Ok(())
+            })
         },
         "example_server",
     ).await?;
index c527a586c416766b09c904ab602bdb7bfa6d1a1e..2ff202467138b94d0c7055d68a833bd7193a6c22 100644 (file)
@@ -7,8 +7,6 @@ use std::os::raw::{c_char, c_uchar, c_int};
 use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
 use std::os::unix::ffi::OsStrExt;
 use std::panic::UnwindSafe;
-use std::pin::Pin;
-use std::task::{Context, Poll};
 use std::path::PathBuf;
 
 use anyhow::{bail, format_err, Error};
@@ -240,31 +238,21 @@ impl Reloadable for tokio::net::TcpListener {
     }
 }
 
-pub struct NotifyReady;
-
-impl Future for NotifyReady {
-    type Output = Result<(), Error>;
-
-    fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Result<(), Error>> {
-        systemd_notify(SystemdNotify::Ready)?;
-        Poll::Ready(Ok(()))
-    }
-}
-
 /// This creates a future representing a daemon which reloads itself when receiving a SIGHUP.
 /// If this is started regularly, a listening socket is created. In this case, the file descriptor
 /// number will be remembered in `PROXMOX_BACKUP_LISTEN_FD`.
 /// If the variable already exists, its contents will instead be used to restore the listening
 /// socket.  The finished listening socket is then passed to the `create_service` function which
-/// can be used to setup the TLS and the HTTP daemon.
+/// can be used to setup the TLS and the HTTP daemon. The returned future has to call
+/// [systemd_notify] with [SystemdNotify::Ready] when the service is ready.
 pub async fn create_daemon<F, S>(
     address: std::net::SocketAddr,
     create_service: F,
     service_name: &str,
 ) -> Result<(), Error>
 where
-    F: FnOnce(tokio::net::TcpListener, NotifyReady) -> Result<S, Error>,
-    S: Future<Output = ()> + Unpin,
+    F: FnOnce(tokio::net::TcpListener) -> Result<S, Error>,
+    S: Future<Output = Result<(), Error>>,
 {
     let mut reloader = Reloader::new()?;
 
@@ -273,7 +261,15 @@ where
         move || async move { Ok(tokio::net::TcpListener::bind(&address).await?) },
     ).await?;
 
-    let server_future = create_service(listener, NotifyReady)?;
+    let service = create_service(listener)?;
+
+    let service = async move {
+        if let Err(err) = service.await {
+            log::error!("server error: {}", err);
+        }
+    };
+
+    let server_future = Box::pin(service);
     let shutdown_future = crate::shutdown_future();
 
     let finish_future = match future::select(server_future, shutdown_future).await {
index d687cda09c1548cf0b2cc5afe57cd864fec4a2f2..d4ef814a2525fce1f74caaeed44b592205903f11 100644 (file)
@@ -106,21 +106,18 @@ async fn run() -> Result<(), Error> {
     // http server future:
     let server = daemon::create_daemon(
         ([127,0,0,1], 82).into(),
-        move |listener, ready| {
+        move |listener| {
             let incoming = hyper::server::conn::AddrIncoming::from_listener(listener)?;
 
-            Ok(ready
-                .and_then(|_| hyper::Server::builder(incoming)
+            Ok(async {
+                daemon::systemd_notify(daemon::SystemdNotify::Ready)?;
+
+                hyper::Server::builder(incoming)
                     .serve(rest_server)
                     .with_graceful_shutdown(proxmox_rest_server::shutdown_future())
                     .map_err(Error::from)
-                )
-                .map(|e| {
-                    if let Err(e) = e {
-                        eprintln!("server error: {}", e);
-                    }
-                })
-            )
+                    .await
+            })
         },
         "proxmox-backup.service",
     );
index 013c14cd2c839b49cbb6c0f59c27d9d8083d5af3..e65a1695c780ed82cd0820da70edd0c70eeecb82 100644 (file)
@@ -247,20 +247,20 @@ async fn run() -> Result<(), Error> {
 
     let server = daemon::create_daemon(
         ([0,0,0,0,0,0,0,0], 8007).into(),
-        move |listener, ready| {
+        move |listener| {
 
             let connections = accept_connections(listener, acceptor, debug);
             let connections = hyper::server::accept::from_stream(ReceiverStream::new(connections));
 
-            Ok(ready
-               .and_then(|_| hyper::Server::builder(connections)
+            Ok(async {
+                daemon::systemd_notify(daemon::SystemdNotify::Ready)?;
+
+                hyper::Server::builder(connections)
                     .serve(rest_server)
                     .with_graceful_shutdown(proxmox_rest_server::shutdown_future())
                     .map_err(Error::from)
-                )
-                .map_err(|err| eprintln!("server error: {}", err))
-                .map(|_| ())
-            )
+                    .await
+            })
         },
         "proxmox-backup-proxy.service",
     );