Skip to content

Fix Health Check API server test: return actual bound socket address after starting #554

@josecelano

Description

@josecelano

When the Health Check API server is started the actual bound socket address is not returned:

/// Starts Health Check API server.
///
/// # Panics
///
/// Will panic if binding to the socket address fails.
pub fn start(
    socket_addr: SocketAddr,
    tx: Sender<ApiServerJobStarted>,
    config: Arc<Configuration>,
) -> impl Future<Output = Result<(), std::io::Error>> {
    let app = Router::new()
        .route("/", get(|| async { Json(json!({})) }))
        .route("/health_check", get(health_check_handler))
        .with_state(config);

    let handle = Handle::new();

    let cloned_handle = handle.clone();

    tokio::task::spawn(async move {
        tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal.");
        info!("Stopping Torrust Health Check API server o http://{} ...", socket_addr);
        cloned_handle.shutdown();
    });

    let running = axum_server::bind(socket_addr)
        .handle(handle)
        .serve(app.into_make_service_with_connect_info::<SocketAddr>());

    tx.send(ApiServerJobStarted { bound_addr: actual_addr })
        .expect("the Health Check API server should not be dropped");

    running
}

The same port as in the configuration is returned. When port 0 is used the returned value is 0 too.

We have to do the same as in other servers like the API:

https://github.com/torrust/torrust-tracker/blob/develop/src/servers/http/v1/launcher.rs#L111-L114

We have to create the TcpListener to get the local address and return the actual socket address the socket was bound to.

    fn start_with_graceful_shutdown<F>(
        &self,
        cfg: torrust_tracker_configuration::HttpTracker,
        tracker: Arc<Tracker>,
        shutdown_signal: F,
    ) -> (SocketAddr, BoxFuture<'static, ()>)
    where
        F: Future<Output = ()> + Send + 'static,
    {
        let addr = SocketAddr::from_str(&cfg.bind_address).expect("bind_address is not a valid SocketAddr.");
        let tcp_listener = std::net::TcpListener::bind(addr).expect("Could not bind tcp_listener to address.");
        let bind_addr = tcp_listener
            .local_addr()
            .expect("Could not get local_addr from tcp_listener.");

        if let (true, Some(ssl_cert_path), Some(ssl_key_path)) = (cfg.ssl_enabled, &cfg.ssl_cert_path, &cfg.ssl_key_path) {
            let server = Self::start_tls_from_tcp_listener_with_graceful_shutdown(
                tcp_listener,
                (ssl_cert_path.to_string(), ssl_key_path.to_string()),
                tracker,
                shutdown_signal,
            );

            (bind_addr, server)
        } else {
            let server = Self::start_from_tcp_listener_with_graceful_shutdown(tcp_listener, tracker, shutdown_signal);

            (bind_addr, server)
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions