From dcbf9bf84f62e8f6ce9fe53c0c9a7754d9912005 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 26 Aug 2023 21:15:37 +0200 Subject: [PATCH] dev: more docker work --- .dockerignore | 30 ++--- .gitignore | 3 +- Dockerfile | 38 +++--- README.md | 4 +- bin/install-demo.sh | 8 +- bin/install.sh | 6 +- cSpell.json | 3 + compose.yaml | 2 +- docker/README.md | 12 +- docker/bin/run-local-image.sh | 2 +- docker/bin/run-public-image.sh | 2 +- docker/entry.sh | 17 +++ packages/configuration/src/lib.rs | 112 +++++++++++++++--- .../config/tracker.sqlite3.development.toml | 2 +- .../config/tracker.sqlite3.distribution.toml | 34 ++++++ src/bootstrap/config.rs | 59 +++------ src/lib.rs | 12 +- src/servers/apis/mod.rs | 2 +- src/servers/apis/v1/middlewares/auth.rs | 2 +- 19 files changed, 234 insertions(+), 116 deletions(-) create mode 100644 docker/entry.sh rename config.toml.local => share/default/config/tracker.sqlite3.development.toml (94%) create mode 100644 share/default/config/tracker.sqlite3.distribution.toml diff --git a/.dockerignore b/.dockerignore index 215cf2881..f42859922 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,16 +1,16 @@ -.git -.git-blame-ignore -.github -.gitignore -.vscode -bin/ -config.toml -config.toml.local -cSpell.json -data.db +/.git +/.git-blame-ignore +/.github +/.gitignore +/.vscode +/bin/ +/tracker.* +/cSpell.json +/data.db /docker/bin/ -NOTICE -README.md -rustfmt.toml -storage/ -target/ +/NOTICE +/README.md +/rustfmt.toml +/storage/ +/target/ +/etc/ diff --git a/.gitignore b/.gitignore index 6b58dcb45..2d8d0b8bd 100644 --- a/.gitignore +++ b/.gitignore @@ -3,9 +3,10 @@ /.coverage/ /.idea/ /.vscode/launch.json -/config.toml +/tracker.toml /data.db /database.db /database.json.bz2 /storage/ /target +/tracker.* diff --git a/Dockerfile b/Dockerfile index 356a54c21..fe293fc0a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,15 +8,19 @@ WORKDIR /tmp RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash RUN cargo binstall --no-confirm cargo-chef cargo-nextest - ## Tester Image FROM rust:slim as tester WORKDIR /tmp -### (fixme) https://github.com/cargo-bins/cargo-binstall/issues/1252 -RUN apt-get update; apt-get install -y curl; apt-get autoclean + +RUN apt-get update; apt-get install -y curl sqlite3; apt-get autoclean RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash RUN cargo binstall --no-confirm cargo-nextest +COPY ./share/ /app/share/torrust +RUN mkdir -p /app/share/torrust/default/database/; \ + touch /app/share/torrust/default/database/tracker.sqlite3.db; \ + echo ";" | sqlite3 /app/share/torrust/default/database/tracker.sqlite3.db + ## Chef Prepare (look at project and see wat we need) FROM chef AS recipe @@ -56,20 +60,16 @@ RUN cargo nextest archive --tests --benches --examples --workspace --all-targets # Extract and Test (debug) FROM tester as test_debug WORKDIR /test -COPY . /test/src +COPY . /test/src/ COPY --from=build_debug \ /build/torrust-tracker-debug.tar.zst \ /test/torrust-tracker-debug.tar.zst -RUN mkdir -p /test/test RUN cargo nextest run --workspace-remap /test/src/ --extract-to /test/src/ --no-run --archive-file /test/torrust-tracker-debug.tar.zst RUN cargo nextest run --workspace-remap /test/src/ --target-dir-remap /test/src/target/ --cargo-metadata /test/src/target/nextest/cargo-metadata.json --binaries-metadata /test/src/target/nextest/binaries-metadata.json RUN mkdir -p /app/bin/; cp -l /test/src/target/debug/torrust-tracker /app/bin/torrust-tracker RUN mkdir /app/lib/; cp -l $(realpath $(ldd /app/bin/torrust-tracker | grep "libz\.so\.1" | awk '{print $3}')) /app/lib/libz.so.1 - -RUN chown -R root:root /app -RUN chmod -R u=rw,go=r,a+X /app -RUN chmod -R a+x /app/bin +RUN chown -R root:root /app; chmod -R u=rw,go=r,a+X /app; chmod -R a+x /app/bin # Extract and Test (release) FROM tester as test @@ -83,21 +83,20 @@ RUN cargo nextest run --workspace-remap /test/src/ --target-dir-remap /test/src/ RUN mkdir -p /app/bin/; cp -l /test/src/target/release/torrust-tracker /app/bin/torrust-tracker RUN mkdir -p /app/lib/; cp -l $(realpath $(ldd /app/bin/torrust-tracker | grep "libz\.so\.1" | awk '{print $3}')) /app/lib/libz.so.1 - -RUN chown -R root:root /app -RUN chmod -R u=rw,go=r,a+X /app -RUN chmod -R a+x /app/bin +RUN chown -R root:root /app; chmod -R u=rw,go=r,a+X /app; chmod -R a+x /app/bin ## Runtime -FROM gcr.io/distroless/cc:debug as Runtime +FROM gcr.io/distroless/cc:debug as runtime RUN ["/busybox/cp", "-sp", "/busybox/sh", "/bin/sh"] +ARG TORRUST_TRACKER_PATH_CONFIG="/etc/torrust/tracker/config.toml" ARG USER_ID=1000 ARG UDP_PORT=6969 ARG HTTP_PORT=7070 ARG API_PORT=1212 +ENV TORRUST_TRACKER_PATH_CONFIG=${TORRUST_TRACKER_PATH_CONFIG} ENV USER_ID=${USER_ID} ENV UDP_PORT=${UDP_PORT} ENV HTTP_PORT=${HTTP_PORT} @@ -110,19 +109,26 @@ EXPOSE ${API_PORT}/tcp WORKDIR /home/torrust RUN adduser --disabled-password --uid "${USER_ID}" "torrust" -RUN mkdir -p /var/lib/torrust; chown -R "${USER_ID}":"${USER_ID}" /var/lib/torrust; chmod -R 2775 /var/lib/torrust +RUN mkdir -p /var/lib/torrust/tracker; chown -R "${USER_ID}":"${USER_ID}" /var/lib/torrust; chmod -R 2770 /var/lib/torrust +RUN mkdir -p /etc/torrust/tracker; chown -R "${USER_ID}":"${USER_ID}" /etc/torrust; chmod -R 2770 /etc/torrust ENV ENV=/etc/profile COPY ./docker/motd.debug /etc/motd +COPY --chmod=0555 ./docker/entry.sh /usr/local/bin/entry.sh + +RUN mkdir -p /usr/local/bin; echo "" RUN echo '[ ! -z "$TERM" -a -r /etc/motd ] && cat /etc/motd' >> /etc/profile USER "torrust":"torrust" - +VOLUME /var/lib/torrust/tracker +VOLUME /etc/torrust/tracker +ENTRYPOINT ["entry.sh"] ## Torrust-Tracker (debug) FROM runtime as debug COPY --from=test_debug /app/ /usr/ RUN env +CMD ["sh"] ## Torrust-Tracker (release) (default) FROM runtime as release diff --git a/README.md b/README.md index b419c12c1..37e6c4140 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ git clone https://github.com/torrust/torrust-tracker.git \ && mkdir -p ./storage/ssl_certificates ``` -And then run `cargo run` twice. The first time to generate the `config.toml` file and the second time to run the tracker with the default configuration. +And then run `cargo run` twice. The first time to generate the `tracker.toml` file and the second time to run the tracker with the default configuration. After running the tracker these services will be available: @@ -78,3 +78,5 @@ The project is licensed under a dual license. See [COPYRIGHT](./COPYRIGHT). ## Acknowledgments This project was a joint effort by [Nautilus Cyberneering GmbH](https://nautilus-cyberneering.de/) and [Dutch Bits](https://dutchbits.nl). Also thanks to [Naim A.](https://github.com/naim94a/udpt) and [greatest-ape](https://github.com/greatest-ape/aquatic) for some parts of the code. Further added features and functions thanks to [Power2All](https://github.com/power2all). + + diff --git a/bin/install-demo.sh b/bin/install-demo.sh index 1b829ca1d..9157ecb1a 100755 --- a/bin/install-demo.sh +++ b/bin/install-demo.sh @@ -8,9 +8,9 @@ if [ -d "./storage" ]; then exit 1 fi -# Check if 'config.toml' file exists in the current directory -if [ -f "./config.toml" ]; then - echo "Warning: 'config.toml' file already exists in the root directory. Please remove or rename it before proceeding." +# Check if 'tracker.toml' file exists in the current directory +if [ -f "./tracker.toml" ]; then + echo "Warning: 'tracker.toml' file already exists in the root directory. Please remove or rename it before proceeding." exit 1 fi @@ -20,7 +20,7 @@ if ! command -v sqlite3 &> /dev/null; then exit 1 fi -wget https://raw.githubusercontent.com/torrust/torrust-tracker/v3.0.0-alpha.3/config.toml.local -O config.toml \ +wget https://raw.githubusercontent.com/torrust/torrust-tracker/v3.0.0-alpha.3/tracker.toml.local -O tracker.toml \ && mkdir -p ./storage/database \ && mkdir -p ./storage/ssl_certificates \ && touch ./storage/database/data.db \ diff --git a/bin/install.sh b/bin/install.sh index 82ea940d0..6c1cc06a7 100755 --- a/bin/install.sh +++ b/bin/install.sh @@ -3,8 +3,8 @@ # This script is only intended to be used for local development or testing environments. # Generate the default settings file if it does not exist -if ! [ -f "./config.toml" ]; then - cp ./config.toml.local ./config.toml +if ! [ -f "./tracker.toml" ]; then + cp ./tracker.toml.local ./tracker.toml fi # Generate storage directory if it does not exist @@ -12,7 +12,7 @@ mkdir -p "./storage/database" # Generate the sqlite database if it does not exist if ! [ -f "./storage/database/data.db" ]; then - # todo: it should get the path from config.toml and only do it when we use sqlite + # todo: it should get the path from tracker.toml and only do it when we use sqlite touch ./storage/database/data.db echo ";" | sqlite3 ./storage/database/data.db fi diff --git a/cSpell.json b/cSpell.json index e1583b90e..789184181 100644 --- a/cSpell.json +++ b/cSpell.json @@ -29,6 +29,7 @@ "codegen", "completei", "connectionless", + "Cyberneering", "distroless", "dockerhub", "downloadedi", @@ -49,6 +50,7 @@ "infoschema", "Intermodal", "intervali", + "keyout", "lcov", "leecher", "leechers", @@ -63,6 +65,7 @@ "myacicontext", "Naim", "nanos", + "newkey", "nextest", "nocapture", "nologin", diff --git a/compose.yaml b/compose.yaml index 98444522f..14cdd8e54 100644 --- a/compose.yaml +++ b/compose.yaml @@ -6,7 +6,7 @@ services: tty: true environment: - TORRUST_TRACKER_CONFIG=${TORRUST_TRACKER_CONFIG} - - TORRUST_TRACKER_API_TOKEN=${TORRUST_TRACKER_API_TOKEN:-MyAccessToken} + - TORRUST_TRACKER_API_ADMIN_TOKEN=${TORRUST_TRACKER_API_ADMIN_TOKEN:-MyAccessToken} networks: - server_side ports: diff --git a/docker/README.md b/docker/README.md index 207dadbbc..dbfadd627 100644 --- a/docker/README.md +++ b/docker/README.md @@ -31,7 +31,7 @@ export TORRUST_TRACKER_USER_UID=1000 \ --publish 7070:7070/tcp \ --publish 1212:1212/tcp \ --volume "$(pwd)/storage":"/app/storage" \ - --volume "$(pwd)/config.toml":"/app/config.toml":ro \ + --volume "$(pwd)/tracker.toml":"/app/tracker.toml":ro \ torrust/tracker:3.0.0-alpha.3 ``` @@ -74,14 +74,14 @@ export TORRUST_TRACKER_USER_UID=1000 In both cases, you will need to: - Create the SQLite DB (`data.db`) if you are going to use SQLite. -- Create the configuration file (`config.toml`) before running the tracker. +- Create the configuration file (`tracker.toml`) before running the tracker. - Replace the user UID (`1000`) with yours. > NOTICE: that the `./bin/install.sh` can setup the application for you. But it uses a predefined configuration. Remember to switch to your default docker context `docker context use default` -and to change the API default configuration in `config.toml` to make it +and to change the API default configuration in `tracker.toml` to make it available from the host machine: ```toml @@ -91,7 +91,7 @@ bind_address = "0.0.0.0:1212" ### With docker-compose -The docker-compose configuration includes the MySQL service configuration. If you want to use MySQL instead of SQLite you have to change your `config.toml` configuration: +The docker-compose configuration includes the MySQL service configuration. If you want to use MySQL instead of SQLite you have to change your `tracker.toml` configuration: ```toml db_driver = "MySQL" @@ -170,7 +170,7 @@ If the database, user or permissions are not created the reason could be the MyS ### SSL Certificates -You can use a certificate for localhost. You can create your [localhost certificate](https://letsencrypt.org/docs/certificates-for-localhost/#making-and-trusting-your-own-certificates) and use it in the `storage` folder and the configuration file (`config.toml`). For example: +You can use a certificate for localhost. You can create your [localhost certificate](https://letsencrypt.org/docs/certificates-for-localhost/#making-and-trusting-your-own-certificates) and use it in the `storage` folder and the configuration file (`tracker.toml`). For example: The storage folder must contain your certificates: @@ -184,7 +184,7 @@ storage/ └── localhost.key ``` -You have not enabled it in your `config.toml` file: +You have not enabled it in your `tracker.toml` file: ```toml ... diff --git a/docker/bin/run-local-image.sh b/docker/bin/run-local-image.sh index 133ba4514..14aafd359 100755 --- a/docker/bin/run-local-image.sh +++ b/docker/bin/run-local-image.sh @@ -1,6 +1,6 @@ #!/bin/bash -TORRUST_TRACKER_CONFIG=$(cat config.toml) +TORRUST_TRACKER_CONFIG=$(cat tracker.toml) docker run -it \ --user="$(whoami)" \ diff --git a/docker/bin/run-public-image.sh b/docker/bin/run-public-image.sh index 8573cef71..f90a9a997 100755 --- a/docker/bin/run-public-image.sh +++ b/docker/bin/run-public-image.sh @@ -1,6 +1,6 @@ #!/bin/bash -TORRUST_TRACKER_CONFIG=$(cat config.toml) +TORRUST_TRACKER_CONFIG=$(cat tracker.toml) docker run -it \ --user="$(whoami)" \ diff --git a/docker/entry.sh b/docker/entry.sh new file mode 100644 index 000000000..ece65c8c2 --- /dev/null +++ b/docker/entry.sh @@ -0,0 +1,17 @@ +#!/bin/sh + +default_database="/usr/share/torrust/default/database/tracker.sqlite3.db" +install_database="/var/lib/torrust/tracker/database/sqlite3.db" + +if [ -e "$default_database" ] && [ ! -e "$install_database" ]; then + install -D -m 0640 "$default_database" "$install_database" +fi + +default_config="/usr/share/torrust/default/config/tracker.sqlite3.distribution.toml" +install_config="/etc/torrust/tracker/config.toml" + +if [ -e "$default_config" ] && [ ! -e "$install_config" ]; then + install -D -m 0640 "$default_config" "$install_config" +fi + +exec "$@" diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 6de0e3ed7..c5af41e48 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -4,7 +4,7 @@ //! Torrust Tracker, which is a `BitTorrent` tracker server. //! //! The configuration is loaded from a [TOML](https://toml.io/en/) file -//! `config.toml` in the project root folder or from an environment variable +//! `tracker.toml` in the project root folder or from an environment variable //! with the same content as the file. //! //! When you run the tracker without a configuration file, a new one will be @@ -239,6 +239,67 @@ use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; +/// Information required for loading config +#[derive(Debug, Default, Clone)] +pub struct Info { + tracker_toml: String, + api_admin_token: Option, +} + +impl Info { + /// Build Configuration Info + /// + /// # Examples + /// + /// ``` + /// use torrust_tracker_configuration::Info; + /// + /// let result = Info::new(env_var_config, env_var_path_config, default_path_config, env_var_api_admin_token); + /// assert_eq!(result, ); + /// ``` + /// + /// # Errors + /// + /// Will return `Err` if unable to obtain a configuration. + /// + #[allow(clippy::needless_pass_by_value)] + pub fn new( + env_var_config: String, + env_var_path_config: String, + default_path_config: String, + env_var_api_admin_token: String, + ) -> Result { + let tracker_toml = if let Ok(tracker_toml) = env::var(&env_var_config) { + println!("Loading configuration from env var {env_var_config} ..."); + + tracker_toml + } else { + let config_path = if let Ok(config_path) = env::var(env_var_path_config) { + println!("Loading configuration file: `{config_path}` ..."); + + config_path + } else { + println!("Loading default configuration file: `{default_path_config}` ..."); + + default_path_config + }; + + fs::read_to_string(config_path) + .map_err(|e| Error::UnableToLoadFromConfigFile { + source: (Arc::new(e) as Arc).into(), + })? + .parse() + .map_err(|_e: std::convert::Infallible| Error::Infallible)? + }; + let api_admin_token = env::var(env_var_api_admin_token).ok(); + + Ok(Self { + tracker_toml, + api_admin_token, + }) + } +} + /// Configuration for each UDP tracker. #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct UdpTracker { @@ -298,6 +359,12 @@ pub struct HttpApi { pub access_tokens: HashMap, } +impl HttpApi { + fn override_admin_token(&mut self, api_admin_token: &str) { + self.access_tokens.insert("admin".to_string(), api_admin_token.to_string()); + } +} + impl HttpApi { /// Checks if the given token is one of the token in the configuration. #[must_use] @@ -411,9 +478,17 @@ pub enum Error { source: LocatedError<'static, dyn std::error::Error + Send + Sync>, }, + #[error("Unable to load from Config File: {source}")] + UnableToLoadFromConfigFile { + source: LocatedError<'static, dyn std::error::Error + Send + Sync>, + }, + /// Unable to load the configuration from the configuration file. #[error("Failed processing the configuration: {source}")] ConfigError { source: LocatedError<'static, ConfigError> }, + + #[error("The error for errors that can never happen.")] + Infallible, } impl From for Error { @@ -471,6 +546,10 @@ impl Default for Configuration { } impl Configuration { + fn override_api_admin_token(&mut self, api_admin_token: &str) { + self.http_api.override_admin_token(api_admin_token); + } + /// Returns the tracker public IP address id defined in the configuration, /// and `None` otherwise. #[must_use] @@ -514,26 +593,25 @@ impl Configuration { Ok(config) } - /// Loads the configuration from the environment variable. The whole - /// configuration must be in the environment variable. It contains the same - /// configuration as the configuration file with the same format. + /// Loads the configuration from the `Info` struct. The whole + /// configuration in toml format is included in the `info.tracker_toml` string. + /// + /// Optionally will override the admin api token. /// /// # Errors /// /// Will return `Err` if the environment variable does not exist or has a bad configuration. - pub fn load_from_env_var(config_env_var_name: &str) -> Result { - match env::var(config_env_var_name) { - Ok(config_toml) => { - let config_builder = Config::builder() - .add_source(File::from_str(&config_toml, FileFormat::Toml)) - .build()?; - let config = config_builder.try_deserialize()?; - Ok(config) - } - Err(e) => Err(Error::UnableToLoadFromEnvironmentVariable { - source: (Arc::new(e) as Arc).into(), - }), - } + pub fn load(info: &Info) -> Result { + let config_builder = Config::builder() + .add_source(File::from_str(&info.tracker_toml, FileFormat::Toml)) + .build()?; + let mut config: Configuration = config_builder.try_deserialize()?; + + if let Some(ref token) = info.api_admin_token { + config.override_api_admin_token(token); + }; + + Ok(config) } /// Saves the configuration to the configuration file. diff --git a/config.toml.local b/share/default/config/tracker.sqlite3.development.toml similarity index 94% rename from config.toml.local rename to share/default/config/tracker.sqlite3.development.toml index be6a11a56..0bc46cfe0 100644 --- a/config.toml.local +++ b/share/default/config/tracker.sqlite3.development.toml @@ -1,7 +1,7 @@ log_level = "info" mode = "public" db_driver = "Sqlite3" -db_path = "./storage/database/data.db" +db_path = "./storage/database/sqlite3.db" announce_interval = 120 min_announce_interval = 120 on_reverse_proxy = false diff --git a/share/default/config/tracker.sqlite3.distribution.toml b/share/default/config/tracker.sqlite3.distribution.toml new file mode 100644 index 000000000..3bb4d3a51 --- /dev/null +++ b/share/default/config/tracker.sqlite3.distribution.toml @@ -0,0 +1,34 @@ +log_level = "info" +mode = "public" +db_driver = "Sqlite3" +db_path = "/var/lib/torrust/tracker/database/sqlite3.db" +announce_interval = 120 +min_announce_interval = 120 +on_reverse_proxy = false +external_ip = "0.0.0.0" +tracker_usage_statistics = true +persistent_torrent_completed_stat = false +max_peer_timeout = 900 +inactive_peer_cleanup_interval = 600 +remove_peerless_torrents = true + +[[udp_trackers]] +enabled = false +bind_address = "0.0.0.0:6969" + +[[http_trackers]] +enabled = false +bind_address = "0.0.0.0:7070" +ssl_enabled = false +ssl_cert_path = "" +ssl_key_path = "" + +[http_api] +enabled = true +bind_address = "127.0.0.1:1212" +ssl_enabled = false +ssl_cert_path = "" +ssl_key_path = "" + +[http_api.access_tokens] +admin = "MyAccessToken" diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 727bf59f7..cb2431f73 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -1,30 +1,28 @@ //! Initialize configuration from file or env var. //! //! All environment variables are prefixed with `TORRUST_TRACKER_BACK_`. -use std::env; -use std::path::Path; -use torrust_tracker_configuration::{Configuration, Error}; +use torrust_tracker_configuration::{Configuration, Info}; // Environment variables -/// The whole `config.toml` file content. It has priority over the config file. +/// The whole `tracker.toml` file content. It has priority over the config file. /// Even if the file is not on the default path. const ENV_VAR_CONFIG: &str = "TORRUST_TRACKER_CONFIG"; +const ENV_VAR_API_ADMIN_TOKEN: &str = "TORRUST_TRACKER_API_ADMIN_TOKEN"; -/// The `config.toml` file location. -pub const ENV_VAR_CONFIG_PATH: &str = "TORRUST_TRACKER_CONFIG_PATH"; +/// The `tracker.toml` file location. +pub const ENV_VAR_PATH_CONFIG: &str = "TORRUST_TRACKER_PATH_CONFIG"; // Default values - -const ENV_VAR_DEFAULT_CONFIG_PATH: &str = "./config.toml"; +pub const DEFAULT_PATH_CONFIG: &str = "./share/default/config/tracker.sqlite3.development.toml"; /// It loads the application configuration from the environment. /// /// There are two methods to inject the configuration: /// -/// 1. By using a config file: `config.toml`. -/// 2. Environment variable: `TORRUST_TRACKER_CONFIG`. The variable contains the same contents as the `config.toml` file. +/// 1. By using a config file: `tracker.toml`. +/// 2. Environment variable: `TORRUST_TRACKER_CONFIG`. The variable contains the same contents as the `tracker.toml` file. /// /// Environment variable has priority over the config file. /// @@ -33,37 +31,16 @@ const ENV_VAR_DEFAULT_CONFIG_PATH: &str = "./config.toml"; /// # Panics /// /// Will panic if it can't load the configuration from either -/// `./config.toml` file or the env var `TORRUST_TRACKER_CONFIG`. +/// `./tracker.toml` file or the env var `TORRUST_TRACKER_CONFIG`. #[must_use] pub fn initialize_configuration() -> Configuration { - if env::var(ENV_VAR_CONFIG).is_ok() { - println!("Loading configuration from env var {ENV_VAR_CONFIG} ..."); - - Configuration::load_from_env_var(ENV_VAR_CONFIG).unwrap() - } else { - let config_path = env::var(ENV_VAR_CONFIG_PATH).unwrap_or_else(|_| ENV_VAR_DEFAULT_CONFIG_PATH.to_string()); - - println!("Loading configuration from configuration file: `{config_path}` ..."); - - load_from_file_or_create_default(&config_path).unwrap() - } -} - -/// Loads the configuration from the configuration file. If the file does -/// not exist, it will create a default configuration file and return an -/// error. -/// -/// # Errors -/// -/// Will return `Err` if `path` does not exist or has a bad configuration. -fn load_from_file_or_create_default(path: &str) -> Result { - if Path::new(&path).is_file() { - Configuration::load_from_file(path) - } else { - println!("Missing configuration file."); - println!("Creating a default configuration file: `{path}` ..."); - let config = Configuration::create_default_configuration_file(path)?; - println!("Please review the config file: `{path}` and restart the tracker if needed."); - Ok(config) - } + let info = Info::new( + ENV_VAR_CONFIG.to_string(), + ENV_VAR_PATH_CONFIG.to_string(), + DEFAULT_PATH_CONFIG.to_string(), + ENV_VAR_API_ADMIN_TOKEN.to_string(), + ) + .unwrap(); + + Configuration::load(&info).unwrap() } diff --git a/src/lib.rs b/src/lib.rs index 28bac9244..e092dfecb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -142,7 +142,7 @@ //! # Configuration //! //! In order to run the tracker you need to provide the configuration. If you run the tracker without providing the configuration, -//! the tracker will generate the default configuration the first time you run it. It will generate a `config.toml` file with +//! the tracker will generate the default configuration the first time you run it. It will generate a `tracker.toml` file with //! in the root directory. //! //! The default configuration is: @@ -188,18 +188,18 @@ //! //! For more information about each service and options you can visit the documentation for the [torrust-tracker-configuration crate](https://docs.rs/torrust-tracker-configuration). //! -//! Alternatively to the `config.toml` file you can use one environment variable `TORRUST_TRACKER_CONFIG` to pass the configuration to the tracker: +//! Alternatively to the `tracker.toml` file you can use one environment variable `TORRUST_TRACKER_CONFIG` to pass the configuration to the tracker: //! //! ```text -//! TORRUST_TRACKER_CONFIG=$(cat config.toml) +//! TORRUST_TRACKER_CONFIG=$(cat tracker.toml) //! cargo run //! ``` //! -//! In the previous example you are just setting the env var with the contents of the `config.toml` file. +//! In the previous example you are just setting the env var with the contents of the `tracker.toml` file. //! -//! The env var contains the same data as the `config.toml`. It's particularly useful in you are [running the tracker with docker](https://github.com/torrust/torrust-tracker/tree/develop/docker). +//! The env var contains the same data as the `tracker.toml`. It's particularly useful in you are [running the tracker with docker](https://github.com/torrust/torrust-tracker/tree/develop/docker). //! -//! > NOTE: The `TORRUST_TRACKER_CONFIG` env var has priority over the `config.toml` file. +//! > NOTE: The `TORRUST_TRACKER_CONFIG` env var has priority over the `tracker.toml` file. //! //! # Usage //! diff --git a/src/servers/apis/mod.rs b/src/servers/apis/mod.rs index eb278bf3c..9b8cd95aa 100644 --- a/src/servers/apis/mod.rs +++ b/src/servers/apis/mod.rs @@ -41,7 +41,7 @@ //! When you run the tracker with enabled API, you will see the following message: //! //! ```text -//! Loading configuration from config file ./config.toml +//! Loading configuration from config file ./tracker.toml //! 023-03-28T12:19:24.963054069+01:00 [torrust_tracker::bootstrap::logging][INFO] logging initialized. //! ... //! 023-03-28T12:19:24.964138723+01:00 [torrust_tracker::bootstrap::jobs::tracker_apis][INFO] Starting Torrust APIs server on: http://0.0.0.0:1212 diff --git a/src/servers/apis/v1/middlewares/auth.rs b/src/servers/apis/v1/middlewares/auth.rs index 41af09031..3e8f74d0c 100644 --- a/src/servers/apis/v1/middlewares/auth.rs +++ b/src/servers/apis/v1/middlewares/auth.rs @@ -11,7 +11,7 @@ //! The token must be one of the `access_tokens` in the tracker //! [HTTP API configuration](torrust_tracker_configuration::HttpApi). //! -//! The configuration file `config.toml` contains a list of tokens: +//! The configuration file `tracker.toml` contains a list of tokens: //! //! ```toml //! [http_api.access_tokens]