Skip to content

Commit 14e672e

Browse files
committed
tracing: add spans to many functions
1 parent 3dc75d5 commit 14e672e

25 files changed

+176
-71
lines changed

src/app.rs

+2
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ use std::sync::Arc;
2525

2626
use tokio::task::JoinHandle;
2727
use torrust_tracker_configuration::Configuration;
28+
use tracing::instrument;
2829

2930
use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker};
3031
use crate::servers::registar::Registar;
@@ -36,6 +37,7 @@ use crate::{core, servers};
3637
///
3738
/// - Can't retrieve tracker keys from database.
3839
/// - Can't load whitelist from database.
40+
#[instrument(skip(config, tracker))]
3941
pub async fn start(config: &Configuration, tracker: Arc<core::Tracker>) -> Vec<JoinHandle<()>> {
4042
if config.http_api.is_none()
4143
&& (config.udp_trackers.is_none() || config.udp_trackers.as_ref().map_or(true, std::vec::Vec::is_empty))

src/bootstrap/app.rs

+6
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use std::sync::Arc;
1616
use torrust_tracker_clock::static_time;
1717
use torrust_tracker_configuration::validator::Validator;
1818
use torrust_tracker_configuration::Configuration;
19+
use tracing::instrument;
1920

2021
use super::config::initialize_configuration;
2122
use crate::bootstrap;
@@ -29,6 +30,7 @@ use crate::shared::crypto::ephemeral_instance_keys;
2930
///
3031
/// Setup can file if the configuration is invalid.
3132
#[must_use]
33+
#[instrument(skip())]
3234
pub fn setup() -> (Configuration, Arc<Tracker>) {
3335
let configuration = initialize_configuration();
3436

@@ -47,6 +49,7 @@ pub fn setup() -> (Configuration, Arc<Tracker>) {
4749
///
4850
/// The configuration may be obtained from the environment (via config file or env vars).
4951
#[must_use]
52+
#[instrument(skip())]
5053
pub fn initialize_with_configuration(configuration: &Configuration) -> Arc<Tracker> {
5154
initialize_static();
5255
initialize_logging(configuration);
@@ -59,6 +62,7 @@ pub fn initialize_with_configuration(configuration: &Configuration) -> Arc<Track
5962
///
6063
/// - The time when the application started.
6164
/// - An ephemeral instance random seed. This seed is used for encryption and it's changed when the main application process is restarted.
65+
#[instrument(skip())]
6266
pub fn initialize_static() {
6367
// Set the time of Torrust app starting
6468
lazy_static::initialize(&static_time::TIME_AT_APP_START);
@@ -72,13 +76,15 @@ pub fn initialize_static() {
7276
/// The tracker is the domain layer service. It's the entrypoint to make requests to the domain layer.
7377
/// It's used by other higher-level components like the UDP and HTTP trackers or the tracker API.
7478
#[must_use]
79+
#[instrument(skip(config))]
7580
pub fn initialize_tracker(config: &Configuration) -> Tracker {
7681
tracker_factory(config)
7782
}
7883

7984
/// It initializes the log threshold, format and channel.
8085
///
8186
/// See [the logging setup](crate::bootstrap::logging::setup) for more info about logging.
87+
#[instrument(skip(config))]
8288
pub fn initialize_logging(config: &Configuration) {
8389
bootstrap::logging::setup(config);
8490
}

src/bootstrap/jobs/health_check_api.rs

+3
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use tokio::sync::oneshot;
1818
use tokio::task::JoinHandle;
1919
use torrust_tracker_configuration::HealthCheckApi;
20+
use tracing::instrument;
2021

2122
use super::Started;
2223
use crate::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET};
@@ -34,6 +35,8 @@ use crate::servers::signals::Halted;
3435
/// # Panics
3536
///
3637
/// It would panic if unable to send the `ApiServerJobStarted` notice.
38+
#[allow(clippy::async_yields_async)]
39+
#[instrument(skip(config, register))]
3740
pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> JoinHandle<()> {
3841
let bind_addr = config.bind_address;
3942

src/bootstrap/jobs/http_tracker.rs

+4
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use std::sync::Arc;
1616
use axum_server::tls_rustls::RustlsConfig;
1717
use tokio::task::JoinHandle;
1818
use torrust_tracker_configuration::HttpTracker;
19+
use tracing::instrument;
1920

2021
use super::make_rust_tls;
2122
use crate::core;
@@ -32,6 +33,7 @@ use crate::servers::registar::ServiceRegistrationForm;
3233
///
3334
/// It would panic if the `config::HttpTracker` struct would contain inappropriate values.
3435
///
36+
#[instrument(skip(config, tracker, form))]
3537
pub async fn start_job(
3638
config: &HttpTracker,
3739
tracker: Arc<core::Tracker>,
@@ -49,6 +51,8 @@ pub async fn start_job(
4951
}
5052
}
5153

54+
#[allow(clippy::async_yields_async)]
55+
#[instrument(skip(socket, tls, tracker, form))]
5256
async fn start_v1(
5357
socket: SocketAddr,
5458
tls: Option<RustlsConfig>,

src/bootstrap/jobs/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ pub struct Started {
2020
pub address: std::net::SocketAddr,
2121
}
2222

23+
#[instrument(skip(opt_tsl_config))]
2324
pub async fn make_rust_tls(opt_tsl_config: &Option<TslConfig>) -> Option<Result<RustlsConfig, Error>> {
2425
match opt_tsl_config {
2526
Some(tsl_config) => {
@@ -89,6 +90,7 @@ use axum_server::tls_rustls::RustlsConfig;
8990
use thiserror::Error;
9091
use torrust_tracker_configuration::TslConfig;
9192
use torrust_tracker_located_error::{DynError, LocatedError};
93+
use tracing::instrument;
9294

9395
/// Error returned by the Bootstrap Process.
9496
#[derive(Error, Debug)]

src/bootstrap/jobs/torrent_cleanup.rs

+2
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use std::sync::Arc;
1515
use chrono::Utc;
1616
use tokio::task::JoinHandle;
1717
use torrust_tracker_configuration::Core;
18+
use tracing::instrument;
1819

1920
use crate::core;
2021

@@ -24,6 +25,7 @@ use crate::core;
2425
///
2526
/// Refer to [`torrust-tracker-configuration documentation`](https://docs.rs/torrust-tracker-configuration) for more info about that option.
2627
#[must_use]
28+
#[instrument(skip(config, tracker))]
2729
pub fn start_job(config: &Core, tracker: &Arc<core::Tracker>) -> JoinHandle<()> {
2830
let weak_tracker = std::sync::Arc::downgrade(tracker);
2931
let interval = config.inactive_peer_cleanup_interval;

src/bootstrap/jobs/tracker_apis.rs

+4
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use std::sync::Arc;
2626
use axum_server::tls_rustls::RustlsConfig;
2727
use tokio::task::JoinHandle;
2828
use torrust_tracker_configuration::{AccessTokens, HttpApi};
29+
use tracing::instrument;
2930

3031
use super::make_rust_tls;
3132
use crate::core;
@@ -53,6 +54,7 @@ pub struct ApiServerJobStarted();
5354
/// It would panic if unable to send the `ApiServerJobStarted` notice.
5455
///
5556
///
57+
#[instrument(skip(config, tracker, form))]
5658
pub async fn start_job(
5759
config: &HttpApi,
5860
tracker: Arc<core::Tracker>,
@@ -72,6 +74,8 @@ pub async fn start_job(
7274
}
7375
}
7476

77+
#[allow(clippy::async_yields_async)]
78+
#[instrument(skip(socket, tls, tracker, form, access_tokens))]
7579
async fn start_v1(
7680
socket: SocketAddr,
7781
tls: Option<RustlsConfig>,

src/bootstrap/jobs/udp_tracker.rs

+3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use std::sync::Arc;
1010

1111
use tokio::task::JoinHandle;
1212
use torrust_tracker_configuration::UdpTracker;
13+
use tracing::instrument;
1314

1415
use crate::core;
1516
use crate::servers::registar::ServiceRegistrationForm;
@@ -27,6 +28,8 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET;
2728
/// It will panic if it is unable to start the UDP service.
2829
/// It will panic if the task did not finish successfully.
2930
#[must_use]
31+
#[allow(clippy::async_yields_async)]
32+
#[instrument(skip(config, tracker, form))]
3033
pub async fn start_job(config: &UdpTracker, tracker: Arc<core::Tracker>, form: ServiceRegistrationForm) -> JoinHandle<()> {
3134
let bind_to = config.bind_address;
3235

src/servers/apis/routes.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use tower_http::compression::CompressionLayer;
2121
use tower_http::propagate_header::PropagateHeaderLayer;
2222
use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer};
2323
use tower_http::trace::{DefaultMakeSpan, TraceLayer};
24-
use tracing::{Level, Span};
24+
use tracing::{instrument, Level, Span};
2525

2626
use super::v1;
2727
use super::v1::context::health_check::handlers::health_check_handler;
@@ -31,6 +31,7 @@ use crate::servers::apis::API_LOG_TARGET;
3131

3232
/// Add all API routes to the router.
3333
#[allow(clippy::needless_pass_by_value)]
34+
#[instrument(skip(tracker, access_tokens))]
3435
pub fn router(tracker: Arc<Tracker>, access_tokens: Arc<AccessTokens>) -> Router {
3536
let router = Router::new();
3637

src/servers/apis/server.rs

+34-8
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,13 @@ use std::sync::Arc;
2828

2929
use axum_server::tls_rustls::RustlsConfig;
3030
use axum_server::Handle;
31+
use derive_more::derive::Display;
3132
use derive_more::Constructor;
3233
use futures::future::BoxFuture;
34+
use thiserror::Error;
3335
use tokio::sync::oneshot::{Receiver, Sender};
3436
use torrust_tracker_configuration::AccessTokens;
37+
use tracing::{instrument, Level};
3538

3639
use super::routes::router;
3740
use crate::bootstrap::jobs::Started;
@@ -43,9 +46,10 @@ use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, Servi
4346
use crate::servers::signals::{graceful_shutdown, Halted};
4447

4548
/// Errors that can occur when starting or stopping the API server.
46-
#[derive(Debug)]
49+
#[derive(Debug, Error)]
4750
pub enum Error {
48-
Error(String),
51+
#[error("Error when starting or stopping the API server")]
52+
FailedToStartOrStop(String),
4953
}
5054

5155
/// An alias for the `ApiServer` struct with the `Stopped` state.
@@ -62,31 +66,39 @@ pub type RunningApiServer = ApiServer<Running>;
6266
/// It's a state machine that can be in one of two
6367
/// states: `Stopped` or `Running`.
6468
#[allow(clippy::module_name_repetitions)]
65-
pub struct ApiServer<S> {
69+
#[derive(Debug, Display)]
70+
pub struct ApiServer<S>
71+
where
72+
S: std::fmt::Debug + std::fmt::Display,
73+
{
6674
pub state: S,
6775
}
6876

6977
/// The `Stopped` state of the `ApiServer` struct.
78+
#[derive(Debug, Display)]
79+
#[display("Stopped: {launcher}")]
7080
pub struct Stopped {
7181
launcher: Launcher,
7282
}
7383

7484
/// The `Running` state of the `ApiServer` struct.
85+
#[derive(Debug, Display)]
86+
#[display("Running (with local address): {local_addr}")]
7587
pub struct Running {
76-
pub binding: SocketAddr,
88+
pub local_addr: SocketAddr,
7789
pub halt_task: tokio::sync::oneshot::Sender<Halted>,
7890
pub task: tokio::task::JoinHandle<Launcher>,
7991
}
8092

8193
impl Running {
8294
#[must_use]
8395
pub fn new(
84-
binding: SocketAddr,
96+
local_addr: SocketAddr,
8597
halt_task: tokio::sync::oneshot::Sender<Halted>,
8698
task: tokio::task::JoinHandle<Launcher>,
8799
) -> Self {
88100
Self {
89-
binding,
101+
local_addr,
90102
halt_task,
91103
task,
92104
}
@@ -110,6 +122,7 @@ impl ApiServer<Stopped> {
110122
/// # Panics
111123
///
112124
/// It would panic if the bound socket address cannot be sent back to this starter.
125+
#[instrument(skip(self, tracker, form, access_tokens), err, ret(Display, level = Level::INFO))]
113126
pub async fn start(
114127
self,
115128
tracker: Arc<Tracker>,
@@ -157,13 +170,14 @@ impl ApiServer<Running> {
157170
/// # Errors
158171
///
159172
/// It would return an error if the channel for the task killer signal was closed.
173+
#[instrument(skip(self), err, ret(Display, level = Level::INFO))]
160174
pub async fn stop(self) -> Result<ApiServer<Stopped>, Error> {
161175
self.state
162176
.halt_task
163177
.send(Halted::Normal)
164-
.map_err(|_| Error::Error("Task killer channel was closed.".to_string()))?;
178+
.map_err(|_| Error::FailedToStartOrStop("Task killer channel was closed.".to_string()))?;
165179

166-
let launcher = self.state.task.await.map_err(|e| Error::Error(e.to_string()))?;
180+
let launcher = self.state.task.await.map_err(|e| Error::FailedToStartOrStop(e.to_string()))?;
167181

168182
Ok(ApiServer {
169183
state: Stopped { launcher },
@@ -178,6 +192,7 @@ impl ApiServer<Running> {
178192
/// This function will return an error if unable to connect.
179193
/// Or if there request returns an error code.
180194
#[must_use]
195+
#[instrument(skip())]
181196
pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob {
182197
let url = format!("http://{binding}/api/health_check"); // DevSkim: ignore DS137138
183198

@@ -199,6 +214,16 @@ pub struct Launcher {
199214
tls: Option<RustlsConfig>,
200215
}
201216

217+
impl std::fmt::Display for Launcher {
218+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
219+
if self.tls.is_some() {
220+
write!(f, "(with socket): {}, using TLS", self.bind_to,)
221+
} else {
222+
write!(f, "(with socket): {}, without TLS", self.bind_to,)
223+
}
224+
}
225+
}
226+
202227
impl Launcher {
203228
/// Starts the API server with graceful shutdown.
204229
///
@@ -210,6 +235,7 @@ impl Launcher {
210235
///
211236
/// Will panic if unable to bind to the socket, or unable to get the address of the bound socket.
212237
/// Will also panic if unable to send message regarding the bound socket address.
238+
#[instrument(skip(self, tracker, access_tokens, tx_start, rx_halt))]
213239
pub fn start(
214240
&self,
215241
tracker: Arc<Tracker>,

src/servers/health_check_api/handlers.rs

+2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::collections::VecDeque;
22

33
use axum::extract::State;
44
use axum::Json;
5+
use tracing::{instrument, Level};
56

67
use super::resources::{CheckReport, Report};
78
use super::responses;
@@ -11,6 +12,7 @@ use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, Servi
1112
///
1213
/// Creates a vector [`CheckReport`] from the input set of [`CheckJob`], and then builds a report from the results.
1314
///
15+
#[instrument(skip(register), ret(level = Level::DEBUG))]
1416
pub(crate) async fn health_check_handler(State(register): State<ServiceRegistry>) -> Json<Report> {
1517
#[allow(unused_assignments)]
1618
let mut checks: VecDeque<ServiceHealthCheckJob> = VecDeque::new();

src/servers/health_check_api/server.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use tower_http::compression::CompressionLayer;
1818
use tower_http::propagate_header::PropagateHeaderLayer;
1919
use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer};
2020
use tower_http::trace::{DefaultMakeSpan, TraceLayer};
21-
use tracing::{Level, Span};
21+
use tracing::{instrument, Level, Span};
2222

2323
use crate::bootstrap::jobs::Started;
2424
use crate::servers::health_check_api::handlers::health_check_handler;
@@ -31,6 +31,7 @@ use crate::servers::signals::{graceful_shutdown, Halted};
3131
/// # Panics
3232
///
3333
/// Will panic if binding to the socket address fails.
34+
#[instrument(skip(bind_to, tx, rx_halt, register))]
3435
pub fn start(
3536
bind_to: SocketAddr,
3637
tx: Sender<Started>,

src/servers/http/server.rs

+2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use axum_server::Handle;
77
use derive_more::Constructor;
88
use futures::future::BoxFuture;
99
use tokio::sync::oneshot::{Receiver, Sender};
10+
use tracing::instrument;
1011

1112
use super::v1::routes::router;
1213
use crate::bootstrap::jobs::Started;
@@ -41,6 +42,7 @@ pub struct Launcher {
4142
}
4243

4344
impl Launcher {
45+
#[instrument(skip(self, tracker, tx_start, rx_halt))]
4446
fn start(&self, tracker: Arc<Tracker>, tx_start: Sender<Started>, rx_halt: Receiver<Halted>) -> BoxFuture<'static, ()> {
4547
let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address.");
4648
let address = socket.local_addr().expect("Could not get local_addr from tcp_listener.");

src/servers/http/v1/routes.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use tower_http::compression::CompressionLayer;
1717
use tower_http::propagate_header::PropagateHeaderLayer;
1818
use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer};
1919
use tower_http::trace::{DefaultMakeSpan, TraceLayer};
20-
use tracing::{Level, Span};
20+
use tracing::{instrument, Level, Span};
2121

2222
use super::handlers::{announce, health_check, scrape};
2323
use crate::core::Tracker;
@@ -28,6 +28,7 @@ use crate::servers::http::HTTP_TRACKER_LOG_TARGET;
2828
/// > **NOTICE**: it's added a layer to get the client IP from the connection
2929
/// > info. The tracker could use the connection info to get the client IP.
3030
#[allow(clippy::needless_pass_by_value)]
31+
#[instrument(skip(tracker, server_socket_addr))]
3132
pub fn router(tracker: Arc<Tracker>, server_socket_addr: SocketAddr) -> Router {
3233
Router::new()
3334
// Health check

0 commit comments

Comments
 (0)