diff --git a/packages/located-error/src/lib.rs b/packages/located-error/src/lib.rs index bfd4d4a86..3cba6042d 100644 --- a/packages/located-error/src/lib.rs +++ b/packages/located-error/src/lib.rs @@ -33,8 +33,6 @@ use std::error::Error; use std::panic::Location; use std::sync::Arc; -use tracing::debug; - pub type DynError = Arc; /// A generic wrapper around an error. @@ -94,7 +92,7 @@ where source: Arc::new(self.0), location: Box::new(*std::panic::Location::caller()), }; - debug!("{e}"); + tracing::debug!("{e}"); e } } diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 0c4029b69..dbd8eef9e 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -28,7 +28,7 @@ pub fn ephemeral() -> Configuration { let mut config = Configuration::default(); - config.logging.threshold = Threshold::Off; // Change to `debug` for tests debugging + config.logging.threshold = Threshold::Off; // It should always be off here, the tests manage their own logging. // Ephemeral socket address for API let api_port = 0u16; diff --git a/src/app.rs b/src/app.rs index b2447a9ef..06fea4d2e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -25,7 +25,7 @@ use std::sync::Arc; use tokio::task::JoinHandle; use torrust_tracker_configuration::Configuration; -use tracing::{info, warn}; +use tracing::instrument; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; use crate::servers::registar::Registar; @@ -37,12 +37,13 @@ use crate::{core, servers}; /// /// - Can't retrieve tracker keys from database. /// - Can't load whitelist from database. +#[instrument(skip(config, tracker))] pub async fn start(config: &Configuration, tracker: Arc) -> Vec> { if config.http_api.is_none() && (config.udp_trackers.is_none() || config.udp_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) && (config.http_trackers.is_none() || config.http_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) { - warn!("No services enabled in configuration"); + tracing::warn!("No services enabled in configuration"); } let mut jobs: Vec> = Vec::new(); @@ -69,7 +70,7 @@ pub async fn start(config: &Configuration, tracker: Arc) -> Vec) -> Vec) -> Vec) -> Vec (Configuration, Arc) { let configuration = initialize_configuration(); @@ -39,7 +40,7 @@ pub fn setup() -> (Configuration, Arc) { let tracker = initialize_with_configuration(&configuration); - info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json()); + tracing::info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json()); (configuration, tracker) } @@ -48,6 +49,7 @@ pub fn setup() -> (Configuration, Arc) { /// /// The configuration may be obtained from the environment (via config file or env vars). #[must_use] +#[instrument(skip())] pub fn initialize_with_configuration(configuration: &Configuration) -> Arc { initialize_static(); initialize_logging(configuration); @@ -60,6 +62,7 @@ pub fn initialize_with_configuration(configuration: &Configuration) -> Arc Tracker { tracker_factory(config) } @@ -80,6 +84,7 @@ pub fn initialize_tracker(config: &Configuration) -> Tracker { /// It initializes the log threshold, format and channel. /// /// See [the logging setup](crate::bootstrap::logging::setup) for more info about logging. +#[instrument(skip(config))] pub fn initialize_logging(config: &Configuration) { bootstrap::logging::setup(config); } diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index b4d4862ee..b6250efcc 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -17,7 +17,7 @@ use tokio::sync::oneshot; use tokio::task::JoinHandle; use torrust_tracker_configuration::HealthCheckApi; -use tracing::info; +use tracing::instrument; use super::Started; use crate::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET}; @@ -35,6 +35,8 @@ use crate::servers::signals::Halted; /// # Panics /// /// It would panic if unable to send the `ApiServerJobStarted` notice. +#[allow(clippy::async_yields_async)] +#[instrument(skip(config, register))] pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> JoinHandle<()> { let bind_addr = config.bind_address; @@ -45,18 +47,18 @@ pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> Jo // Run the API server let join_handle = tokio::spawn(async move { - info!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting on: {protocol}://{}", bind_addr); + tracing::info!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting on: {protocol}://{}", bind_addr); let handle = server::start(bind_addr, tx_start, rx_halt, register); if let Ok(()) = handle.await { - info!(target: HEALTH_CHECK_API_LOG_TARGET, "Stopped server running on: {protocol}://{}", bind_addr); + tracing::info!(target: HEALTH_CHECK_API_LOG_TARGET, "Stopped server running on: {protocol}://{}", bind_addr); } }); // Wait until the server sends the started message match rx_start.await { - Ok(msg) => info!(target: HEALTH_CHECK_API_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", msg.address), + Ok(msg) => tracing::info!(target: HEALTH_CHECK_API_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", msg.address), Err(e) => panic!("the Health Check API server was dropped: {e}"), } diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 745f564b1..c55723bc6 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -16,6 +16,7 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; use torrust_tracker_configuration::HttpTracker; +use tracing::instrument; use super::make_rust_tls; use crate::core; @@ -32,6 +33,7 @@ use crate::servers::registar::ServiceRegistrationForm; /// /// It would panic if the `config::HttpTracker` struct would contain inappropriate values. /// +#[instrument(skip(config, tracker, form))] pub async fn start_job( config: &HttpTracker, tracker: Arc, @@ -49,6 +51,8 @@ pub async fn start_job( } } +#[allow(clippy::async_yields_async)] +#[instrument(skip(socket, tls, tracker, form))] async fn start_v1( socket: SocketAddr, tls: Option, diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index 79a4347ef..6e18ec3ba 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -20,6 +20,7 @@ pub struct Started { pub address: std::net::SocketAddr, } +#[instrument(skip(opt_tsl_config))] pub async fn make_rust_tls(opt_tsl_config: &Option) -> Option> { match opt_tsl_config { Some(tsl_config) => { @@ -32,8 +33,8 @@ pub async fn make_rust_tls(opt_tsl_config: &Option) -> Option) -> JoinHandle<()> { let weak_tracker = std::sync::Arc::downgrade(tracker); let interval = config.inactive_peer_cleanup_interval; @@ -37,15 +38,15 @@ pub fn start_job(config: &Core, tracker: &Arc) -> JoinHandle<()> loop { tokio::select! { _ = tokio::signal::ctrl_c() => { - info!("Stopping torrent cleanup job.."); + tracing::info!("Stopping torrent cleanup job.."); break; } _ = interval.tick() => { if let Some(tracker) = weak_tracker.upgrade() { let start_time = Utc::now().time(); - info!("Cleaning up torrents.."); + tracing::info!("Cleaning up torrents.."); tracker.cleanup_torrents(); - info!("Cleaned up torrents in: {}ms", (Utc::now().time() - start_time).num_milliseconds()); + tracing::info!("Cleaned up torrents in: {}ms", (Utc::now().time() - start_time).num_milliseconds()); } else { break; } diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index ca91fbc83..35b13b7ce 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -26,6 +26,7 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; use torrust_tracker_configuration::{AccessTokens, HttpApi}; +use tracing::instrument; use super::make_rust_tls; use crate::core; @@ -53,6 +54,7 @@ pub struct ApiServerJobStarted(); /// It would panic if unable to send the `ApiServerJobStarted` notice. /// /// +#[instrument(skip(config, tracker, form))] pub async fn start_job( config: &HttpApi, tracker: Arc, @@ -72,6 +74,8 @@ pub async fn start_job( } } +#[allow(clippy::async_yields_async)] +#[instrument(skip(socket, tls, tracker, form, access_tokens))] async fn start_v1( socket: SocketAddr, tls: Option, diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 647461bfc..ca503aa29 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use tokio::task::JoinHandle; use torrust_tracker_configuration::UdpTracker; -use tracing::debug; +use tracing::instrument; use crate::core; use crate::servers::registar::ServiceRegistrationForm; @@ -28,6 +28,8 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// It will panic if it is unable to start the UDP service. /// It will panic if the task did not finish successfully. #[must_use] +#[allow(clippy::async_yields_async)] +#[instrument(skip(config, tracker, form))] pub async fn start_job(config: &UdpTracker, tracker: Arc, form: ServiceRegistrationForm) -> JoinHandle<()> { let bind_to = config.bind_address; @@ -37,8 +39,8 @@ pub async fn start_job(config: &UdpTracker, tracker: Arc, form: S .expect("it should be able to start the udp tracker"); tokio::spawn(async move { - debug!(target: UDP_TRACKER_LOG_TARGET, "Wait for launcher (UDP service) to finish ..."); - debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed before waiting?: {}", server.state.halt_task.is_closed()); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, "Wait for launcher (UDP service) to finish ..."); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed before waiting?: {}", server.state.halt_task.is_closed()); assert!( !server.state.halt_task.is_closed(), @@ -51,6 +53,6 @@ pub async fn start_job(config: &UdpTracker, tracker: Arc, form: S .await .expect("it should be able to join to the udp tracker task"); - debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed after finishing the server?: {}", server.state.halt_task.is_closed()); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed after finishing the server?: {}", server.state.halt_task.is_closed()); }) } diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs index 496b3ea45..34809c1ca 100644 --- a/src/bootstrap/logging.rs +++ b/src/bootstrap/logging.rs @@ -14,7 +14,6 @@ use std::sync::Once; use torrust_tracker_configuration::{Configuration, Threshold}; -use tracing::info; use tracing::level_filters::LevelFilter; static INIT: Once = Once::new(); @@ -54,7 +53,7 @@ fn tracing_stdout_init(filter: LevelFilter, style: &TraceStyle) { TraceStyle::Json => builder.json().init(), }; - info!("Logging initialized"); + tracing::info!("Logging initialized"); } #[derive(Debug)] diff --git a/src/console/ci/e2e/docker.rs b/src/console/ci/e2e/docker.rs index 32a0c3e56..ce2b1aa99 100644 --- a/src/console/ci/e2e/docker.rs +++ b/src/console/ci/e2e/docker.rs @@ -4,8 +4,6 @@ use std::process::{Command, Output}; use std::thread::sleep; use std::time::{Duration, Instant}; -use tracing::{debug, info}; - /// Docker command wrapper. pub struct Docker {} @@ -20,7 +18,7 @@ impl Drop for RunningContainer { /// Ensures that the temporary container is stopped when the struct goes out /// of scope. fn drop(&mut self) { - info!("Dropping running container: {}", self.name); + tracing::info!("Dropping running container: {}", self.name); if Docker::is_container_running(&self.name) { let _unused = Docker::stop(self); } @@ -89,7 +87,7 @@ impl Docker { let args = [initial_args, env_var_args, port_args, [image.to_string()].to_vec()].concat(); - debug!("Docker run args: {:?}", args); + tracing::debug!("Docker run args: {:?}", args); let output = Command::new("docker").args(args).output()?; @@ -176,7 +174,7 @@ impl Docker { let output_str = String::from_utf8_lossy(&output.stdout); - info!("Waiting until container is healthy: {:?}", output_str); + tracing::info!("Waiting until container is healthy: {:?}", output_str); if output_str.contains("(healthy)") { return true; diff --git a/src/console/ci/e2e/runner.rs b/src/console/ci/e2e/runner.rs index f2285938b..118ecda42 100644 --- a/src/console/ci/e2e/runner.rs +++ b/src/console/ci/e2e/runner.rs @@ -21,7 +21,6 @@ use std::path::PathBuf; use anyhow::Context; use clap::Parser; -use tracing::info; use tracing::level_filters::LevelFilter; use super::tracker_container::TrackerContainer; @@ -68,7 +67,7 @@ pub fn run() -> anyhow::Result<()> { let tracker_config = load_tracker_configuration(&args)?; - info!("tracker config:\n{tracker_config}"); + tracing::info!("tracker config:\n{tracker_config}"); let mut tracker_container = TrackerContainer::new(CONTAINER_IMAGE, CONTAINER_NAME_PREFIX); @@ -91,7 +90,7 @@ pub fn run() -> anyhow::Result<()> { let running_services = tracker_container.running_services(); - info!( + tracing::info!( "Running services:\n {}", serde_json::to_string_pretty(&running_services).expect("running services to be serializable to JSON") ); @@ -110,27 +109,27 @@ pub fn run() -> anyhow::Result<()> { tracker_container.remove(); - info!("Tracker container final state:\n{:#?}", tracker_container); + tracing::info!("Tracker container final state:\n{:#?}", tracker_container); Ok(()) } fn tracing_stdout_init(filter: LevelFilter) { tracing_subscriber::fmt().with_max_level(filter).init(); - info!("Logging initialized"); + tracing::info!("Logging initialized"); } fn load_tracker_configuration(args: &Args) -> anyhow::Result { match (args.config_toml_path.clone(), args.config_toml.clone()) { (Some(config_path), _) => { - info!( + tracing::info!( "Reading tracker configuration from file: {} ...", config_path.to_string_lossy() ); load_config_from_file(&config_path) } (_, Some(config_content)) => { - info!("Reading tracker configuration from env var ..."); + tracing::info!("Reading tracker configuration from env var ..."); Ok(config_content) } _ => Err(anyhow::anyhow!("No configuration provided")), diff --git a/src/console/ci/e2e/tracker_checker.rs b/src/console/ci/e2e/tracker_checker.rs index b2fd7df2e..192795e61 100644 --- a/src/console/ci/e2e/tracker_checker.rs +++ b/src/console/ci/e2e/tracker_checker.rs @@ -1,16 +1,14 @@ use std::io; use std::process::Command; -use tracing::info; - /// Runs the Tracker Checker. /// /// # Errors /// /// Will return an error if the Tracker Checker fails. pub fn run(config_content: &str) -> io::Result<()> { - info!("Running Tracker Checker: TORRUST_CHECKER_CONFIG=[config] cargo run --bin tracker_checker"); - info!("Tracker Checker config:\n{config_content}"); + tracing::info!("Running Tracker Checker: TORRUST_CHECKER_CONFIG=[config] cargo run --bin tracker_checker"); + tracing::info!("Tracker Checker config:\n{config_content}"); let status = Command::new("cargo") .env("TORRUST_CHECKER_CONFIG", config_content) diff --git a/src/console/ci/e2e/tracker_container.rs b/src/console/ci/e2e/tracker_container.rs index 528fd3c62..0d15035a8 100644 --- a/src/console/ci/e2e/tracker_container.rs +++ b/src/console/ci/e2e/tracker_container.rs @@ -2,7 +2,6 @@ use std::time::Duration; use rand::distributions::Alphanumeric; use rand::Rng; -use tracing::{error, info}; use super::docker::{RunOptions, RunningContainer}; use super::logs_parser::RunningServices; @@ -19,7 +18,7 @@ impl Drop for TrackerContainer { /// Ensures that the temporary container is removed when the /// struct goes out of scope. fn drop(&mut self) { - info!("Dropping tracker container: {}", self.name); + tracing::info!("Dropping tracker container: {}", self.name); if Docker::container_exist(&self.name) { let _unused = Docker::remove(&self.name); } @@ -40,7 +39,7 @@ impl TrackerContainer { /// /// Will panic if it can't build the docker image. pub fn build_image(&self) { - info!("Building tracker container image with tag: {} ...", self.image); + tracing::info!("Building tracker container image with tag: {} ...", self.image); Docker::build("./Containerfile", &self.image).expect("A tracker local docker image should be built"); } @@ -48,17 +47,17 @@ impl TrackerContainer { /// /// Will panic if it can't run the container. pub fn run(&mut self, options: &RunOptions) { - info!("Running docker tracker image: {} ...", self.name); + tracing::info!("Running docker tracker image: {} ...", self.name); let container = Docker::run(&self.image, &self.name, options).expect("A tracker local docker image should be running"); - info!("Waiting for the container {} to be healthy ...", self.name); + tracing::info!("Waiting for the container {} to be healthy ...", self.name); let is_healthy = Docker::wait_until_is_healthy(&self.name, Duration::from_secs(10)); assert!(is_healthy, "Unhealthy tracker container: {}", &self.name); - info!("Container {} is healthy ...", &self.name); + tracing::info!("Container {} is healthy ...", &self.name); self.running = Some(container); @@ -72,7 +71,7 @@ impl TrackerContainer { pub fn running_services(&self) -> RunningServices { let logs = Docker::logs(&self.name).expect("Logs should be captured from running container"); - info!("Parsing running services from logs. Logs :\n{logs}"); + tracing::info!("Parsing running services from logs. Logs :\n{logs}"); RunningServices::parse_from_logs(&logs) } @@ -83,7 +82,7 @@ impl TrackerContainer { pub fn stop(&mut self) { match &self.running { Some(container) => { - info!("Stopping docker tracker container: {} ...", self.name); + tracing::info!("Stopping docker tracker container: {} ...", self.name); Docker::stop(container).expect("Container should be stopped"); @@ -91,9 +90,9 @@ impl TrackerContainer { } None => { if Docker::is_container_running(&self.name) { - error!("Tracker container {} was started manually", self.name); + tracing::error!("Tracker container {} was started manually", self.name); } else { - info!("Docker tracker container is not running: {} ...", self.name); + tracing::info!("Docker tracker container is not running: {} ...", self.name); } } } @@ -106,9 +105,9 @@ impl TrackerContainer { /// Will panic if it can't remove the container. pub fn remove(&self) { if let Some(_running_container) = &self.running { - error!("Can't remove running container: {} ...", self.name); + tracing::error!("Can't remove running container: {} ...", self.name); } else { - info!("Removing docker tracker container: {} ...", self.name); + tracing::info!("Removing docker tracker container: {} ...", self.name); Docker::remove(&self.name).expect("Container should be removed"); } } diff --git a/src/console/clients/checker/app.rs b/src/console/clients/checker/app.rs index 3bafc2661..395f65df9 100644 --- a/src/console/clients/checker/app.rs +++ b/src/console/clients/checker/app.rs @@ -61,7 +61,6 @@ use std::sync::Arc; use anyhow::{Context, Result}; use clap::Parser; -use tracing::debug; use tracing::level_filters::LevelFilter; use super::config::Configuration; @@ -103,7 +102,7 @@ pub async fn run() -> Result> { fn tracing_stdout_init(filter: LevelFilter) { tracing_subscriber::fmt().with_max_level(filter).init(); - debug!("Logging initialized"); + tracing::debug!("Logging initialized"); } fn setup_config(args: Args) -> Result { diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index af6f10611..c2ba647b8 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -64,7 +64,6 @@ use aquatic_udp_protocol::{Response, TransactionId}; use clap::{Parser, Subcommand}; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; -use tracing::debug; use tracing::level_filters::LevelFilter; use url::Url; @@ -129,7 +128,7 @@ pub async fn run() -> anyhow::Result<()> { fn tracing_stdout_init(filter: LevelFilter) { tracing_subscriber::fmt().with_max_level(filter).init(); - debug!("Logging initialized"); + tracing::debug!("Logging initialized"); } async fn handle_announce(remote_addr: SocketAddr, info_hash: &TorrustInfoHash) -> Result { @@ -153,11 +152,11 @@ async fn handle_scrape(remote_addr: SocketAddr, info_hashes: &[TorrustInfoHash]) } fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result { - debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); + tracing::debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); // Check if the address is a valid URL. If so, extract the host and port. let resolved_addr = if let Ok(url) = Url::parse(tracker_socket_addr_str) { - debug!("Tracker socket address URL: {url:?}"); + tracing::debug!("Tracker socket address URL: {url:?}"); let host = url .host_str() @@ -192,7 +191,7 @@ fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result = resolved_addr.to_socket_addrs()?.collect(); diff --git a/src/console/clients/udp/checker.rs b/src/console/clients/udp/checker.rs index 49f0ac41f..437af33e0 100644 --- a/src/console/clients/udp/checker.rs +++ b/src/console/clients/udp/checker.rs @@ -8,7 +8,6 @@ use aquatic_udp_protocol::{ PeerId, PeerKey, Port, Response, ScrapeRequest, TransactionId, }; use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; -use tracing::debug; use super::Error; use crate::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; @@ -57,7 +56,7 @@ impl Client { /// /// Will panic if it receives an unexpected response. pub async fn send_connection_request(&self, transaction_id: TransactionId) -> Result { - debug!("Sending connection request with transaction id: {transaction_id:#?}"); + tracing::debug!("Sending connection request with transaction id: {transaction_id:#?}"); let connect_request = ConnectRequest { transaction_id }; @@ -95,7 +94,7 @@ impl Client { connection_id: ConnectionId, info_hash: TorrustInfoHash, ) -> Result { - debug!("Sending announce request with transaction id: {transaction_id:#?}"); + tracing::debug!("Sending announce request with transaction id: {transaction_id:#?}"); let port = NonZeroU16::new( self.client @@ -150,7 +149,7 @@ impl Client { transaction_id: TransactionId, info_hashes: &[TorrustInfoHash], ) -> Result { - debug!("Sending scrape request with transaction id: {transaction_id:#?}"); + tracing::debug!("Sending scrape request with transaction id: {transaction_id:#?}"); let scrape_request = ScrapeRequest { connection_id, diff --git a/src/console/profiling.rs b/src/console/profiling.rs index 3e2925d9c..5fb507197 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -160,7 +160,6 @@ use std::env; use std::time::Duration; use tokio::time::sleep; -use tracing::info; use crate::{app, bootstrap}; @@ -189,10 +188,10 @@ pub async fn run() { tokio::select! { () = run_duration => { - info!("Torrust timed shutdown.."); + tracing::info!("Torrust timed shutdown.."); }, _ = tokio::signal::ctrl_c() => { - info!("Torrust shutting down via Ctrl+C ..."); + tracing::info!("Torrust shutting down via Ctrl+C ..."); // Await for all jobs to shutdown futures::future::join_all(jobs).await; } diff --git a/src/core/auth.rs b/src/core/auth.rs index 61ccbdb52..0243fceb4 100644 --- a/src/core/auth.rs +++ b/src/core/auth.rs @@ -50,7 +50,6 @@ use torrust_tracker_clock::clock::Time; use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; use torrust_tracker_located_error::{DynError, LocatedError}; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use tracing::debug; use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; use crate::CurrentClock; @@ -81,14 +80,14 @@ pub fn generate_key(lifetime: Option) -> PeerKey { .collect(); if let Some(lifetime) = lifetime { - debug!("Generated key: {}, valid for: {:?} seconds", random_id, lifetime); + tracing::debug!("Generated key: {}, valid for: {:?} seconds", random_id, lifetime); PeerKey { key: random_id.parse::().unwrap(), valid_until: Some(CurrentClock::now_add(&lifetime).unwrap()), } } else { - debug!("Generated key: {}, permanent", random_id); + tracing::debug!("Generated key: {}, permanent", random_id); PeerKey { key: random_id.parse::().unwrap(), diff --git a/src/core/databases/mysql.rs b/src/core/databases/mysql.rs index 3a06c4982..28a5f363b 100644 --- a/src/core/databases/mysql.rs +++ b/src/core/databases/mysql.rs @@ -8,7 +8,6 @@ use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; use r2d2_mysql::MySqlConnectionManager; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::PersistentTorrents; -use tracing::debug; use super::driver::Driver; use super::{Database, Error}; @@ -158,7 +157,7 @@ impl Database for Mysql { let info_hash_str = info_hash.to_string(); - debug!("{}", info_hash_str); + tracing::debug!("{}", info_hash_str); Ok(conn.exec_drop(COMMAND, params! { info_hash_str, completed })?) } diff --git a/src/core/mod.rs b/src/core/mod.rs index a7ad66052..cbdd7bcbc 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -469,7 +469,6 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; -use tracing::debug; use self::auth::Key; use self::error::Error; @@ -656,9 +655,9 @@ impl Tracker { // we are actually handling authentication at the handlers level. So I would extract that // responsibility into another authentication service. - debug!("Before: {peer:?}"); + tracing::debug!("Before: {peer:?}"); peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip)); - debug!("After: {peer:?}"); + tracing::debug!("After: {peer:?}"); let stats = self.upsert_peer_and_get_stats(info_hash, peer); diff --git a/src/core/statistics.rs b/src/core/statistics.rs index bcafda17f..c9681d23c 100644 --- a/src/core/statistics.rs +++ b/src/core/statistics.rs @@ -25,7 +25,6 @@ use futures::FutureExt; use mockall::{automock, predicate::str}; use tokio::sync::mpsc::error::SendError; use tokio::sync::{mpsc, RwLock, RwLockReadGuard}; -use tracing::debug; const CHANNEL_BUFFER_SIZE: usize = 65_535; @@ -182,7 +181,7 @@ async fn event_handler(event: Event, stats_repository: &Repo) { } } - debug!("stats: {:?}", stats_repository.get_stats().await); + tracing::debug!("stats: {:?}", stats_repository.get_stats().await); } /// A trait to allow sending statistics events diff --git a/src/main.rs b/src/main.rs index ab2af65e2..e0b7bc4ab 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,4 @@ use torrust_tracker::{app, bootstrap}; -use tracing::info; #[tokio::main] async fn main() { @@ -10,11 +9,11 @@ async fn main() { // handle the signals tokio::select! { _ = tokio::signal::ctrl_c() => { - info!("Torrust shutting down ..."); + tracing::info!("Torrust shutting down ..."); // Await for all jobs to shutdown futures::future::join_all(jobs).await; - info!("Torrust successfully shutdown."); + tracing::info!("Torrust successfully shutdown."); } } } diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 4901d760d..327cab0c5 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -21,7 +21,7 @@ use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; -use tracing::{Level, Span}; +use tracing::{instrument, Level, Span}; use super::v1; use super::v1::context::health_check::handlers::health_check_handler; @@ -31,6 +31,7 @@ use crate::servers::apis::API_LOG_TARGET; /// Add all API routes to the router. #[allow(clippy::needless_pass_by_value)] +#[instrument(skip(tracker, access_tokens))] pub fn router(tracker: Arc, access_tokens: Arc) -> Router { let router = Router::new(); diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 40c4d0779..31220f497 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -28,11 +28,13 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use axum_server::Handle; +use derive_more::derive::Display; use derive_more::Constructor; use futures::future::BoxFuture; +use thiserror::Error; use tokio::sync::oneshot::{Receiver, Sender}; use torrust_tracker_configuration::AccessTokens; -use tracing::{debug, error, info}; +use tracing::{instrument, Level}; use super::routes::router; use crate::bootstrap::jobs::Started; @@ -44,9 +46,10 @@ use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, Servi use crate::servers::signals::{graceful_shutdown, Halted}; /// Errors that can occur when starting or stopping the API server. -#[derive(Debug)] +#[derive(Debug, Error)] pub enum Error { - Error(String), + #[error("Error when starting or stopping the API server")] + FailedToStartOrStop(String), } /// An alias for the `ApiServer` struct with the `Stopped` state. @@ -63,18 +66,26 @@ pub type RunningApiServer = ApiServer; /// It's a state machine that can be in one of two /// states: `Stopped` or `Running`. #[allow(clippy::module_name_repetitions)] -pub struct ApiServer { +#[derive(Debug, Display)] +pub struct ApiServer +where + S: std::fmt::Debug + std::fmt::Display, +{ pub state: S, } /// The `Stopped` state of the `ApiServer` struct. +#[derive(Debug, Display)] +#[display("Stopped: {launcher}")] pub struct Stopped { launcher: Launcher, } /// The `Running` state of the `ApiServer` struct. +#[derive(Debug, Display)] +#[display("Running (with local address): {local_addr}")] pub struct Running { - pub binding: SocketAddr, + pub local_addr: SocketAddr, pub halt_task: tokio::sync::oneshot::Sender, pub task: tokio::task::JoinHandle, } @@ -82,12 +93,12 @@ pub struct Running { impl Running { #[must_use] pub fn new( - binding: SocketAddr, + local_addr: SocketAddr, halt_task: tokio::sync::oneshot::Sender, task: tokio::task::JoinHandle, ) -> Self { Self { - binding, + local_addr, halt_task, task, } @@ -111,6 +122,7 @@ impl ApiServer { /// # Panics /// /// It would panic if the bound socket address cannot be sent back to this starter. + #[instrument(skip(self, tracker, form, access_tokens), err, ret(Display, level = Level::INFO))] pub async fn start( self, tracker: Arc, @@ -123,11 +135,11 @@ impl ApiServer { let launcher = self.state.launcher; let task = tokio::spawn(async move { - debug!(target: API_LOG_TARGET, "Starting with launcher in spawned task ..."); + tracing::debug!(target: API_LOG_TARGET, "Starting with launcher in spawned task ..."); let _task = launcher.start(tracker, access_tokens, tx_start, rx_halt).await; - debug!(target: API_LOG_TARGET, "Started with launcher in spawned task"); + tracing::debug!(target: API_LOG_TARGET, "Started with launcher in spawned task"); launcher }); @@ -143,7 +155,7 @@ impl ApiServer { } Err(err) => { let msg = format!("Unable to start API server: {err}"); - error!("{}", msg); + tracing::error!("{}", msg); panic!("{}", msg); } }; @@ -158,13 +170,14 @@ impl ApiServer { /// # Errors /// /// It would return an error if the channel for the task killer signal was closed. + #[instrument(skip(self), err, ret(Display, level = Level::INFO))] pub async fn stop(self) -> Result, Error> { self.state .halt_task .send(Halted::Normal) - .map_err(|_| Error::Error("Task killer channel was closed.".to_string()))?; + .map_err(|_| Error::FailedToStartOrStop("Task killer channel was closed.".to_string()))?; - let launcher = self.state.task.await.map_err(|e| Error::Error(e.to_string()))?; + let launcher = self.state.task.await.map_err(|e| Error::FailedToStartOrStop(e.to_string()))?; Ok(ApiServer { state: Stopped { launcher }, @@ -179,6 +192,7 @@ impl ApiServer { /// This function will return an error if unable to connect. /// Or if there request returns an error code. #[must_use] +#[instrument(skip())] pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { let url = format!("http://{binding}/api/health_check"); // DevSkim: ignore DS137138 @@ -200,6 +214,16 @@ pub struct Launcher { tls: Option, } +impl std::fmt::Display for Launcher { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if self.tls.is_some() { + write!(f, "(with socket): {}, using TLS", self.bind_to,) + } else { + write!(f, "(with socket): {}, without TLS", self.bind_to,) + } + } +} + impl Launcher { /// Starts the API server with graceful shutdown. /// @@ -211,6 +235,7 @@ impl Launcher { /// /// Will panic if unable to bind to the socket, or unable to get the address of the bound socket. /// Will also panic if unable to send message regarding the bound socket address. + #[instrument(skip(self, tracker, access_tokens, tx_start, rx_halt))] pub fn start( &self, tracker: Arc, @@ -233,7 +258,7 @@ impl Launcher { let tls = self.tls.clone(); let protocol = if tls.is_some() { "https" } else { "http" }; - info!(target: API_LOG_TARGET, "Starting on {protocol}://{}", address); + tracing::info!(target: API_LOG_TARGET, "Starting on {protocol}://{}", address); let running = Box::pin(async { match tls { @@ -254,7 +279,7 @@ impl Launcher { } }); - info!(target: API_LOG_TARGET, "{STARTED_ON} {protocol}://{}", address); + tracing::info!(target: API_LOG_TARGET, "{STARTED_ON} {protocol}://{}", address); tx_start .send(Started { address }) diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/src/servers/apis/v1/context/torrent/handlers.rs index b2418c689..ebca504fd 100644 --- a/src/servers/apis/v1/context/torrent/handlers.rs +++ b/src/servers/apis/v1/context/torrent/handlers.rs @@ -11,7 +11,6 @@ use serde::{de, Deserialize, Deserializer}; use thiserror::Error; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; -use tracing::debug; use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response}; use crate::core::services::torrent::{get_torrent_info, get_torrents, get_torrents_page}; @@ -77,7 +76,7 @@ pub struct QueryParams { /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::torrent#list-torrents) /// for more information about this endpoint. pub async fn get_torrents_handler(State(tracker): State>, pagination: Query) -> Response { - debug!("pagination: {:?}", pagination); + tracing::debug!("pagination: {:?}", pagination); if pagination.0.info_hashes.is_empty() { torrent_list_response( diff --git a/src/servers/health_check_api/handlers.rs b/src/servers/health_check_api/handlers.rs index 944e84a1d..fe65e996b 100644 --- a/src/servers/health_check_api/handlers.rs +++ b/src/servers/health_check_api/handlers.rs @@ -2,6 +2,7 @@ use std::collections::VecDeque; use axum::extract::State; use axum::Json; +use tracing::{instrument, Level}; use super::resources::{CheckReport, Report}; use super::responses; @@ -11,6 +12,7 @@ use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, Servi /// /// Creates a vector [`CheckReport`] from the input set of [`CheckJob`], and then builds a report from the results. /// +#[instrument(skip(register), ret(level = Level::DEBUG))] pub(crate) async fn health_check_handler(State(register): State) -> Json { #[allow(unused_assignments)] let mut checks: VecDeque = VecDeque::new(); diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index 89fbafe45..df4b1cf69 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -18,7 +18,7 @@ use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; -use tracing::{debug, Level, Span}; +use tracing::{instrument, Level, Span}; use crate::bootstrap::jobs::Started; use crate::servers::health_check_api::handlers::health_check_handler; @@ -31,6 +31,7 @@ use crate::servers::signals::{graceful_shutdown, Halted}; /// # Panics /// /// Will panic if binding to the socket address fails. +#[instrument(skip(bind_to, tx, rx_halt, register))] pub fn start( bind_to: SocketAddr, tx: Sender, @@ -81,7 +82,7 @@ pub fn start( let handle = Handle::new(); - debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting service with graceful shutdown in a spawned task ..."); + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting service with graceful shutdown in a spawned task ..."); tokio::task::spawn(graceful_shutdown( handle.clone(), diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 4a6dccc6a..560d91681 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -7,7 +7,7 @@ use axum_server::Handle; use derive_more::Constructor; use futures::future::BoxFuture; use tokio::sync::oneshot::{Receiver, Sender}; -use tracing::info; +use tracing::instrument; use super::v1::routes::router; use crate::bootstrap::jobs::Started; @@ -42,6 +42,7 @@ pub struct Launcher { } impl Launcher { + #[instrument(skip(self, tracker, tx_start, rx_halt))] fn start(&self, tracker: Arc, tx_start: Sender, rx_halt: Receiver) -> BoxFuture<'static, ()> { let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); @@ -57,7 +58,7 @@ impl Launcher { let tls = self.tls.clone(); let protocol = if tls.is_some() { "https" } else { "http" }; - info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{}", address); + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{}", address); let app = router(tracker, address); @@ -80,7 +81,7 @@ impl Launcher { } }); - info!(target: HTTP_TRACKER_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", address); + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", address); tx_start .send(Started { address }) diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 0c1d2fdac..ee70b7841 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -14,7 +14,6 @@ use axum::extract::State; use axum::response::{IntoResponse, Response}; use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::peer; -use tracing::debug; use crate::core::auth::Key; use crate::core::{AnnounceData, Tracker}; @@ -36,7 +35,7 @@ pub async fn handle_without_key( ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { - debug!("http announce request: {:#?}", announce_request); + tracing::debug!("http announce request: {:#?}", announce_request); handle(&tracker, &announce_request, &client_ip_sources, None).await } @@ -50,7 +49,7 @@ pub async fn handle_with_key( ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, ) -> Response { - debug!("http announce request: {:#?}", announce_request); + tracing::debug!("http announce request: {:#?}", announce_request); handle(&tracker, &announce_request, &client_ip_sources, Some(key)).await } diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index eb8875a58..ca4c85207 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -9,7 +9,6 @@ use std::sync::Arc; use axum::extract::State; use axum::response::{IntoResponse, Response}; -use tracing::debug; use crate::core::auth::Key; use crate::core::{ScrapeData, Tracker}; @@ -28,7 +27,7 @@ pub async fn handle_without_key( ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { - debug!("http scrape request: {:#?}", &scrape_request); + tracing::debug!("http scrape request: {:#?}", &scrape_request); handle(&tracker, &scrape_request, &client_ip_sources, None).await } @@ -44,7 +43,7 @@ pub async fn handle_with_key( ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, ) -> Response { - debug!("http scrape request: {:#?}", &scrape_request); + tracing::debug!("http scrape request: {:#?}", &scrape_request); handle(&tracker, &scrape_request, &client_ip_sources, Some(key)).await } diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index c24797c4a..16e39b61b 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -17,7 +17,7 @@ use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; -use tracing::{Level, Span}; +use tracing::{instrument, Level, Span}; use super::handlers::{announce, health_check, scrape}; use crate::core::Tracker; @@ -28,6 +28,7 @@ use crate::servers::http::HTTP_TRACKER_LOG_TARGET; /// > **NOTICE**: it's added a layer to get the client IP from the connection /// > info. The tracker could use the connection info to get the client IP. #[allow(clippy::needless_pass_by_value)] +#[instrument(skip(tracker, server_socket_addr))] pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { Router::new() // Health check diff --git a/src/servers/registar.rs b/src/servers/registar.rs index 6058595ba..6b67188dc 100644 --- a/src/servers/registar.rs +++ b/src/servers/registar.rs @@ -7,7 +7,6 @@ use std::sync::Arc; use derive_more::Constructor; use tokio::sync::Mutex; use tokio::task::JoinHandle; -use tracing::debug; /// A [`ServiceHeathCheckResult`] is returned by a completed health check. pub type ServiceHeathCheckResult = Result; @@ -82,7 +81,7 @@ impl Registar { /// Inserts a listing into the registry. async fn insert(&self, rx: tokio::sync::oneshot::Receiver) { - debug!("Waiting for the started service to send registration data ..."); + tracing::debug!("Waiting for the started service to send registration data ..."); let service_registration = rx .await diff --git a/src/servers/signals.rs b/src/servers/signals.rs index 0a1a06312..b83dd5213 100644 --- a/src/servers/signals.rs +++ b/src/servers/signals.rs @@ -3,7 +3,7 @@ use std::time::Duration; use derive_more::Display; use tokio::time::sleep; -use tracing::info; +use tracing::instrument; /// This is the message that the "launcher" spawned task receives from the main /// application process to notify the service to shutdown. @@ -18,6 +18,7 @@ pub enum Halted { /// # Panics /// /// Will panic if the `ctrl_c` or `terminate` signal resolves with an error. +#[instrument(skip())] pub async fn global_shutdown_signal() { let ctrl_c = async { tokio::signal::ctrl_c().await.expect("failed to install Ctrl+C handler"); @@ -35,8 +36,8 @@ pub async fn global_shutdown_signal() { let terminate = std::future::pending::<()>(); tokio::select! { - () = ctrl_c => {}, - () = terminate => {} + () = ctrl_c => {tracing::warn!("caught interrupt signal (ctrl-c), halting...");}, + () = terminate => {tracing::warn!("caught interrupt signal (terminate), halting...");} } } @@ -45,6 +46,7 @@ pub async fn global_shutdown_signal() { /// # Panics /// /// Will panic if the `stop_receiver` resolves with an error. +#[instrument(skip(rx_halt))] pub async fn shutdown_signal(rx_halt: tokio::sync::oneshot::Receiver) { let halt = async { match rx_halt.await { @@ -54,22 +56,24 @@ pub async fn shutdown_signal(rx_halt: tokio::sync::oneshot::Receiver) { }; tokio::select! { - signal = halt => { info!("Halt signal processed: {}", signal) }, - () = global_shutdown_signal() => { info!("Global shutdown signal processed") } + signal = halt => { tracing::debug!("Halt signal processed: {}", signal) }, + () = global_shutdown_signal() => { tracing::debug!("Global shutdown signal processed") } } } /// Same as `shutdown_signal()`, but shows a message when it resolves. +#[instrument(skip(rx_halt))] pub async fn shutdown_signal_with_message(rx_halt: tokio::sync::oneshot::Receiver, message: String) { shutdown_signal(rx_halt).await; - info!("{message}"); + tracing::info!("{message}"); } +#[instrument(skip(handle, rx_halt, message))] pub async fn graceful_shutdown(handle: axum_server::Handle, rx_halt: tokio::sync::oneshot::Receiver, message: String) { shutdown_signal_with_message(rx_halt, message).await; - info!("Sending graceful shutdown signal"); + tracing::debug!("Sending graceful shutdown signal"); handle.graceful_shutdown(Some(Duration::from_secs(90))); println!("!! shuting down in 90 seconds !!"); @@ -77,6 +81,6 @@ pub async fn graceful_shutdown(handle: axum_server::Handle, rx_halt: tokio::sync loop { sleep(Duration::from_secs(1)).await; - info!("remaining alive connections: {}", handle.connection_count()); + tracing::info!("remaining alive connections: {}", handle.connection_count()); } } diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 1ef404ff0..373fb9c14 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -12,7 +12,7 @@ use aquatic_udp_protocol::{ }; use torrust_tracker_located_error::DynError; use torrust_tracker_primitives::info_hash::InfoHash; -use tracing::debug; +use tracing::{instrument, Level}; use uuid::Uuid; use zerocopy::network_endian::I32; @@ -32,8 +32,9 @@ use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; /// - Delegating the request to the correct handler depending on the request type. /// /// It will return an `Error` response if the request is invalid. +#[instrument(skip(udp_request, tracker, local_addr), ret(level = Level::TRACE))] pub(crate) async fn handle_packet(udp_request: RawRequest, tracker: &Tracker, local_addr: SocketAddr) -> Response { - debug!("Handling Packets: {udp_request:?}"); + tracing::debug!("Handling Packets: {udp_request:?}"); let start_time = Instant::now(); @@ -87,8 +88,9 @@ pub(crate) async fn handle_packet(udp_request: RawRequest, tracker: &Tracker, lo /// # Errors /// /// If a error happens in the `handle_request` function, it will just return the `ServerError`. +#[instrument(skip(request, remote_addr, tracker))] pub async fn handle_request(request: Request, remote_addr: SocketAddr, tracker: &Tracker) -> Result { - debug!("Handling Request: {request:?} to: {remote_addr:?}"); + tracing::trace!("handle request"); match request { Request::Connect(connect_request) => handle_connect(remote_addr, &connect_request, tracker).await, @@ -103,8 +105,9 @@ pub async fn handle_request(request: Request, remote_addr: SocketAddr, tracker: /// # Errors /// /// This function does not ever return an error. +#[instrument(skip(tracker), err, ret(level = Level::TRACE))] pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, tracker: &Tracker) -> Result { - debug!("udp connect request: {:#?}", request); + tracing::trace!("handle connect"); let connection_cookie = make(&remote_addr); let connection_id = into_connection_id(&connection_cookie); @@ -114,8 +117,6 @@ pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, t connection_id, }; - debug!("udp connect response: {:#?}", response); - // send stats event match remote_addr { SocketAddr::V4(_) => { @@ -135,12 +136,13 @@ pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, t /// # Errors /// /// If a error happens in the `handle_announce` function, it will just return the `ServerError`. +#[instrument(skip(tracker), err, ret(level = Level::TRACE))] pub async fn handle_announce( remote_addr: SocketAddr, announce_request: &AnnounceRequest, tracker: &Tracker, ) -> Result { - debug!("udp announce request: {:#?}", announce_request); + tracing::trace!("handle announce"); // Authentication if tracker.requires_authentication() { @@ -197,8 +199,6 @@ pub async fn handle_announce( .collect(), }; - debug!("udp announce response: {:#?}", announce_response); - Ok(Response::from(announce_response)) } else { let announce_response = AnnounceResponse { @@ -224,8 +224,6 @@ pub async fn handle_announce( .collect(), }; - debug!("udp announce response: {:#?}", announce_response); - Ok(Response::from(announce_response)) } } @@ -236,8 +234,9 @@ pub async fn handle_announce( /// # Errors /// /// This function does not ever return an error. +#[instrument(skip(tracker), err, ret(level = Level::TRACE))] pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tracker: &Tracker) -> Result { - debug!("udp scrape request: {:#?}", request); + tracing::trace!("handle scrape"); // Convert from aquatic infohashes let mut info_hashes: Vec = vec![]; @@ -283,8 +282,6 @@ pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tra torrent_stats, }; - debug!("udp scrape response: {:#?}", response); - Ok(Response::from(response)) } diff --git a/src/servers/udp/server/bound_socket.rs b/src/servers/udp/server/bound_socket.rs index 42242e44a..658589aa6 100644 --- a/src/servers/udp/server/bound_socket.rs +++ b/src/servers/udp/server/bound_socket.rs @@ -26,7 +26,7 @@ impl BoundSocket { Err(e) => Err(e)?, }; - let local_addr = format!("udp://{addr}"); + let local_addr = format!("udp://{}", socket.local_addr()?); tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "UdpSocket::new (bound)"); Ok(Self { socket }) diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index 7b40f6604..c9ad213f6 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -6,6 +6,7 @@ use derive_more::Constructor; use futures_util::StreamExt; use tokio::select; use tokio::sync::oneshot; +use tracing::instrument; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; @@ -30,17 +31,13 @@ impl Launcher { /// /// It panics if unable to bind to udp socket, and get the address from the udp socket. /// It also panics if unable to send address of socket. + #[instrument(skip(tracker, bind_to, tx_start, rx_halt))] pub async fn run_with_graceful_shutdown( tracker: Arc, bind_to: SocketAddr, tx_start: oneshot::Sender, rx_halt: oneshot::Receiver, ) { - let halt_task = tokio::task::spawn(shutdown_signal_with_message( - rx_halt, - format!("Halting UDP Service Bound to Socket: {bind_to}"), - )); - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting on: {bind_to}"); let socket = tokio::time::timeout(Duration::from_millis(5000), BoundSocket::new(bind_to)) @@ -80,6 +77,11 @@ impl Launcher { let stop = running.abort_handle(); + let halt_task = tokio::task::spawn(shutdown_signal_with_message( + rx_halt, + format!("Halting UDP Service Bound to Socket: {address}"), + )); + select! { _ = running => { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (stopped)"); }, _ = halt_task => { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (halting)"); } @@ -90,6 +92,7 @@ impl Launcher { } #[must_use] + #[instrument(skip(binding))] pub fn check(binding: &SocketAddr) -> ServiceHealthCheckJob { let binding = *binding; let info = format!("checking the udp tracker health check at: {binding}"); @@ -99,6 +102,7 @@ impl Launcher { ServiceHealthCheckJob::new(binding, info, job) } + #[instrument(skip(receiver, tracker))] async fn run_udp_server_main(mut receiver: Receiver, tracker: Arc) { let active_requests = &mut ActiveRequests::default(); diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 16133e21b..d81624cb2 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -1,6 +1,9 @@ //! Module to handle the UDP server instances. use std::fmt::Debug; +use derive_more::derive::Display; +use thiserror::Error; + use super::RawRequest; pub mod bound_socket; @@ -21,11 +24,13 @@ pub mod states; /// Some errors triggered while stopping the server are: /// /// - The [`Server`] cannot send the shutdown signal to the spawned UDP service thread. -#[derive(Debug)] +#[derive(Debug, Error)] pub enum UdpError { - /// Any kind of error starting or stopping the server. - Socket(std::io::Error), - Error(String), + #[error("Any error to do with the socket")] + FailedToBindSocket(std::io::Error), + + #[error("Any error to do with starting or stopping the sever")] + FailedToStartOrStopServer(String), } /// A UDP server. @@ -38,7 +43,11 @@ pub enum UdpError { /// > reset to the initial value after stopping the server. This struct is not /// > intended to persist configurations between runs. #[allow(clippy::module_name_repetitions)] -pub struct Server { +#[derive(Debug, Display)] +pub struct Server +where + S: std::fmt::Debug + std::fmt::Display, +{ /// The state of the server: `running` or `stopped`. pub state: S, } diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index e633a2358..9fa28a44d 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -3,10 +3,11 @@ use std::net::SocketAddr; use std::sync::Arc; use aquatic_udp_protocol::Response; +use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; use crate::core::Tracker; -use crate::servers::udp::{handlers, RawRequest, UDP_TRACKER_LOG_TARGET}; +use crate::servers::udp::{handlers, RawRequest}; pub struct Processor { socket: Arc, @@ -18,15 +19,17 @@ impl Processor { Self { socket, tracker } } + #[instrument(skip(self, request))] pub async fn process_request(self, request: RawRequest) { - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, request = %request.from, "Udp::process_request (receiving)"); - let from = request.from; let response = handlers::handle_packet(request, &self.tracker, self.socket.address()).await; self.send_response(from, response).await; } - async fn send_response(self, to: SocketAddr, response: Response) { + #[instrument(skip(self))] + async fn send_response(self, target: SocketAddr, response: Response) { + tracing::debug!("send response"); + let response_type = match &response { Response::Connect(_) => "Connect".to_string(), Response::AnnounceIpv4(_) => "AnnounceIpv4".to_string(), @@ -35,8 +38,6 @@ impl Processor { Response::Error(e) => format!("Error: {e:?}"), }; - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, target = ?to, response_type, "Udp::send_response (sending)"); - let mut writer = Cursor::new(Vec::with_capacity(200)); match response.write_bytes(&mut writer) { @@ -44,23 +45,28 @@ impl Processor { let bytes_count = writer.get_ref().len(); let payload = writer.get_ref(); - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, ?to, bytes_count, "Udp::send_response (sending...)" ); - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, ?to, bytes_count, ?payload, "Udp::send_response (sending...)"); - - self.send_packet(&to, payload).await; - - tracing::trace!(target:UDP_TRACKER_LOG_TARGET, ?to, bytes_count, "Udp::send_response (sent)"); + let () = match self.send_packet(&target, payload).await { + Ok(sent_bytes) => { + if tracing::event_enabled!(Level::TRACE) { + tracing::debug!(%bytes_count, %sent_bytes, ?payload, "sent {response_type}"); + } else { + tracing::debug!(%bytes_count, %sent_bytes, "sent {response_type}"); + } + } + Err(error) => tracing::warn!(%bytes_count, %error, ?payload, "failed to send"), + }; } Err(e) => { - tracing::error!(target: UDP_TRACKER_LOG_TARGET, ?to, response_type, err = %e, "Udp::send_response (error)"); + tracing::error!(%e, "error"); } } } - async fn send_packet(&self, remote_addr: &SocketAddr, payload: &[u8]) { - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, to = %remote_addr, ?payload, "Udp::send_response (sending)"); + #[instrument(skip(self))] + async fn send_packet(&self, target: &SocketAddr, payload: &[u8]) -> std::io::Result { + tracing::trace!("send packet"); // doesn't matter if it reaches or not - drop(self.socket.send_to(payload, remote_addr).await); + self.socket.send_to(payload, target).await } } diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index e4612fbe0..dea293ad7 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -2,6 +2,7 @@ use std::net::SocketAddr; use std::sync::Arc; +use derive_more::derive::Display; use derive_more::Constructor; use tokio::sync::oneshot; use tokio::task::JoinHandle; @@ -11,7 +12,8 @@ use crate::bootstrap::jobs::Started; use crate::core::Tracker; use crate::servers::signals::Halted; -#[derive(Constructor, Copy, Clone, Debug)] +#[derive(Constructor, Copy, Clone, Debug, Display)] +#[display("(with socket): {bind_to}")] pub struct Spawner { pub bind_to: SocketAddr, } diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index d0a2e4e8a..e90c4da54 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -2,8 +2,10 @@ use std::fmt::Debug; use std::net::SocketAddr; use std::sync::Arc; +use derive_more::derive::Display; use derive_more::Constructor; use tokio::task::JoinHandle; +use tracing::{instrument, Level}; use super::spawner::Spawner; use super::{Server, UdpError}; @@ -23,16 +25,18 @@ pub type StoppedUdpServer = Server; pub type RunningUdpServer = Server; /// A stopped UDP server state. - +#[derive(Debug, Display)] +#[display("Stopped: {spawner}")] pub struct Stopped { pub spawner: Spawner, } /// A running UDP server state. -#[derive(Debug, Constructor)] +#[derive(Debug, Display, Constructor)] +#[display("Running (with local address): {local_addr}")] pub struct Running { /// The address where the server is bound. - pub binding: SocketAddr, + pub local_addr: SocketAddr, pub halt_task: tokio::sync::oneshot::Sender, pub task: JoinHandle, } @@ -57,6 +61,7 @@ impl Server { /// /// It panics if unable to receive the bound socket address from service. /// + #[instrument(skip(self, tracker, form), err, ret(Display, level = Level::INFO))] pub async fn start(self, tracker: Arc, form: ServiceRegistrationForm) -> Result, std::io::Error> { let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); @@ -66,20 +71,20 @@ impl Server { // May need to wrap in a task to about a tokio bug. let task = self.state.spawner.spawn_launcher(tracker, tx_start, rx_halt); - let binding = rx_start.await.expect("it should be able to start the service").address; - let local_addr = format!("udp://{binding}"); + let local_addr = rx_start.await.expect("it should be able to start the service").address; - form.send(ServiceRegistration::new(binding, Launcher::check)) + form.send(ServiceRegistration::new(local_addr, Launcher::check)) .expect("it should be able to send service registration"); let running_udp_server: Server = Server { state: Running { - binding, + local_addr, halt_task: tx_halt, task, }, }; + let local_addr = format!("udp://{local_addr}"); tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "UdpServer::start (running)"); Ok(running_udp_server) @@ -98,11 +103,12 @@ impl Server { /// # Panics /// /// It panics if unable to shutdown service. + #[instrument(skip(self), err, ret(Display, level = Level::INFO))] pub async fn stop(self) -> Result, UdpError> { self.state .halt_task .send(Halted::Normal) - .map_err(|e| UdpError::Error(e.to_string()))?; + .map_err(|e| UdpError::FailedToStartOrStopServer(e.to_string()))?; let launcher = self.state.task.await.expect("it should shutdown service"); diff --git a/tests/common/clock.rs b/tests/common/clock.rs index 5d94bb83d..de3cc7c65 100644 --- a/tests/common/clock.rs +++ b/tests/common/clock.rs @@ -1,11 +1,17 @@ use std::time::Duration; use torrust_tracker_clock::clock::Time; +use tracing::level_filters::LevelFilter; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::CurrentClock; #[test] fn it_should_use_stopped_time_for_testing() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + assert_eq!(CurrentClock::dbg_clock_type(), "Stopped".to_owned()); let time = CurrentClock::now(); diff --git a/tests/common/logging.rs b/tests/common/logging.rs new file mode 100644 index 000000000..71be2ece7 --- /dev/null +++ b/tests/common/logging.rs @@ -0,0 +1,30 @@ +#![allow(clippy::doc_markdown)] +//! Logging for the Integration Tests +//! +//! Tests should start their own logging. +//! +//! To find tests that do not start their own logging: +//! +//! ´´´ sh +//! awk 'BEGIN{RS=""; FS="\n"} /#\[tokio::test\]\s*async\s+fn\s+\w+\s*\(\s*\)\s*\{[^}]*\}/ && !/#\[tokio::test\]\s*async\s+fn\s+\w+\s*\(\s*\)\s*\{[^}]*INIT\.call_once/' $(find . -name "*.rs") +//! ´´´ +//! + +use std::sync::Once; + +use tracing::level_filters::LevelFilter; + +#[allow(dead_code)] +pub static INIT: Once = Once::new(); + +#[allow(dead_code)] +pub fn tracing_stderr_init(filter: LevelFilter) { + let builder = tracing_subscriber::fmt() + .with_max_level(filter) + .with_ansi(true) + .with_writer(std::io::stderr); + + builder.pretty().with_file(true).init(); + + tracing::info!("Logging initialized"); +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 281c1fb9c..9589ccb1e 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,4 +1,5 @@ pub mod clock; pub mod fixtures; pub mod http; +pub mod logging; pub mod udp; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 92ef7b70b..2f4606be7 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -13,14 +13,20 @@ use torrust_tracker_primitives::peer; use super::connection_info::ConnectionInfo; -pub struct Environment { +pub struct Environment +where + S: std::fmt::Debug + std::fmt::Display, +{ pub config: Arc, pub tracker: Arc, pub registar: Registar, pub server: ApiServer, } -impl Environment { +impl Environment +where + S: std::fmt::Debug + std::fmt::Display, +{ /// Add a torrent to the tracker pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { self.tracker.upsert_peer_and_get_stats(info_hash, peer); @@ -79,12 +85,12 @@ impl Environment { pub fn get_connection_info(&self) -> ConnectionInfo { ConnectionInfo { - bind_address: self.server.state.binding.to_string(), + bind_address: self.server.state.local_addr.to_string(), api_token: self.config.access_tokens.get("admin").cloned(), } } pub fn bind_address(&self) -> SocketAddr { - self.server.state.binding + self.server.state.local_addr } } diff --git a/tests/servers/api/v1/contract/authentication.rs b/tests/servers/api/v1/contract/authentication.rs index 49981dd02..5c5cd3ae0 100644 --- a/tests/servers/api/v1/contract/authentication.rs +++ b/tests/servers/api/v1/contract/authentication.rs @@ -1,12 +1,18 @@ use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; use crate::common::http::{Query, QueryParam}; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api::v1::asserts::{assert_token_not_valid, assert_unauthorized}; use crate::servers::api::v1::client::Client; use crate::servers::api::Started; #[tokio::test] async fn should_authenticate_requests_by_using_a_token_query_param() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let token = env.get_connection_info().api_token.unwrap(); @@ -22,6 +28,10 @@ async fn should_authenticate_requests_by_using_a_token_query_param() { #[tokio::test] async fn should_not_authenticate_requests_when_the_token_is_missing() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(env.get_connection_info()) @@ -35,6 +45,10 @@ async fn should_not_authenticate_requests_when_the_token_is_missing() { #[tokio::test] async fn should_not_authenticate_requests_when_the_token_is_empty() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(env.get_connection_info()) @@ -48,6 +62,10 @@ async fn should_not_authenticate_requests_when_the_token_is_empty() { #[tokio::test] async fn should_not_authenticate_requests_when_the_token_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(env.get_connection_info()) @@ -61,6 +79,10 @@ async fn should_not_authenticate_requests_when_the_token_is_invalid() { #[tokio::test] async fn should_allow_the_token_query_param_to_be_at_any_position_in_the_url_query() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let token = env.get_connection_info().api_token.unwrap(); diff --git a/tests/servers/api/v1/contract/configuration.rs b/tests/servers/api/v1/contract/configuration.rs index 4220f62d2..be42f16ad 100644 --- a/tests/servers/api/v1/contract/configuration.rs +++ b/tests/servers/api/v1/contract/configuration.rs @@ -7,10 +7,18 @@ // use crate::common::app::setup_with_configuration; // use crate::servers::api::environment::stopped_environment; +use tracing::level_filters::LevelFilter; + +use crate::common::logging::{tracing_stderr_init, INIT}; + #[tokio::test] #[ignore] #[should_panic = "Could not receive bind_address."] async fn should_fail_with_ssl_enabled_and_bad_ssl_config() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // let tracker = setup_with_configuration(&Arc::new(configuration::ephemeral())); // let config = tracker.config.http_api.clone(); diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 41f421ca6..2792a513c 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -3,7 +3,9 @@ use std::time::Duration; use serde::Serialize; use torrust_tracker::core::auth::Key; use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_auth_key_utf8, assert_failed_to_delete_key, assert_failed_to_generate_key, assert_failed_to_reload_keys, @@ -15,6 +17,10 @@ use crate::servers::api::{force_database_error, Started}; #[tokio::test] async fn should_allow_generating_a_new_random_auth_key() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(env.get_connection_info()) @@ -37,6 +43,10 @@ async fn should_allow_generating_a_new_random_auth_key() { #[tokio::test] async fn should_allow_uploading_a_preexisting_auth_key() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(env.get_connection_info()) @@ -59,6 +69,10 @@ async fn should_allow_uploading_a_preexisting_auth_key() { #[tokio::test] async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) @@ -84,6 +98,10 @@ async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() #[tokio::test] async fn should_fail_when_the_auth_key_cannot_be_generated() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; force_database_error(&env.tracker); @@ -102,6 +120,10 @@ async fn should_fail_when_the_auth_key_cannot_be_generated() { #[tokio::test] async fn should_allow_deleting_an_auth_key() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -129,6 +151,10 @@ async fn should_fail_generating_a_new_auth_key_when_the_provided_key_is_invalid( pub seconds_valid: u64, } + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_keys = [ @@ -166,6 +192,10 @@ async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid( pub seconds_valid: String, } + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_key_durations = [ @@ -193,6 +223,10 @@ async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid( #[tokio::test] async fn should_fail_deleting_an_auth_key_when_the_key_id_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_auth_keys = [ @@ -216,6 +250,10 @@ async fn should_fail_deleting_an_auth_key_when_the_key_id_is_invalid() { #[tokio::test] async fn should_fail_when_the_auth_key_cannot_be_deleted() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -238,6 +276,10 @@ async fn should_fail_when_the_auth_key_cannot_be_deleted() { #[tokio::test] async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -273,6 +315,10 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { #[tokio::test] async fn should_allow_reloading_keys() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -290,6 +336,10 @@ async fn should_allow_reloading_keys() { #[tokio::test] async fn should_fail_when_keys_cannot_be_reloaded() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -309,6 +359,10 @@ async fn should_fail_when_keys_cannot_be_reloaded() { #[tokio::test] async fn should_not_allow_reloading_keys_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -336,7 +390,9 @@ mod deprecated_generate_key_endpoint { use torrust_tracker::core::auth::Key; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_auth_key_utf8, assert_failed_to_generate_key, assert_invalid_key_duration_param, assert_token_not_valid, @@ -347,6 +403,10 @@ mod deprecated_generate_key_endpoint { #[tokio::test] async fn should_allow_generating_a_new_auth_key() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -366,6 +426,10 @@ mod deprecated_generate_key_endpoint { #[tokio::test] async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -387,6 +451,10 @@ mod deprecated_generate_key_endpoint { #[tokio::test] async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_key_durations = [ @@ -408,6 +476,10 @@ mod deprecated_generate_key_endpoint { #[tokio::test] async fn should_fail_when_the_auth_key_cannot_be_generated() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; force_database_error(&env.tracker); diff --git a/tests/servers/api/v1/contract/context/health_check.rs b/tests/servers/api/v1/contract/context/health_check.rs index d8dc3c030..af46a5abe 100644 --- a/tests/servers/api/v1/contract/context/health_check.rs +++ b/tests/servers/api/v1/contract/context/health_check.rs @@ -1,11 +1,17 @@ use torrust_tracker::servers::apis::v1::context::health_check::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api::v1::client::get; use crate::servers::api::Started; #[tokio::test] async fn health_check_endpoint_should_return_status_ok_if_api_is_running() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let url = format!("http://{}/api/health_check", env.get_connection_info().bind_address); diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index c4c992484..a034a7778 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -4,7 +4,9 @@ use torrust_tracker::servers::apis::v1::context::stats::resources::Stats; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{assert_stats, assert_token_not_valid, assert_unauthorized}; use crate::servers::api::v1::client::Client; @@ -12,6 +14,10 @@ use crate::servers::api::Started; #[tokio::test] async fn should_allow_getting_tracker_statistics() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; env.add_torrent_peer( @@ -49,6 +55,10 @@ async fn should_allow_getting_tracker_statistics() { #[tokio::test] async fn should_not_allow_getting_tracker_statistics_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index 7ef35e729..f5e930be3 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -5,8 +5,10 @@ use torrust_tracker::servers::apis::v1::context::torrent::resources::torrent::{s use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; use crate::common::http::{Query, QueryParam}; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_bad_request, assert_invalid_infohash_param, assert_not_found, assert_token_not_valid, assert_torrent_info, @@ -20,6 +22,10 @@ use crate::servers::api::Started; #[tokio::test] async fn should_allow_getting_all_torrents() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); @@ -44,6 +50,10 @@ async fn should_allow_getting_all_torrents() { #[tokio::test] async fn should_allow_limiting_the_torrents_in_the_result() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; // torrents are ordered alphabetically by infohashes @@ -73,6 +83,10 @@ async fn should_allow_limiting_the_torrents_in_the_result() { #[tokio::test] async fn should_allow_the_torrents_result_pagination() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; // torrents are ordered alphabetically by infohashes @@ -102,6 +116,10 @@ async fn should_allow_the_torrents_result_pagination() { #[tokio::test] async fn should_allow_getting_a_list_of_torrents_providing_infohashes() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 @@ -144,6 +162,10 @@ async fn should_allow_getting_a_list_of_torrents_providing_infohashes() { #[tokio::test] async fn should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_parsed() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_offsets = [" ", "-1", "1.1", "INVALID OFFSET"]; @@ -161,6 +183,10 @@ async fn should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_ #[tokio::test] async fn should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_parsed() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_limits = [" ", "-1", "1.1", "INVALID LIMIT"]; @@ -178,6 +204,10 @@ async fn should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_p #[tokio::test] async fn should_fail_getting_torrents_when_the_info_hash_parameter_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_info_hashes = [" ", "-1", "1.1", "INVALID INFO_HASH"]; @@ -199,6 +229,10 @@ async fn should_fail_getting_torrents_when_the_info_hash_parameter_is_invalid() #[tokio::test] async fn should_not_allow_getting_torrents_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) @@ -218,6 +252,10 @@ async fn should_not_allow_getting_torrents_for_unauthenticated_users() { #[tokio::test] async fn should_allow_getting_a_torrent_info() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); @@ -247,6 +285,10 @@ async fn should_allow_getting_a_torrent_info() { #[tokio::test] async fn should_fail_while_getting_a_torrent_info_when_the_torrent_does_not_exist() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); @@ -262,6 +304,10 @@ async fn should_fail_while_getting_a_torrent_info_when_the_torrent_does_not_exis #[tokio::test] async fn should_fail_getting_a_torrent_info_when_the_provided_infohash_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; for invalid_infohash in &invalid_infohashes_returning_bad_request() { @@ -281,6 +327,10 @@ async fn should_fail_getting_a_torrent_info_when_the_provided_infohash_is_invali #[tokio::test] async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index 29064ec9e..b30a7dbf8 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -2,7 +2,9 @@ use std::str::FromStr; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_failed_to_reload_whitelist, assert_failed_to_remove_torrent_from_whitelist, assert_failed_to_whitelist_torrent, @@ -16,6 +18,10 @@ use crate::servers::api::{force_database_error, Started}; #[tokio::test] async fn should_allow_whitelisting_a_torrent() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -34,6 +40,10 @@ async fn should_allow_whitelisting_a_torrent() { #[tokio::test] async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -51,6 +61,10 @@ async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() #[tokio::test] async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -72,6 +86,10 @@ async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { #[tokio::test] async fn should_fail_when_the_torrent_cannot_be_whitelisted() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -87,6 +105,10 @@ async fn should_fail_when_the_torrent_cannot_be_whitelisted() { #[tokio::test] async fn should_fail_whitelisting_a_torrent_when_the_provided_infohash_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; for invalid_infohash in &invalid_infohashes_returning_bad_request() { @@ -110,6 +132,10 @@ async fn should_fail_whitelisting_a_torrent_when_the_provided_infohash_is_invali #[tokio::test] async fn should_allow_removing_a_torrent_from_the_whitelist() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -128,6 +154,10 @@ async fn should_allow_removing_a_torrent_from_the_whitelist() { #[tokio::test] async fn should_not_fail_trying_to_remove_a_non_whitelisted_torrent_from_the_whitelist() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let non_whitelisted_torrent_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -143,6 +173,10 @@ async fn should_not_fail_trying_to_remove_a_non_whitelisted_torrent_from_the_whi #[tokio::test] async fn should_fail_removing_a_torrent_from_the_whitelist_when_the_provided_infohash_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; for invalid_infohash in &invalid_infohashes_returning_bad_request() { @@ -166,6 +200,10 @@ async fn should_fail_removing_a_torrent_from_the_whitelist_when_the_provided_inf #[tokio::test] async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -185,6 +223,10 @@ async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { #[tokio::test] async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -209,6 +251,10 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica #[tokio::test] async fn should_allow_reload_the_whitelist_from_the_database() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -234,6 +280,10 @@ async fn should_allow_reload_the_whitelist_from_the_database() { #[tokio::test] async fn should_fail_when_the_whitelist_cannot_be_reloaded_from_the_database() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index 3c3c13151..d40899f98 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -1,12 +1,18 @@ use torrust_tracker::servers::health_check_api::resources::{Report, Status}; use torrust_tracker::servers::registar::Registar; use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::health_check_api::client::get; use crate::servers::health_check_api::Started; #[tokio::test] async fn health_check_endpoint_should_return_status_ok_when_there_is_no_services_registered() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let configuration = configuration::ephemeral_with_no_services(); let env = Started::new(&configuration.health_check_api.into(), Registar::default()).await; @@ -31,13 +37,19 @@ mod api { use torrust_tracker::servers::health_check_api::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api; use crate::servers::health_check_api::client::get; use crate::servers::health_check_api::Started; #[tokio::test] pub(crate) async fn it_should_return_good_health_for_api_service() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let configuration = Arc::new(configuration::ephemeral()); let service = api::Started::new(&configuration).await; @@ -83,6 +95,10 @@ mod api { #[tokio::test] pub(crate) async fn it_should_return_error_when_api_service_was_stopped_after_registration() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let configuration = Arc::new(configuration::ephemeral()); let service = api::Started::new(&configuration).await; @@ -136,13 +152,19 @@ mod http { use torrust_tracker::servers::health_check_api::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::health_check_api::client::get; use crate::servers::health_check_api::Started; use crate::servers::http; #[tokio::test] pub(crate) async fn it_should_return_good_health_for_http_service() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let configuration = Arc::new(configuration::ephemeral()); let service = http::Started::new(&configuration).await; @@ -187,6 +209,10 @@ mod http { #[tokio::test] pub(crate) async fn it_should_return_error_when_http_service_was_stopped_after_registration() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let configuration = Arc::new(configuration::ephemeral()); let service = http::Started::new(&configuration).await; @@ -240,13 +266,19 @@ mod udp { use torrust_tracker::servers::health_check_api::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::health_check_api::client::get; use crate::servers::health_check_api::Started; use crate::servers::udp; #[tokio::test] pub(crate) async fn it_should_return_good_health_for_udp_service() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let configuration = Arc::new(configuration::ephemeral()); let service = udp::Started::new(&configuration).await; @@ -288,6 +320,10 @@ mod udp { #[tokio::test] pub(crate) async fn it_should_return_error_when_udp_service_was_stopped_after_registration() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let configuration = Arc::new(configuration::ephemeral()); let service = udp::Started::new(&configuration).await; diff --git a/tests/servers/health_check_api/environment.rs b/tests/servers/health_check_api/environment.rs index cf0566d67..b101a54e7 100644 --- a/tests/servers/health_check_api/environment.rs +++ b/tests/servers/health_check_api/environment.rs @@ -8,7 +8,6 @@ use torrust_tracker::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TA use torrust_tracker::servers::registar::Registar; use torrust_tracker::servers::signals::{self, Halted}; use torrust_tracker_configuration::HealthCheckApi; -use tracing::debug; #[derive(Debug)] pub enum Error { @@ -49,21 +48,21 @@ impl Environment { let register = self.registar.entries(); - debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Spawning task to launch the service ..."); + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Spawning task to launch the service ..."); let server = tokio::spawn(async move { - debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting the server in a spawned task ..."); + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting the server in a spawned task ..."); server::start(self.state.bind_to, tx_start, rx_halt, register) .await .expect("it should start the health check service"); - debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Server started. Sending the binding {} ...", self.state.bind_to); + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Server started. Sending the binding {} ...", self.state.bind_to); self.state.bind_to }); - debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Waiting for spawning task to send the binding ..."); + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Waiting for spawning task to send the binding ..."); let binding = rx_start.await.expect("it should send service binding").address; diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index edc06fb07..41e92c9d6 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -13,12 +13,18 @@ mod for_all_config_modes { use torrust_tracker::servers::http::v1::handlers::health_check::{Report, Status}; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::client::Client; use crate::servers::http::Started; #[tokio::test] async fn health_check_endpoint_should_return_ok_if_the_http_tracker_is_running() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; let response = Client::new(*env.bind_address()).health_check().await; @@ -32,7 +38,9 @@ mod for_all_config_modes { mod and_running_on_reverse_proxy { use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::asserts::assert_could_not_find_remote_address_on_x_forwarded_for_header_error_response; use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; @@ -40,6 +48,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_http_request_does_not_include_the_xff_http_request_header() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // If the tracker is running behind a reverse proxy, the peer IP is the // right most IP in the `X-Forwarded-For` HTTP header, which is the IP of the proxy's client. @@ -56,6 +68,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_xff_http_request_header_contains_an_invalid_ip() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; let params = QueryBuilder::default().query().params(); @@ -93,8 +109,10 @@ mod for_all_config_modes { use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; use crate::common::fixtures::invalid_info_hashes; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::asserts::{ assert_announce_response, assert_bad_announce_request_error_response, assert_cannot_parse_query_param_error_response, assert_cannot_parse_query_params_error_response, assert_compact_announce_response, assert_empty_announce_response, @@ -107,12 +125,20 @@ mod for_all_config_modes { #[tokio::test] async fn it_should_start_and_stop() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; env.stop().await; } #[tokio::test] async fn should_respond_if_only_the_mandatory_fields_are_provided() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -128,6 +154,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_url_query_component_is_empty() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(*env.bind_address()).get("announce").await; @@ -139,6 +169,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_url_query_parameters_are_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_query_param = "a=b=c"; @@ -154,6 +188,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_a_mandatory_field_is_missing() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; // Without `info_hash` param @@ -191,6 +229,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_info_hash_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -208,6 +250,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_not_fail_when_the_peer_address_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // AnnounceQuery does not even contain the `peer_addr` // The peer IP is obtained in two ways: // 1. If tracker is NOT running `on_reverse_proxy` from the remote client IP. @@ -228,6 +274,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_downloaded_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -247,6 +297,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_uploaded_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -266,6 +320,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_peer_id_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -292,6 +350,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_port_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -311,6 +373,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_left_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -330,6 +396,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_event_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -357,6 +427,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_compact_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -376,6 +450,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_no_peers_if_the_announced_peer_is_the_first_one() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let response = Client::new(*env.bind_address()) @@ -405,6 +483,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_list_of_previously_announced_peers() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -445,6 +527,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_list_of_previously_announced_peers_including_peers_using_ipv4_and_ipv6() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -497,6 +583,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_consider_two_peers_to_be_the_same_when_they_have_the_same_peer_id_even_if_the_ip_is_different() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -521,6 +611,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_compact_response() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // Tracker Returns Compact Peer Lists // https://www.bittorrent.org/beps/bep_0023.html @@ -560,6 +654,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_not_return_the_compact_response_by_default() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // code-review: the HTTP tracker does not return the compact response by default if the "compact" // param is not provided in the announce URL. The BEP 23 suggest to do so. @@ -599,6 +697,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp4_connections_handled_in_statistics() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; Client::new(*env.bind_address()) @@ -616,6 +718,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp6_connections_handled_in_statistics() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) .await .is_err() @@ -640,6 +746,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_not_increase_the_number_of_tcp6_connections_handled_if_the_client_is_not_using_an_ipv6_ip() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // The tracker ignores the peer address in the request param. It uses the client remote ip address. let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -663,6 +773,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp4_announce_requests_handled_in_statistics() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; Client::new(*env.bind_address()) @@ -680,6 +794,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp6_announce_requests_handled_in_statistics() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) .await .is_err() @@ -704,6 +822,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_not_increase_the_number_of_tcp6_announce_requests_handled_if_the_client_is_not_using_an_ipv6_ip() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // The tracker ignores the peer address in the request param. It uses the client remote ip address. let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -727,6 +849,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_assign_to_the_peer_ip_the_remote_client_ip_instead_of_the_peer_address_in_the_request_param() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -756,6 +882,10 @@ mod for_all_config_modes { #[tokio::test] async fn when_the_client_ip_is_a_loopback_ipv4_it_should_assign_to_the_peer_ip_the_external_ip_in_the_tracker_configuration( ) { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + /* We assume that both the client and tracker share the same public IP. client <-> tracker <-> Internet @@ -792,6 +922,10 @@ mod for_all_config_modes { #[tokio::test] async fn when_the_client_ip_is_a_loopback_ipv6_it_should_assign_to_the_peer_ip_the_external_ip_in_the_tracker_configuration( ) { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + /* We assume that both the client and tracker share the same public IP. client <-> tracker <-> Internet @@ -832,6 +966,10 @@ mod for_all_config_modes { #[tokio::test] async fn when_the_tracker_is_behind_a_reverse_proxy_it_should_assign_to_the_peer_ip_the_ip_in_the_x_forwarded_for_http_header( ) { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + /* client <-> http proxy <-> tracker <-> Internet ip: header: config: peer addr: @@ -885,8 +1023,10 @@ mod for_all_config_modes { use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; use crate::common::fixtures::invalid_info_hashes; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::asserts::{ assert_cannot_parse_query_params_error_response, assert_missing_query_params_for_scrape_request_error_response, assert_scrape_response, @@ -896,9 +1036,13 @@ mod for_all_config_modes { use crate::servers::http::responses::scrape::{self, File, ResponseBuilder}; use crate::servers::http::{requests, Started}; - //#[tokio::test] + #[tokio::test] #[allow(dead_code)] async fn should_fail_when_the_request_is_empty() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let response = Client::new(*env.bind_address()).get("scrape").await; @@ -909,6 +1053,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_info_hash_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -926,6 +1074,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_file_with_the_incomplete_peer_when_there_is_one_peer_with_bytes_pending_to_download() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -964,6 +1116,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_file_with_the_complete_peer_when_there_is_one_peer_with_no_bytes_pending_to_download() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1002,6 +1158,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_a_file_with_zeroed_values_when_there_are_no_peers() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1021,6 +1181,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_accept_multiple_infohashes() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash1 = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1047,6 +1211,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_ot_tcp4_scrape_requests_handled_in_statistics() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1070,6 +1238,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_ot_tcp6_scrape_requests_handled_in_statistics() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) .await .is_err() @@ -1107,7 +1279,9 @@ mod configured_as_whitelisted { use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::asserts::{assert_is_announce_response, assert_torrent_not_in_whitelist_error_response}; use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; @@ -1115,6 +1289,10 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_fail_if_the_torrent_is_not_in_the_whitelist() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_listed().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1130,6 +1308,10 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_allow_announcing_a_whitelisted_torrent() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_listed().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1156,7 +1338,9 @@ mod configured_as_whitelisted { use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::asserts::assert_scrape_response; use crate::servers::http::client::Client; use crate::servers::http::responses::scrape::{File, ResponseBuilder}; @@ -1164,6 +1348,10 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_return_the_zeroed_file_when_the_requested_file_is_not_whitelisted() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_listed().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1193,6 +1381,10 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_return_the_file_stats_when_the_requested_file_is_whitelisted() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_listed().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1245,7 +1437,9 @@ mod configured_as_private { use torrust_tracker::core::auth::Key; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::asserts::{assert_authentication_error_response, assert_is_announce_response}; use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; @@ -1253,6 +1447,10 @@ mod configured_as_private { #[tokio::test] async fn should_respond_to_authenticated_peers() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_private().into()).await; let expiring_key = env.tracker.generate_auth_key(Some(Duration::from_secs(60))).await.unwrap(); @@ -1268,6 +1466,10 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_peer_has_not_provided_the_authentication_key() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_private().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1283,6 +1485,10 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_private().into()).await; let invalid_key = "INVALID_KEY"; @@ -1298,6 +1504,10 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_peer_cannot_be_authenticated_with_the_provided_key() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_private().into()).await; // The tracker does not have this key @@ -1323,7 +1533,9 @@ mod configured_as_private { use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::asserts::{assert_authentication_error_response, assert_scrape_response}; use crate::servers::http::client::Client; use crate::servers::http::responses::scrape::{File, ResponseBuilder}; @@ -1331,6 +1543,10 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_private().into()).await; let invalid_key = "INVALID_KEY"; @@ -1346,6 +1562,10 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_zeroed_file_when_the_client_is_not_authenticated() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_private().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1375,6 +1595,10 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_real_file_stats_when_the_client_is_authenticated() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_private().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1415,6 +1639,10 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_zeroed_file_when_the_authentication_key_provided_by_the_client_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // There is not authentication error // code-review: should this really be this way? diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index e37ef7bf0..91f4c4e06 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -10,7 +10,9 @@ use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient use torrust_tracker::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::udp::asserts::is_error_response; use crate::servers::udp::Started; @@ -39,6 +41,10 @@ async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrac #[tokio::test] async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_request() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { @@ -68,12 +74,18 @@ mod receiving_a_connection_request { use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::udp::asserts::is_connect_response; use crate::servers::udp::Started; #[tokio::test] async fn should_return_a_connect_response() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { @@ -111,7 +123,9 @@ mod receiving_an_announce_request { use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::udp::asserts::is_ipv4_announce_response; use crate::servers::udp::contract::send_connection_request; use crate::servers::udp::Started; @@ -152,6 +166,10 @@ mod receiving_an_announce_request { #[tokio::test] async fn should_return_an_announce_response() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { @@ -170,6 +188,10 @@ mod receiving_an_announce_request { #[tokio::test] async fn should_return_many_announce_response() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { @@ -195,13 +217,19 @@ mod receiving_an_scrape_request { use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::udp::asserts::is_scrape_response; use crate::servers::udp::contract::send_connection_request; use crate::servers::udp::Started; #[tokio::test] async fn should_return_a_scrape_response() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index cfc4390c9..b7ac2336c 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -11,14 +11,20 @@ use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer; -pub struct Environment { +pub struct Environment +where + S: std::fmt::Debug + std::fmt::Display, +{ pub config: Arc, pub tracker: Arc, pub registar: Registar, pub server: Server, } -impl Environment { +impl Environment +where + S: std::fmt::Debug + std::fmt::Display, +{ /// Add a torrent to the tracker #[allow(dead_code)] pub fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { @@ -80,7 +86,7 @@ impl Environment { } pub fn bind_address(&self) -> SocketAddr { - self.server.state.binding + self.server.state.local_addr } } @@ -90,11 +96,17 @@ mod tests { use tokio::time::sleep; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::udp::Started; #[tokio::test] async fn it_should_make_and_stop_udp_server() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; sleep(Duration::from_secs(1)).await; env.stop().await;