Skip to content

Commit

Permalink
feat: [torrust#508] add health check for UDP tracker
Browse files Browse the repository at this point in the history
Using the `connect` UDP request. If the UDP trackers replies to a
connection request we assume is healthy.
  • Loading branch information
josecelano committed Nov 24, 2023
1 parent 2a05590 commit bf23479
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion src/servers/health_check_api/handlers.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use std::net::SocketAddr;
use std::sync::Arc;

use aquatic_udp_protocol::{ConnectRequest, Response, TransactionId};
use axum::extract::State;
use axum::Json;
use torrust_tracker_configuration::Configuration;

use super::resources::Report;
use super::responses;
use crate::shared::bit_torrent::udp::client::new_udp_tracker_client_connected;

/// If port 0 is specified in the configuration the OS will automatically
/// assign a free port. But we do now know in from the configuration.
Expand All @@ -23,6 +25,8 @@ pub(crate) async fn health_check_handler(State(config): State<Arc<Configuration>
// running service, after starting it as we do for testing with ephemeral
// configurations.

// Health check for API

if config.http_api.enabled {
let addr: SocketAddr = config.http_api.bind_address.parse().expect("invalid socket address for API");

Expand All @@ -35,6 +39,8 @@ pub(crate) async fn health_check_handler(State(config): State<Arc<Configuration>
}
}

// Health check for HTTP Trackers

for http_tracker_config in &config.http_trackers {
if !http_tracker_config.enabled {
continue;
Expand All @@ -56,7 +62,22 @@ pub(crate) async fn health_check_handler(State(config): State<Arc<Configuration>
}
}

// todo: for all UDP Trackers, if enabled, check if is healthy
// Health check for UDP Trackers

for udp_tracker_config in &config.udp_trackers {
if !udp_tracker_config.enabled {
continue;
}

let addr: SocketAddr = udp_tracker_config
.bind_address
.parse()
.expect("invalid socket address for UDP tracker");

if addr.port() != UNKNOWN_PORT && !can_connect_to_udp_tracker(&addr.to_string()).await {
return responses::error(format!("UDP Tracker is not healthy. Can't connect to: {addr}"));
}
}

responses::ok()
}
Expand All @@ -67,3 +88,18 @@ async fn get_req_is_ok(url: &str) -> bool {
Err(_err) => false,
}
}

/// Tries to connect to an UDP tracker. It returns true if it succeeded.
async fn can_connect_to_udp_tracker(url: &str) -> bool {
let client = new_udp_tracker_client_connected(url).await;

let connect_request = ConnectRequest {
transaction_id: TransactionId(123),
};

client.send(connect_request.into()).await;

let response = client.receive().await;

matches!(response, Response::Connect(_connect_response))
}

0 comments on commit bf23479

Please sign in to comment.