From db8294a863658cf375223068a5d902863b5b5629 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 14 Oct 2023 14:38:29 +0200 Subject: [PATCH] dev: upgrade containers many copy-paste from torrust-tracker - intergration tests are disabled for now. --- .github/workflows/container.yaml | 178 +++++ .github/workflows/deployment.yaml | 1 + .github/workflows/publish_docker_image.yaml | 85 --- .github/workflows/test_docker.yaml | 26 - .github/workflows/testing.yaml | 21 - Cargo.lock | 44 +- Cargo.toml | 6 +- Containerfile | 140 ++++ Dockerfile | 72 -- bin/install.sh | 22 - compose.yaml | 31 +- .../dev-tools/container}/build.sh | 0 .../container}/e2e/mysql/e2e-env-reset.sh | 0 .../container}/e2e/mysql/e2e-env-restart.sh | 0 .../container}/e2e/mysql/e2e-env-up.sh | 0 .../dev-tools/container}/e2e/run-e2e-tests.sh | 0 .../container}/e2e/sqlite/e2e-env-reset.sh | 0 .../container}/e2e/sqlite/e2e-env-restart.sh | 0 .../container}/e2e/sqlite/e2e-env-up.sh | 0 .../dev-tools/container}/install.sh | 0 .../dev-tools/container}/run.sh | 0 contrib/dev-tools/init/install-local.sh | 12 + contrib/dev-tools/su-exec/LICENSE | 22 + contrib/dev-tools/su-exec/Makefile | 17 + contrib/dev-tools/su-exec/README.md | 46 ++ contrib/dev-tools/su-exec/su-exec.c | 109 +++ docker/README.md | 157 ----- .../20230510152112_lowercas_infohashes.md | 0 ..._non_standard_fields_in_info_dictionary.md | 0 {adrs => docs/adrs}/README.md | 0 docs/containers.md | 223 ++++++ packages/located-error/Cargo.toml | 21 + packages/located-error/LICENSE | 661 ++++++++++++++++++ packages/located-error/README.md | 11 + packages/located-error/src/lib.rs | 136 ++++ project-words.txt | 4 + share/container/entry_script_sh | 81 +++ share/container/message | 4 + .../default/config/index.container.mysql.toml | 4 + .../config/index.container.sqlite3.toml | 6 +- .../config/index.development.sqlite3.toml | 0 .../config/tracker.container.mysql.toml | 38 + .../config/tracker.container.sqlite3.toml | 34 +- src/bootstrap/config.rs | 74 +- src/config.rs | 145 +++- .../commands/import_tracker_statistics.rs | 4 +- src/{bin => }/main.rs | 4 +- tests/e2e/config.rs | 74 +- tests/e2e/environment.rs | 6 +- 49 files changed, 1998 insertions(+), 521 deletions(-) create mode 100644 .github/workflows/container.yaml delete mode 100644 .github/workflows/publish_docker_image.yaml delete mode 100644 .github/workflows/test_docker.yaml create mode 100644 Containerfile delete mode 100644 Dockerfile delete mode 100755 bin/install.sh rename {docker/bin => contrib/dev-tools/container}/build.sh (100%) rename {docker/bin => contrib/dev-tools/container}/e2e/mysql/e2e-env-reset.sh (100%) rename {docker/bin => contrib/dev-tools/container}/e2e/mysql/e2e-env-restart.sh (100%) rename {docker/bin => contrib/dev-tools/container}/e2e/mysql/e2e-env-up.sh (100%) rename {docker/bin => contrib/dev-tools/container}/e2e/run-e2e-tests.sh (100%) rename {docker/bin => contrib/dev-tools/container}/e2e/sqlite/e2e-env-reset.sh (100%) rename {docker/bin => contrib/dev-tools/container}/e2e/sqlite/e2e-env-restart.sh (100%) rename {docker/bin => contrib/dev-tools/container}/e2e/sqlite/e2e-env-up.sh (100%) rename {docker/bin => contrib/dev-tools/container}/install.sh (100%) rename {docker/bin => contrib/dev-tools/container}/run.sh (100%) create mode 100755 contrib/dev-tools/init/install-local.sh create mode 100644 contrib/dev-tools/su-exec/LICENSE create mode 100644 contrib/dev-tools/su-exec/Makefile create mode 100644 contrib/dev-tools/su-exec/README.md create mode 100644 contrib/dev-tools/su-exec/su-exec.c delete mode 100644 docker/README.md rename {adrs => docs/adrs}/20230510152112_lowercas_infohashes.md (100%) rename {adrs => docs/adrs}/20230824135449_ignore_non_standard_fields_in_info_dictionary.md (100%) rename {adrs => docs/adrs}/README.md (100%) create mode 100644 docs/containers.md create mode 100644 packages/located-error/Cargo.toml create mode 100644 packages/located-error/LICENSE create mode 100644 packages/located-error/README.md create mode 100644 packages/located-error/src/lib.rs create mode 100644 share/container/entry_script_sh create mode 100644 share/container/message rename config-idx-back.mysql.local.toml => share/default/config/index.container.mysql.toml (86%) rename config-idx-back.sqlite.local.toml => share/default/config/index.container.sqlite3.toml (78%) rename config.local.toml => share/default/config/index.development.sqlite3.toml (100%) create mode 100644 share/default/config/tracker.container.mysql.toml rename config-tracker.local.toml => share/default/config/tracker.container.sqlite3.toml (56%) rename src/{bin => }/main.rs (74%) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml new file mode 100644 index 00000000..884a1584 --- /dev/null +++ b/.github/workflows/container.yaml @@ -0,0 +1,178 @@ +name: Container + +on: + push: + branches: + - "develop" + - "main" + - "releases/**/*" + pull_request: + branches: + - "develop" + - "main" + +env: + CARGO_TERM_COLOR: always + +jobs: + test: + name: Test (Docker) + runs-on: ubuntu-latest + + strategy: + matrix: + target: [debug, release] + + steps: + - id: setup + name: Setup Toolchain + uses: docker/setup-buildx-action@v3 + + - id: build + name: Build + uses: docker/build-push-action@v5 + with: + file: ./Containerfile + push: false + load: true + target: ${{ matrix.target }} + tags: torrust-tracker:local + cache-from: type=gha + cache-to: type=gha + + - id: inspect + name: Inspect + run: docker image inspect torrust-tracker:local + + - id: checkout + name: Checkout Repository + uses: actions/checkout@v4 + + - id: compose + name: Compose + run: docker compose build + + context: + name: Context + needs: test + runs-on: ubuntu-latest + + outputs: + continue: ${{ steps.check.outputs.continue }} + type: ${{ steps.check.outputs.type }} + version: ${{ steps.check.outputs.version }} + + steps: + - id: check + name: Check Context + run: | + if [[ "${{ github.repository }}" == "torrust/torrust-tracker" ]]; then + if [[ "${{ github.event_name }}" == "push" ]]; then + if [[ "${{ github.ref }}" == "refs/heads/main" ]]; then + + echo "type=development" >> $GITHUB_OUTPUT + echo "continue=true" >> $GITHUB_OUTPUT + echo "On \`main\` Branch, Type: \`development\`" + + elif [[ "${{ github.ref }}" == "refs/heads/develop" ]]; then + + echo "type=development" >> $GITHUB_OUTPUT + echo "continue=true" >> $GITHUB_OUTPUT + echo "On \`develop\` Branch, Type: \`development\`" + + elif [[ $(echo "${{ github.ref }}" | grep -P '^(refs\/heads\/releases\/)(v)(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$') ]]; then + + version=$(echo "${{ github.ref }}" | sed -n -E 's/^(refs\/heads\/releases\/)//p') + echo "version=$version" >> $GITHUB_OUTPUT + echo "type=release" >> $GITHUB_OUTPUT + echo "continue=true" >> $GITHUB_OUTPUT + echo "In \`releases/$version\` Branch, Type: \`release\`" + + else + echo "Not Correct Branch. Will Not Continue" + fi + else + echo "Not a Push Event. Will Not Continue" + fi + else + echo "On a Forked Repository. Will Not Continue" + fi + + publish_development: + name: Publish (Development) + environment: dockerhub-torrust + needs: context + if: needs.context.outputs.continue == 'true' && needs.context.outputs.type == 'development' + runs-on: ubuntu-latest + + steps: + - id: meta + name: Docker Meta + uses: docker/metadata-action@v5 + with: + images: | + "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" + tags: | + type=ref,event=branch + + - id: login + name: Login to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_HUB_USERNAME }} + password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} + + - id: setup + name: Setup Toolchain + uses: docker/setup-buildx-action@v3 + + - name: Build and push + uses: docker/build-push-action@v5 + with: + file: ./Containerfile + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha + + publish_release: + name: Publish (Release) + environment: dockerhub-torrust + needs: context + if: needs.context.outputs.continue == 'true' && needs.context.outputs.type == 'release' + runs-on: ubuntu-latest + + steps: + - id: meta + name: Docker Meta + uses: docker/metadata-action@v5 + with: + images: | + "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" + tags: | + type=semver,value=${{ needs.context.outputs.version }},pattern={{raw}} + type=semver,value=${{ needs.context.outputs.version }},pattern={{version}} + type=semver,value=${{ needs.context.outputs.version }},pattern=v{{major}} + type=semver,value=${{ needs.context.outputs.version }},pattern={{major}}.{{minor}} + + - id: login + name: Login to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_HUB_USERNAME }} + password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} + + - id: setup + name: Setup Toolchain + uses: docker/setup-buildx-action@v3 + + - name: Build and push + uses: docker/build-push-action@v5 + with: + file: ./Containerfile + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 59688c2e..30b6d5de 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -51,4 +51,5 @@ jobs: env: CARGO_REGISTRY_TOKEN: "${{ secrets.TORRUST_UPDATE_CARGO_REGISTRY_TOKEN }}" run: | + cargo publish -p torrust-index-located-error cargo publish -p torrust-index diff --git a/.github/workflows/publish_docker_image.yaml b/.github/workflows/publish_docker_image.yaml deleted file mode 100644 index 9f8ee15e..00000000 --- a/.github/workflows/publish_docker_image.yaml +++ /dev/null @@ -1,85 +0,0 @@ -name: Publish Docker Image - -on: - push: - branches: - - "main" - - "develop" - tags: - - "v*" - -env: - TORRUST_IDX_BACK_RUN_AS_USER: appuser - -jobs: - check-secret: - runs-on: ubuntu-latest - environment: dockerhub-torrust - outputs: - publish: ${{ steps.check.outputs.publish }} - steps: - - id: check - env: - DOCKER_HUB_USERNAME: "${{ secrets.DOCKER_HUB_USERNAME }}" - if: "${{ env.DOCKER_HUB_USERNAME != '' }}" - run: echo "publish=true" >> $GITHUB_OUTPUT - - test: - needs: check-secret - if: needs.check-secret.outputs.publish == 'true' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - components: llvm-tools-preview - - uses: Swatinem/rust-cache@v2 - - name: Install torrent edition tool (needed for testing) - run: cargo install imdl - - name: Run Tests - run: cargo test - - dockerhub: - needs: test - if: needs.check-secret.outputs.publish == 'true' - runs-on: ubuntu-latest - environment: dockerhub-torrust - steps: - - name: Checkout - uses: actions/checkout@v3 - - - name: Docker meta - id: meta - uses: docker/metadata-action@v4 - with: - images: | - # For example: torrust/index - "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" - tags: | - type=ref,event=branch - type=ref,event=pr - type=semver,pattern={{version}} - type=semver,pattern={{major}}.{{minor}} - - - name: Login to Docker Hub - uses: docker/login-action@v2 - with: - username: ${{ secrets.DOCKER_HUB_USERNAME }} - password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 - - - name: Build and push - uses: docker/build-push-action@v4 - with: - context: . - file: ./Dockerfile - build-args: | - RUN_AS_USER=${{ env.TORRUST_IDX_BACK_RUN_AS_USER }} - push: ${{ github.event_name != 'pull_request' }} - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max diff --git a/.github/workflows/test_docker.yaml b/.github/workflows/test_docker.yaml deleted file mode 100644 index efb54e60..00000000 --- a/.github/workflows/test_docker.yaml +++ /dev/null @@ -1,26 +0,0 @@ -name: Test Docker Build - -on: - push: - pull_request: - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 - - - name: Build docker image - uses: docker/build-push-action@v4 - with: - context: . - file: ./Dockerfile - push: false - cache-from: type=gha - cache-to: type=gha,mode=max - - - name: Build docker-compose images - run: docker compose build diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 395c1d5a..88ebbd9e 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -118,24 +118,3 @@ jobs: - id: coverage name: Generate Coverage Report run: cargo llvm-cov nextest --tests --benches --examples --workspace --all-targets --all-features - - integration: - name: Integrations - runs-on: ubuntu-latest - - steps: - - id: checkout - name: Checkout Repository - uses: actions/checkout@v4 - - - id: setup - name: Setup Toolchain - uses: dtolnay/rust-toolchain@stable - - - id: cache - name: Enable Job Cache - uses: Swatinem/rust-cache@v2 - - - id: test - name: Run Integration Tests - run: ./docker/bin/e2e/run-e2e-tests.sh diff --git a/Cargo.lock b/Cargo.lock index 8f2e0653..5ec37ed0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -494,9 +494,12 @@ dependencies = [ [[package]] name = "deranged" -version = "0.3.8" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2696e8a945f658fd14dc3b87242e6b80cd0f36ff04ea560fa39082368847946" +checksum = "0f32d04922c60427da6f9fef14d042d9edddef64cb9d4ce0d64d0685fbeb1fd3" +dependencies = [ + "powerfmt", +] [[package]] name = "derive-new" @@ -1778,6 +1781,12 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.17" @@ -2784,12 +2793,13 @@ dependencies = [ [[package]] name = "time" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "426f806f4089c493dcac0d24c29c01e2c38baf8e30f1b716ee37e83d200b18fe" +checksum = "c4a34ab300f2dee6e562c10a046fc05e358b29f9bf92277f30c3c8d82275f6f5" dependencies = [ "deranged", "itoa", + "powerfmt", "serde", "time-core", "time-macros", @@ -3021,12 +3031,21 @@ dependencies = [ "thiserror", "tokio", "toml 0.8.2", + "torrust-index-located-error", "tower-http", "urlencoding", "uuid", "which", ] +[[package]] +name = "torrust-index-located-error" +version = "3.0.0-alpha.1-develop" +dependencies = [ + "log", + "thiserror", +] + [[package]] name = "tower" version = "0.4.13" @@ -3078,11 +3097,10 @@ checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" [[package]] name = "tracing" -version = "0.1.37" +version = "0.1.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" +checksum = "ee2ef2af84856a50c1d430afce2fdded0a4ec7eda868db86409b4543df0797f9" dependencies = [ - "cfg-if", "log", "pin-project-lite", "tracing-attributes", @@ -3091,9 +3109,9 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.26" +version = "0.1.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f4f31f56159e98206da9efd823404b79b6ef3143b4a7ab76e67b1751b25a4ab" +checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", @@ -3102,9 +3120,9 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.31" +version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" +checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" dependencies = [ "once_cell", ] @@ -3493,9 +3511,9 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "winnow" -version = "0.5.16" +version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711d82167854aff2018dfd193aa0fef5370f456732f0d5a0c59b0f1b4b907" +checksum = "a3b801d0e0a6726477cc207f60162da452f3a95adb368399bef20a946e06f65c" dependencies = [ "memchr", ] diff --git a/Cargo.toml b/Cargo.toml index afbec95d..3b62dbc9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,6 @@ [package] name = "torrust-index" readme = "README.md" -default-run = "main" authors.workspace = true description.workspace = true @@ -16,7 +15,9 @@ rust-version.workspace = true version.workspace = true [workspace.package] -authors = ["Nautilus Cyberneering , Mick van Dijke "] +authors = [ + "Nautilus Cyberneering , Mick van Dijke ", +] categories = ["network-programming", "web-programming"] description = "A BitTorrent Index" documentation = "https://docs.rs/crate/torrust-tracker/" @@ -91,6 +92,7 @@ tower-http = { version = "0", features = ["cors", "compression-full"] } email_address = "0" hex = "0" uuid = { version = "1", features = ["v4"] } +torrust-index-located-error = { version = "3.0.0-alpha.1-develop", path = "packages/located-error" } [dev-dependencies] rand = "0" diff --git a/Containerfile b/Containerfile new file mode 100644 index 00000000..378a9b10 --- /dev/null +++ b/Containerfile @@ -0,0 +1,140 @@ +# syntax=docker/dockerfile:latest + +# Torrust Index + +## Builder Image +FROM rust:bookworm as chef +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-bookworm as tester +WORKDIR /tmp + +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 imdl + +COPY ./share/ /app/share/torrust +RUN mkdir -p /app/share/torrust/default/database/; \ + sqlite3 /app/share/torrust/default/database/index.sqlite3.db "VACUUM;" + +## Su Exe Compile +FROM docker.io/library/gcc:bookworm as gcc +COPY ./contrib/dev-tools/su-exec/ /usr/local/src/su-exec/ +RUN cc -Wall -Werror -g /usr/local/src/su-exec/su-exec.c -o /usr/local/bin/su-exec; chmod +x /usr/local/bin/su-exec + + +## Chef Prepare (look at project and see wat we need) +FROM chef AS recipe +WORKDIR /build/src +COPY . /build/src +RUN cargo chef prepare --recipe-path /build/recipe.json + + +## Cook (debug) +FROM chef AS dependencies_debug +WORKDIR /build/src +COPY --from=recipe /build/recipe.json /build/recipe.json +RUN cargo chef cook --tests --benches --examples --workspace --all-targets --all-features --recipe-path /build/recipe.json +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/temp.tar.zst ; rm -f /build/temp.tar.zst + +## Cook (release) +FROM chef AS dependencies +WORKDIR /build/src +COPY --from=recipe /build/recipe.json /build/recipe.json +RUN cargo chef cook --tests --benches --examples --workspace --all-targets --all-features --recipe-path /build/recipe.json --release +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/temp.tar.zst --release ; rm -f /build/temp.tar.zst + + +## Build Archive (debug) +FROM dependencies_debug AS build_debug +WORKDIR /build/src +COPY . /build/src +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/torrust-index-debug.tar.zst + +## Build Archive (release) +FROM dependencies AS build +WORKDIR /build/src +COPY . /build/src +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/torrust-index.tar.zst --release + + +# Extract and Test (debug) +FROM tester as test_debug +WORKDIR /test +COPY . /test/src/ +COPY --from=build_debug \ + /build/torrust-index-debug.tar.zst \ + /test/torrust-index-debug.tar.zst +RUN cargo nextest run --workspace-remap /test/src/ --extract-to /test/src/ --no-run --archive-file /test/torrust-index-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-index /app/bin/torrust-index +# RUN mkdir /app/lib/; cp -l $(realpath $(ldd /app/bin/torrust-index | grep "libz\.so\.1" | awk '{print $3}')) /app/lib/libz.so.1 +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 +WORKDIR /test +COPY . /test/src +COPY --from=build \ + /build/torrust-index.tar.zst \ + /test/torrust-index.tar.zst +RUN cargo nextest run --workspace-remap /test/src/ --extract-to /test/src/ --no-run --archive-file /test/torrust-index.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/release/torrust-index /app/bin/torrust-index +# RUN mkdir -p /app/lib/; cp -l $(realpath $(ldd /app/bin/torrust-index | grep "libz\.so\.1" | awk '{print $3}')) /app/lib/libz.so.1 +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-debian12:debug as runtime +RUN ["/busybox/cp", "-sp", "/busybox/sh","/busybox/cat","/busybox/ls","/busybox/env", "/bin/"] +COPY --from=gcc --chmod=0555 /usr/local/bin/su-exec /bin/su-exec + +ARG TORRUST_INDEX_PATH_CONFIG="/etc/torrust/index/index.toml" +ARG TORRUST_INDEX_DATABASE_DRIVER="sqlite3" +ARG USER_ID=1000 +ARG UDP_PORT=6969 +ARG HTTP_PORT=7070 +ARG API_PORT=1212 + +ENV TORRUST_INDEX_PATH_CONFIG=${TORRUST_INDEX_PATH_CONFIG} +ENV TORRUST_INDEX_DATABASE_DRIVER=${TORRUST_INDEX_DATABASE_DRIVER} +ENV USER_ID=${USER_ID} +ENV UDP_PORT=${UDP_PORT} +ENV HTTP_PORT=${HTTP_PORT} +ENV API_PORT=${API_PORT} +ENV TZ=Etc/UTC + +EXPOSE ${UDP_PORT}/udp +EXPOSE ${HTTP_PORT}/tcp +EXPOSE ${API_PORT}/tcp + +RUN mkdir -p /var/lib/torrust/index /var/log/torrust/index /etc/torrust/index + +ENV ENV=/etc/profile +COPY --chmod=0555 ./share/container/entry_script_sh /usr/local/bin/entry.sh + +VOLUME ["/var/lib/torrust/index","/var/log/torrust/index","/etc/torrust/index"] + +ENV RUNTIME="runtime" +ENTRYPOINT ["/usr/local/bin/entry.sh"] + + +## Torrust-Index (debug) +FROM runtime as debug +ENV RUNTIME="debug" +COPY --from=test_debug /app/ /usr/ +RUN env +CMD ["sh"] + +## Torrust-Index (release) (default) +FROM runtime as release +ENV RUNTIME="release" +COPY --from=test /app/ /usr/ +# HEALTHCHECK CMD ["/usr/bin/wget", "--no-verbose", "--tries=1", "--spider", "localhost:${API_PORT}/version"] +CMD ["/usr/bin/torrust-index"] diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index ffdd7ef0..00000000 --- a/Dockerfile +++ /dev/null @@ -1,72 +0,0 @@ -FROM clux/muslrust:stable AS chef -WORKDIR /app -RUN cargo install cargo-chef - - -FROM chef AS planner -WORKDIR /app -COPY . . -RUN cargo chef prepare --recipe-path recipe.json - - -FROM chef as development -WORKDIR /app -ARG UID=1000 -ARG RUN_AS_USER=appuser -ARG IDX_BACK_API_PORT=3001 -# Add the app user for development -ENV USER=appuser -ENV UID=$UID -RUN adduser --uid "${UID}" "${USER}" -# Build dependencies -COPY --from=planner /app/recipe.json recipe.json -RUN cargo chef cook --recipe-path recipe.json -# Build the application -COPY . . -RUN cargo build --bin main -USER $RUN_AS_USER:$RUN_AS_USER -EXPOSE $IDX_BACK_API_PORT/tcp -CMD ["cargo", "run"] - - -FROM chef AS builder -WORKDIR /app -ARG UID=1000 -# Add the app user for production -ENV USER=appuser -ENV UID=$UID -RUN adduser \ - --disabled-password \ - --gecos "" \ - --home "/nonexistent" \ - --shell "/sbin/nologin" \ - --no-create-home \ - --uid "${UID}" \ - "${USER}" -# Build dependencies -COPY --from=planner /app/recipe.json recipe.json -RUN cargo chef cook --release --target x86_64-unknown-linux-musl --recipe-path recipe.json -# Build the application -COPY . . -RUN cargo build --release --target x86_64-unknown-linux-musl --bin main -# Strip the binary -# More info: https://github.com/LukeMathWalker/cargo-chef/issues/149 -RUN strip /app/target/x86_64-unknown-linux-musl/release/main - - -FROM alpine:latest -WORKDIR /app -ARG RUN_AS_USER=appuser -ARG IDX_BACK_API_PORT=3001 -RUN apk --no-cache add ca-certificates -ENV TZ=Etc/UTC -ENV RUN_AS_USER=$RUN_AS_USER -COPY --from=builder /etc/passwd /etc/passwd -COPY --from=builder /etc/group /etc/group -COPY --from=builder --chown=$RUN_AS_USER \ - /app/target/x86_64-unknown-linux-musl/release/main \ - /app/main -RUN chown -R $RUN_AS_USER:$RUN_AS_USER /app -USER $RUN_AS_USER:$RUN_AS_USER -EXPOSE $IDX_BACK_API_PORT/tcp -ENTRYPOINT ["/app/main"] \ No newline at end of file diff --git a/bin/install.sh b/bin/install.sh deleted file mode 100755 index c8fa79ae..00000000 --- a/bin/install.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/bash - -# Generate the default settings file if it does not exist -if ! [ -f "./config.toml" ]; then - cp ./config.local.toml ./config.toml -fi - -# Generate storage directory if it does not exist -mkdir -p "./storage/database" - -# Generate the sqlite database for the index if it does not exist -if ! [ -f "./storage/database/data.db" ]; then - sqlite3 ./storage/database/data.db "VACUUM;" -fi - -# Generate storage directory if it does not exist -mkdir -p "./storage/tracker/lib/database" - -# Generate the sqlite database for the tracker if it does not exist -if ! [ -f "./storage/tracker/lib/database/sqlite3.db" ]; then - sqlite3 ./storage/tracker/lib/database/sqlite3.db "VACUUM;" -fi diff --git a/compose.yaml b/compose.yaml index ad7b0dc7..613ed0b0 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,36 +1,21 @@ name: torrust services: - idx-back: - build: - context: . - args: - RUN_AS_USER: appuser - UID: ${TORRUST_IDX_BACK_USER_UID:-1000} - target: development - user: ${TORRUST_IDX_BACK_USER_UID:-1000}:${TORRUST_IDX_BACK_USER_UID:-1000} + index: + image: torrust-index:release tty: true environment: - - TORRUST_IDX_BACK_CONFIG=${TORRUST_IDX_BACK_CONFIG} - - CARGO_HOME=/home/appuser/.cargo + - TORRUST_INDEX_CONFIG=${TORRUST_TRACKER_CONFIG} + - TORRUST_INDEX_DATABASE_DRIVER=${TORRUST_TRACKER_DATABASE_DRIVER:-sqlite3} + - TORRUST_INDEX_TRACKER_API_TOKEN=${TORRUST_INDEX_TRACKER_API_TOKEN:-MyAccessToken} networks: - server_side ports: - 3001:3001 - # todo: implement healthcheck - #healthcheck: - # test: - # [ - # "CMD-SHELL", - # "cargo run healthcheck" - # ] - # interval: 10s - # retries: 5 - # start_period: 10s - # timeout: 3s volumes: - - ./:/app - - ~/.cargo:/home/appuser/.cargo + - ./storage/tracker/lib:/var/lib/torrust/index:Z + - ./storage/tracker/log:/var/log/torrust/index:Z + - ./storage/tracker/etc:/etc/torrust/index:Z depends_on: - tracker - mailcatcher diff --git a/docker/bin/build.sh b/contrib/dev-tools/container/build.sh similarity index 100% rename from docker/bin/build.sh rename to contrib/dev-tools/container/build.sh diff --git a/docker/bin/e2e/mysql/e2e-env-reset.sh b/contrib/dev-tools/container/e2e/mysql/e2e-env-reset.sh similarity index 100% rename from docker/bin/e2e/mysql/e2e-env-reset.sh rename to contrib/dev-tools/container/e2e/mysql/e2e-env-reset.sh diff --git a/docker/bin/e2e/mysql/e2e-env-restart.sh b/contrib/dev-tools/container/e2e/mysql/e2e-env-restart.sh similarity index 100% rename from docker/bin/e2e/mysql/e2e-env-restart.sh rename to contrib/dev-tools/container/e2e/mysql/e2e-env-restart.sh diff --git a/docker/bin/e2e/mysql/e2e-env-up.sh b/contrib/dev-tools/container/e2e/mysql/e2e-env-up.sh similarity index 100% rename from docker/bin/e2e/mysql/e2e-env-up.sh rename to contrib/dev-tools/container/e2e/mysql/e2e-env-up.sh diff --git a/docker/bin/e2e/run-e2e-tests.sh b/contrib/dev-tools/container/e2e/run-e2e-tests.sh similarity index 100% rename from docker/bin/e2e/run-e2e-tests.sh rename to contrib/dev-tools/container/e2e/run-e2e-tests.sh diff --git a/docker/bin/e2e/sqlite/e2e-env-reset.sh b/contrib/dev-tools/container/e2e/sqlite/e2e-env-reset.sh similarity index 100% rename from docker/bin/e2e/sqlite/e2e-env-reset.sh rename to contrib/dev-tools/container/e2e/sqlite/e2e-env-reset.sh diff --git a/docker/bin/e2e/sqlite/e2e-env-restart.sh b/contrib/dev-tools/container/e2e/sqlite/e2e-env-restart.sh similarity index 100% rename from docker/bin/e2e/sqlite/e2e-env-restart.sh rename to contrib/dev-tools/container/e2e/sqlite/e2e-env-restart.sh diff --git a/docker/bin/e2e/sqlite/e2e-env-up.sh b/contrib/dev-tools/container/e2e/sqlite/e2e-env-up.sh similarity index 100% rename from docker/bin/e2e/sqlite/e2e-env-up.sh rename to contrib/dev-tools/container/e2e/sqlite/e2e-env-up.sh diff --git a/docker/bin/install.sh b/contrib/dev-tools/container/install.sh similarity index 100% rename from docker/bin/install.sh rename to contrib/dev-tools/container/install.sh diff --git a/docker/bin/run.sh b/contrib/dev-tools/container/run.sh similarity index 100% rename from docker/bin/run.sh rename to contrib/dev-tools/container/run.sh diff --git a/contrib/dev-tools/init/install-local.sh b/contrib/dev-tools/init/install-local.sh new file mode 100755 index 00000000..3396c047 --- /dev/null +++ b/contrib/dev-tools/init/install-local.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +# This script is only intended to be used for local development or testing environments. + +# Generate storage directory if it does not exist +mkdir -p ./storage/index/lib/database + +# Generate the sqlite database if it does not exist +if ! [ -f "./storage/index/lib/database/sqlite3.db" ]; then + # todo: it should get the path from tracker.toml and only do it when we use sqlite + sqlite3 ./storage/index/lib/database/sqlite3.db "VACUUM;" +fi diff --git a/contrib/dev-tools/su-exec/LICENSE b/contrib/dev-tools/su-exec/LICENSE new file mode 100644 index 00000000..f623b904 --- /dev/null +++ b/contrib/dev-tools/su-exec/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 ncopa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/contrib/dev-tools/su-exec/Makefile b/contrib/dev-tools/su-exec/Makefile new file mode 100644 index 00000000..bda76895 --- /dev/null +++ b/contrib/dev-tools/su-exec/Makefile @@ -0,0 +1,17 @@ + +CFLAGS ?= -Wall -Werror -g +LDFLAGS ?= + +PROG := su-exec +SRCS := $(PROG).c + +all: $(PROG) + +$(PROG): $(SRCS) + $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) + +$(PROG)-static: $(SRCS) + $(CC) $(CFLAGS) -o $@ $^ -static $(LDFLAGS) + +clean: + rm -f $(PROG) $(PROG)-static diff --git a/contrib/dev-tools/su-exec/README.md b/contrib/dev-tools/su-exec/README.md new file mode 100644 index 00000000..2b051737 --- /dev/null +++ b/contrib/dev-tools/su-exec/README.md @@ -0,0 +1,46 @@ +# su-exec +switch user and group id, setgroups and exec + +## Purpose + +This is a simple tool that will simply execute a program with different +privileges. The program will be executed directly and not run as a child, +like su and sudo does, which avoids TTY and signal issues (see below). + +Notice that su-exec depends on being run by the root user, non-root +users do not have permission to change uid/gid. + +## Usage + +```shell +su-exec user-spec command [ arguments... ] +``` + +`user-spec` is either a user name (e.g. `nobody`) or user name and group +name separated with colon (e.g. `nobody:ftp`). Numeric uid/gid values +can be used instead of names. Example: + +```shell +$ su-exec apache:1000 /usr/sbin/httpd -f /opt/www/httpd.conf +``` + +## TTY & parent/child handling + +Notice how `su` will make `ps` be a child of a shell while `su-exec` +just executes `ps` directly. + +```shell +$ docker run -it --rm alpine:edge su postgres -c 'ps aux' +PID USER TIME COMMAND + 1 postgres 0:00 ash -c ps aux + 12 postgres 0:00 ps aux +$ docker run -it --rm -v $PWD/su-exec:/sbin/su-exec:ro alpine:edge su-exec postgres ps aux +PID USER TIME COMMAND + 1 postgres 0:00 ps aux +``` + +## Why reinvent gosu? + +This does more or less exactly the same thing as [gosu](https://github.com/tianon/gosu) +but it is only 10kb instead of 1.8MB. + diff --git a/contrib/dev-tools/su-exec/su-exec.c b/contrib/dev-tools/su-exec/su-exec.c new file mode 100644 index 00000000..499071c6 --- /dev/null +++ b/contrib/dev-tools/su-exec/su-exec.c @@ -0,0 +1,109 @@ +/* set user and group id and exec */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +static char *argv0; + +static void usage(int exitcode) +{ + printf("Usage: %s user-spec command [args]\n", argv0); + exit(exitcode); +} + +int main(int argc, char *argv[]) +{ + char *user, *group, **cmdargv; + char *end; + + uid_t uid = getuid(); + gid_t gid = getgid(); + + argv0 = argv[0]; + if (argc < 3) + usage(0); + + user = argv[1]; + group = strchr(user, ':'); + if (group) + *group++ = '\0'; + + cmdargv = &argv[2]; + + struct passwd *pw = NULL; + if (user[0] != '\0') { + uid_t nuid = strtol(user, &end, 10); + if (*end == '\0') + uid = nuid; + else { + pw = getpwnam(user); + if (pw == NULL) + err(1, "getpwnam(%s)", user); + } + } + if (pw == NULL) { + pw = getpwuid(uid); + } + if (pw != NULL) { + uid = pw->pw_uid; + gid = pw->pw_gid; + } + + setenv("HOME", pw != NULL ? pw->pw_dir : "/", 1); + + if (group && group[0] != '\0') { + /* group was specified, ignore grouplist for setgroups later */ + pw = NULL; + + gid_t ngid = strtol(group, &end, 10); + if (*end == '\0') + gid = ngid; + else { + struct group *gr = getgrnam(group); + if (gr == NULL) + err(1, "getgrnam(%s)", group); + gid = gr->gr_gid; + } + } + + if (pw == NULL) { + if (setgroups(1, &gid) < 0) + err(1, "setgroups(%i)", gid); + } else { + int ngroups = 0; + gid_t *glist = NULL; + + while (1) { + int r = getgrouplist(pw->pw_name, gid, glist, &ngroups); + + if (r >= 0) { + if (setgroups(ngroups, glist) < 0) + err(1, "setgroups"); + break; + } + + glist = realloc(glist, ngroups * sizeof(gid_t)); + if (glist == NULL) + err(1, "malloc"); + } + } + + if (setgid(gid) < 0) + err(1, "setgid(%i)", gid); + + if (setuid(uid) < 0) + err(1, "setuid(%i)", uid); + + execvp(cmdargv[0], cmdargv); + err(1, "%s", cmdargv[0]); + + return 1; +} diff --git a/docker/README.md b/docker/README.md deleted file mode 100644 index 73e50d08..00000000 --- a/docker/README.md +++ /dev/null @@ -1,157 +0,0 @@ -# Docker - -## Requirements - -- Docker version 20.10.21 -- You need to create the `storage` directory with this structure and files: - -```s -$ tree storage/ -storage/ -└── database -  ├── data.db -   └── tracker.db -``` - -## Dev environment - -### With docker - -Build and run locally: - -```s -docker context use default -export TORRUST_IDX_BACK_USER_UID=$(id -u) -./docker/bin/build.sh $TORRUST_IDX_BACK_USER_UID -./bin/install.sh -./docker/bin/run.sh $TORRUST_IDX_BACK_USER_UID -``` - -Run using the pre-built public docker image: - -```s -export TORRUST_IDX_BACK_USER_UID=$(id -u) -docker run -it \ - --user="$TORRUST_IDX_BACK_USER_UID" \ - --publish 3001:3001/tcp \ - --volume "$(pwd)/storage":"/app/storage" \ - torrust/index -``` - -> NOTES: -> -> - You have to create the SQLite DB (`data.db`) and configuration (`config.toml`) before running the index. See `bin/install.sh`. -> - You have to replace the user UID (`1000`) with yours. -> - Remember to switch to your default docker context `docker context use default`. - -### 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` or `config-idx-back.local.toml` configuration from: - -```toml -connect_url = "sqlite://storage/database/data.db?mode=rwc" -``` - -to: - -```toml -connect_url = "mysql://root:root_secret_password@mysql:3306/torrust_index" -``` - -If you want to inject an environment variable into docker-compose you can use the file `.env`. There is a template `.env.local`. - -Build and run it locally: - -```s -TORRUST_IDX_BACK_USER_UID=${TORRUST_IDX_BACK_USER_UID:-1000} \ - TORRUST_IDX_BACK_CONFIG=$(cat config-idx-back.local.toml) \ - TORRUST_TRACKER_DATABASE_DRIVER=${TORRUST_TRACKER_DATABASE_DRIVER:-mysql} \ - TORRUST_TRACKER_CONFIG=$(cat config-tracker.local.toml) \ - TORRUST_TRACKER_API_ADMIN_TOKEN=${TORRUST_TRACKER_API_ADMIN_TOKEN:-MyAccessToken} \ - docker compose up -d --build -``` - -After running the "up" command you will have three running containers: - -```s -$ docker ps -CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES -e35b14edaceb torrust-idx-back "cargo run" 19 seconds ago Up 17 seconds 0.0.0.0:3001->3001/tcp, :::3001->3001/tcp torrust-idx-back-1 -ddbad9fb496a torrust/tracker:develop "/app/torrust-tracker" 19 seconds ago Up 18 seconds 0.0.0.0:1212->1212/tcp, :::1212->1212/tcp, 0.0.0.0:6969->6969/udp, :::6969->6969/udp, 7070/tcp torrust-tracker-1 -f1d991d62170 mysql:8.0 "docker-entrypoint.s…" 3 hours ago Up 18 seconds (healthy) 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp torrust-mysql-1 - torrust-mysql-1 -``` - -And you should be able to use the application, for example making a request to the API: - - - -The Tracker API is available at: - - - -> NOTICE: You have to bind the tracker services to the wildcard IP `0.0.0.0` to make it accessible from the host. - -You can stop the containers with: - -```s -docker compose down -``` - -Additionally, you can delete all resources (containers, volumes, networks) with: - -```s -docker compose down -v -``` - -### Access Mysql with docker - -These are some useful commands for MySQL. - -Open a shell in the MySQL container using docker or docker-compose. - -```s -docker exec -it torrust-mysql-1 /bin/bash -docker compose exec mysql /bin/bash -``` - -Connect to MySQL from inside the MySQL container or from the host: - -```s -mysql -h127.0.0.1 -uroot -proot_secret_password -``` - -The when MySQL container is started the first time, it creates the database, user, and permissions needed. -If you see the error "Host is not allowed to connect to this MySQL server" you can check that users have the right permissions in the database. Make sure the user `root` and `db_user` can connect from any host (`%`). - -```s -mysql> SELECT host, user FROM mysql.user; -+-----------+------------------+ -| host | user | -+-----------+------------------+ -| % | db_user | -| % | root | -| localhost | mysql.infoschema | -| localhost | mysql.session | -| localhost | mysql.sys | -| localhost | root | -+-----------+------------------+ -6 rows in set (0.00 sec) -``` - -```s -mysql> show databases; -+-----------------------+ -| Database | -+-----------------------+ -| information_schema | -| mysql | -| performance_schema | -| sys | -| torrust_index | -| torrust_tracker | -+-----------------------+ -6 rows in set (0,00 sec) -``` - -If the database, user or permissions are not created the reason could be the MySQL container volume can be corrupted. Delete it and start again the containers. diff --git a/adrs/20230510152112_lowercas_infohashes.md b/docs/adrs/20230510152112_lowercas_infohashes.md similarity index 100% rename from adrs/20230510152112_lowercas_infohashes.md rename to docs/adrs/20230510152112_lowercas_infohashes.md diff --git a/adrs/20230824135449_ignore_non_standard_fields_in_info_dictionary.md b/docs/adrs/20230824135449_ignore_non_standard_fields_in_info_dictionary.md similarity index 100% rename from adrs/20230824135449_ignore_non_standard_fields_in_info_dictionary.md rename to docs/adrs/20230824135449_ignore_non_standard_fields_in_info_dictionary.md diff --git a/adrs/README.md b/docs/adrs/README.md similarity index 100% rename from adrs/README.md rename to docs/adrs/README.md diff --git a/docs/containers.md b/docs/containers.md new file mode 100644 index 00000000..e2185532 --- /dev/null +++ b/docs/containers.md @@ -0,0 +1,223 @@ +# Containers (Docker or Podman) + +## Demo environment +It is simple to setup the index with the default +configuration and run it using the pre-built public docker image: + + +With Docker: + +```sh +docker run -it torrust/index:latest +``` + +or with Podman: + +```sh +podman run -it torrust/index:latest +``` + + +## Requirements +- Tested with recent versions of Docker or Podman. + +## Volumes +The [Containerfile](../Containerfile) (i.e. the Dockerfile) Defines Three Volumes: + +```Dockerfile +VOLUME ["/var/lib/torrust/index","/var/log/torrust/index","/etc/torrust/index"] +``` + +When instancing the container image with the `docker run` or `podman run` command, we map these volumes to the local storage: + +```s +./storage/index/lib -> /var/lib/torrust/index +./storage/index/log -> /var/log/torrust/index +./storage/index/etc -> /etc/torrust/index +``` + +> NOTE: You can adjust this mapping for your preference, however this mapping is the default in our guides and scripts. + +### Pre-Create Host-Mapped Folders: +Please run this command where you wish to run the container: + +```sh +mkdir -p ./storage/index/lib/ ./storage/index/log/ ./storage/index/etc/ +``` + +### Matching Ownership ID's of Host Storage and Container Volumes +It is important that the `torrust` user has the same uid `$(id -u)` as the host mapped folders. In our [entry script](../share/container/entry_script_sh), installed to `/usr/local/bin/entry.sh` inside the container, switches to the `torrust` user created based upon the `USER_UID` environmental variable. + +When running the container, you may use the `--env USER_ID="$(id -u)"` argument that gets the current user-id and passes to the container. + +### Mapped Tree Structure +Using the standard mapping defined above produces this following mapped tree: + +```s +storage/index/ +├── lib +│ ├── database +│ │   └── sqlite3.db => /var/lib/torrust/index/database/sqlite3.db [auto populated] +│ └── tls +│ ├── localhost.crt => /var/lib/torrust/index/tls/localhost.crt [user supplied] +│ └── localhost.key => /var/lib/torrust/index/tls/localhost.key [user supplied] +├── log => /var/log/torrust/index (future use) +└── etc + └── index.toml => /etc/torrust/index/index.toml [auto populated] +``` + +> NOTE: you only need the `tls` directory and certificates in case you have enabled SSL. + +## Building the Container + +### Clone and Change into Repository + +```sh +# Inside your dev folder +git clone https://github.com/torrust/torrust-index.git; cd torrust-index +``` + +### (Docker) Setup Context +Before starting, if you are using docker, it is helpful to reset the context to the default: + +```sh +docker context use default +``` + +### (Docker) Build + +```sh +# Release Mode +docker build --target release --tag torrust-index:release --file Containerfile . + +# Debug Mode +docker build --target debug --tag torrust-index:debug --file Containerfile . +``` + +### (Podman) Build + +```sh +# Release Mode +podman build --target release --tag torrust-index:release --file Containerfile . + +# Debug Mode +podman build --target debug --tag torrust-index:debug --file Containerfile . +``` + +## Running the Container + +### Basic Run +No arguments are needed for simply checking the container image works: + +#### (Docker) Run Basic + +```sh +# Release Mode +docker run -it torrust-index:release + +# Debug Mode +docker run -it torrust-index:debug +``` +#### (Podman) Run Basic + +```sh +# Release Mode +podman run -it torrust-index:release + +# Debug Mode +podman run -it torrust-index:debug +``` + +### Arguments +The arguments need to be placed before the image tag. i.e. + +`run [arguments] torrust-index:release` + +#### Environmental Variables: +Environmental variables are loaded through the `--env`, in the format `--env VAR="value"`. + +The following environmental variables can be set: + +- `TORRUST_INDEX_PATH_CONFIG` - The in-container path to the index configuration file, (default: `"/etc/torrust/index/index.toml"`). +- `TORRUST_INDEX_TRACKER_API_TOKEN` - Override of the admin token. If set, this value overrides any value set in the config. +- `TORRUST_INDEX_DATABASE_DRIVER` - The database type used for the container, (options: `sqlite3`, `mysql`, default `sqlite3`). Please Note: This dose not override the database configuration within the `.toml` config file. +- `TORRUST_INDEX_CONFIG` - Load config from this environmental variable instead from a file, (i.e: `TORRUST_INDEX_CONFIG=$(cat index-index.toml)`). +- `USER_ID` - The user id for the runtime crated `torrust` user. Please Note: This user id should match the ownership of the host-mapped volumes, (default `1000`). +- `UDP_PORT` - The port for the UDP index. This should match the port used in the configuration, (default `6969`). +- `HTTP_PORT` - The port for the HTTP index. This should match the port used in the configuration, (default `7070`). +- `API_PORT` - The port for the index API. This should match the port used in the configuration, (default `1212`). + + +### Sockets +Socket ports used internally within the container can be mapped to with the `--publish` argument. + +The format is: `--publish [optional_host_ip]:[host_port]:[container_port]/[optional_protocol]`, for example: `--publish 127.0.0.1:8080:80/tcp`. + +The default ports can be mapped with the following: + +```s +--publish 0.0.0.0:3001:3001/tcp +``` + +> NOTE: Inside the container it is necessary to expose a socket with the wildcard address `0.0.0.0` so that it may be accessible from the host. Verify that the configuration that the sockets are wildcard. + +### Volumes +By default the container will use install volumes for `/var/lib/torrust/index`, `/var/log/torrust/index`, and `/etc/torrust/index`, however for better administration it good to make these volumes host-mapped. + +The argument to host-map volumes is `--volume`, with the format: `--volume=[host-src:]container-dest[:]`. + +The default mapping can be supplied with the following arguments: + +```s +--volume ./storage/index/lib:/var/lib/torrust/index:Z \ +--volume ./storage/index/log:/var/log/torrust/index:Z \ +--volume ./storage/index/etc:/etc/torrust/index:Z \ +``` + + +Please not the `:Z` at the end of the podman `--volume` mapping arguments, this is to give read-write permission on SELinux enabled systemd, if this doesn't work on your system, you can use `:rw` instead. + +## Complete Example: + +### With Docker + +```sh +## Setup Docker Default Context +docker context use default + +## Build Container Image +docker build --target release --tag torrust-index:release --file Containerfile . + +## Setup Mapped Volumes +mkdir -p ./storage/index/lib/ ./storage/index/log/ ./storage/index/etc/ + +## Run Torrust Index Container Image +docker run -it \ + --env TORRUST_INDEX_TRACKER_API_TOKEN="MySecretToken" \ + --env USER_ID="$(id -u)" \ + --publish 0.0.0.0:3001:3001/tcp \ + --volume ./storage/index/lib:/var/lib/torrust/index:Z \ + --volume ./storage/index/log:/var/log/torrust/index:Z \ + --volume ./storage/index/etc:/etc/torrust/index:Z \ + torrust-index:release +``` + +### With Podman + +```sh +## Build Container Image +podman build --target release --tag torrust-index:release --file Containerfile . + +## Setup Mapped Volumes +mkdir -p ./storage/index/lib/ ./storage/index/log/ ./storage/index/etc/ + +## Run Torrust Index Container Image +podman run -it \ + --env TORRUST_INDEX_TRACKER_API_TOKEN="MySecretToken" \ + --env USER_ID="$(id -u)" \ + --publish 0.0.0.0:3001:3001/tcp \ + --volume ./storage/index/lib:/var/lib/torrust/index:Z \ + --volume ./storage/index/log:/var/log/torrust/index:Z \ + --volume ./storage/index/etc:/etc/torrust/index:Z \ + torrust-index:release +``` diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml new file mode 100644 index 00000000..d8065bca --- /dev/null +++ b/packages/located-error/Cargo.toml @@ -0,0 +1,21 @@ +[package] +description = "A library to provide error decorator with the location and the source of the original error." +keywords = ["errors", "helper", "library"] +name = "torrust-index-located-error" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +log = { version = "0", features = ["release_max_level_info"] } + +[dev-dependencies] +thiserror = "1.0" diff --git a/packages/located-error/LICENSE b/packages/located-error/LICENSE new file mode 100644 index 00000000..0ad25db4 --- /dev/null +++ b/packages/located-error/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/located-error/README.md b/packages/located-error/README.md new file mode 100644 index 00000000..c3c18fa4 --- /dev/null +++ b/packages/located-error/README.md @@ -0,0 +1,11 @@ +# Torrust Tracker Located Error + +A library to provide an error decorator with the location and the source of the original error. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-located-error). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/located-error/src/lib.rs b/packages/located-error/src/lib.rs new file mode 100644 index 00000000..bf861868 --- /dev/null +++ b/packages/located-error/src/lib.rs @@ -0,0 +1,136 @@ +//! This crate provides a wrapper around an error that includes the location of +//! the error. +//! +//! ```rust +//! use std::error::Error; +//! use std::panic::Location; +//! use std::sync::Arc; +//! use torrust_tracker_located_error::{Located, LocatedError}; +//! +//! #[derive(thiserror::Error, Debug)] +//! enum TestError { +//! #[error("Test")] +//! Test, +//! } +//! +//! #[track_caller] +//! fn get_caller_location() -> Location<'static> { +//! *Location::caller() +//! } +//! +//! let e = TestError::Test; +//! +//! let b: LocatedError = Located(e).into(); +//! let l = get_caller_location(); +//! +//! assert!(b.to_string().contains("Test, src/lib.rs")); +//! ``` +//! +//! # Credits +//! +//! +use std::error::Error; +use std::panic::Location; +use std::sync::Arc; + +/// A generic wrapper around an error. +/// +/// Where `E` is the inner error (source error). +pub struct Located(pub E); + +/// A wrapper around an error that includes the location of the error. +#[derive(Debug)] +pub struct LocatedError<'a, E> +where + E: Error + ?Sized + Send + Sync, +{ + source: Arc, + location: Box>, +} + +impl<'a, E> std::fmt::Display for LocatedError<'a, E> +where + E: Error + ?Sized + Send + Sync, +{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}, {}", self.source, self.location) + } +} + +impl<'a, E> Error for LocatedError<'a, E> +where + E: Error + ?Sized + Send + Sync + 'static, +{ + fn source(&self) -> Option<&(dyn Error + 'static)> { + Some(&self.source) + } +} + +impl<'a, E> Clone for LocatedError<'a, E> +where + E: Error + ?Sized + Send + Sync, +{ + fn clone(&self) -> Self { + LocatedError { + source: self.source.clone(), + location: self.location.clone(), + } + } +} + +#[allow(clippy::from_over_into)] +impl<'a, E> Into> for Located +where + E: Error + Send + Sync, + Arc: Clone, +{ + #[track_caller] + fn into(self) -> LocatedError<'a, E> { + let e = LocatedError { + source: Arc::new(self.0), + location: Box::new(*std::panic::Location::caller()), + }; + log::debug!("{e}"); + e + } +} + +#[allow(clippy::from_over_into)] +impl<'a> Into> for Arc { + #[track_caller] + fn into(self) -> LocatedError<'a, dyn std::error::Error + Send + Sync> { + LocatedError { + source: self, + location: Box::new(*std::panic::Location::caller()), + } + } +} + +#[cfg(test)] +mod tests { + use std::panic::Location; + + use super::LocatedError; + use crate::Located; + + #[derive(thiserror::Error, Debug)] + enum TestError { + #[error("Test")] + Test, + } + + #[track_caller] + fn get_caller_location() -> Location<'static> { + *Location::caller() + } + + #[test] + fn error_should_include_location() { + let e = TestError::Test; + + let b: LocatedError<'_, TestError> = Located(e).into(); + let l = get_caller_location(); + + assert_eq!(b.location.file(), l.file()); + } +} diff --git a/project-words.txt b/project-words.txt index 5a52dc61..74e427ce 100644 --- a/project-words.txt +++ b/project-words.txt @@ -7,20 +7,24 @@ bencoded Benoit binascii btih +buildx chrono clippy codecov codegen compatiblelicenses +Containerfile creativecommons creds Culqt Cyberneering datetime DATETIME +dockerhub Dont dotless dtolnay +elif grcov Grünwald hasher diff --git a/share/container/entry_script_sh b/share/container/entry_script_sh new file mode 100644 index 00000000..5f8d9d21 --- /dev/null +++ b/share/container/entry_script_sh @@ -0,0 +1,81 @@ +#!/bin/sh +set -x + +to_lc() { echo "$1" | tr '[:upper:]' '[:lower:]'; } +clean() { echo "$1" | tr -d -c 'a-zA-Z0-9-' ; } +cmp_lc() { [ "$(to_lc "$(clean "$1")")" = "$(to_lc "$(clean "$2")")" ]; } + + +inst() { + if [ -n "$1" ] && [ -n "$2" ] && [ -e "$1" ] && [ ! -e "$2" ]; then + install -D -m 0640 -o torrust -g torrust "$1" "$2"; fi; } + + +# Add torrust user, based upon supplied user-id. +if [ -z "$USER_ID" ] && [ "$USER_ID" -lt 1000 ]; then + echo "ERROR: USER_ID is not set, or less than 1000" + exit 1 +fi + +adduser --disabled-password --shell "/bin/sh" --uid "$USER_ID" "torrust" + +# Configure Permissions for Torrust Folders +mkdir -p /var/lib/torrust/index/database/ /etc/torrust/index/ +chown -R "${USER_ID}" /var/lib/torrust /var/log/torrust /etc/torrust +chmod -R 2770 /var/lib/torrust /var/log/torrust /etc/torrust + + +# Install the database and config: +if [ -n "$TORRUST_INDEX_DATABASE_DRIVER" ]; then + if cmp_lc "$TORRUST_INDEX_DATABASE_DRIVER" "sqlite3"; then + + # Select sqlite3 empty database + default_database="/usr/share/torrust/default/database/index.sqlite3.db" + + # Select sqlite3 default configuration + default_config="/usr/share/torrust/default/config/index.container.sqlite3.toml" + + elif cmp_lc "$TORRUST_INDEX_DATABASE_DRIVER" "mysql"; then + + # (no database file needed for mysql) + + # Select default mysql configuration + default_config="/usr/share/torrust/default/config/index.container.mysql.toml" + + else + echo "Error: Unsupported Database Type: \"$TORRUST_INDEX_DATABASE_DRIVER\"." + echo "Please Note: Supported Database Types: \"sqlite3\", \"mysql\"." + exit 1 + fi +else + echo "Error: \"\$TORRUST_INDEX_DATABASE_DRIVER\" was not set!"; exit 1; +fi + +install_config="/etc/torrust/index/index.toml" +install_database="/var/lib/torrust/index/database/sqlite3.db" + +inst "$default_config" "$install_config" +inst "$default_database" "$install_database" + +# Make Minimal Message of the Day +if cmp_lc "$RUNTIME" "runtime"; then + printf '\n in runtime \n' >> /etc/motd; +elif cmp_lc "$RUNTIME" "debug"; then + printf '\n in debug mode \n' >> /etc/motd; +elif cmp_lc "$RUNTIME" "release"; then + printf '\n in release mode \n' >> /etc/motd; +else + echo "ERROR: running in unknown mode: \"$RUNTIME\""; exit 1 +fi + +if [ -e "/usr/share/torrust/container/message" ]; then + cat "/usr/share/torrust/container/message" >> /etc/motd; chmod 0644 /etc/motd +fi + +# Load message of the day from Profile +echo '[ ! -z "$TERM" -a -r /etc/motd ] && cat /etc/motd' >> /etc/profile + +cd /home/torrust || exit 1 + +# Switch to torrust user +exec /bin/su-exec torrust "$@" diff --git a/share/container/message b/share/container/message new file mode 100644 index 00000000..5a69f106 --- /dev/null +++ b/share/container/message @@ -0,0 +1,4 @@ + +Lovely welcome to our Torrust Index Container! + +run 'torrust-index' to start the index diff --git a/config-idx-back.mysql.local.toml b/share/default/config/index.container.mysql.toml similarity index 86% rename from config-idx-back.mysql.local.toml rename to share/default/config/index.container.mysql.toml index 0e8bd2a8..1999c4a1 100644 --- a/config-idx-back.mysql.local.toml +++ b/share/default/config/index.container.mysql.toml @@ -3,6 +3,10 @@ log_level = "info" [website] name = "Torrust" +# Please override the tracker token setting the +# `TORRUST_INDEX_TRACKER_API_TOKEN` +# environmental variable! + [tracker] url = "udp://tracker:6969" mode = "Public" diff --git a/config-idx-back.sqlite.local.toml b/share/default/config/index.container.sqlite3.toml similarity index 78% rename from config-idx-back.sqlite.local.toml rename to share/default/config/index.container.sqlite3.toml index 12dcbab0..c0cb6002 100644 --- a/config-idx-back.sqlite.local.toml +++ b/share/default/config/index.container.sqlite3.toml @@ -3,6 +3,10 @@ log_level = "info" [website] name = "Torrust" +# Please override the tracker token setting the +# `TORRUST_INDEX_TRACKER_API_TOKEN` +# environmental variable! + [tracker] url = "udp://tracker:6969" mode = "Public" @@ -20,7 +24,7 @@ max_password_length = 64 secret_key = "MaxVerstappenWC2021" [database] -connect_url = "sqlite://storage/database/torrust_index_e2e_testing.db?mode=rwc" +connect_url = "sqlite:///var/lib/torrust/index/database/sqlite3.db?mode=rwc" [mail] email_verification_enabled = false diff --git a/config.local.toml b/share/default/config/index.development.sqlite3.toml similarity index 100% rename from config.local.toml rename to share/default/config/index.development.sqlite3.toml diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml new file mode 100644 index 00000000..fb9cbf78 --- /dev/null +++ b/share/default/config/tracker.container.mysql.toml @@ -0,0 +1,38 @@ +announce_interval = 120 +db_driver = "MySQL" +db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" +external_ip = "0.0.0.0" +inactive_peer_cleanup_interval = 600 +log_level = "info" +max_peer_timeout = 900 +min_announce_interval = 120 +mode = "public" +on_reverse_proxy = false +persistent_torrent_completed_stat = false +remove_peerless_torrents = true +tracker_usage_statistics = true + +[[udp_trackers]] +bind_address = "0.0.0.0:6969" +enabled = false + +[[http_trackers]] +bind_address = "0.0.0.0:7070" +enabled = false +ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_enabled = false +ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + +[http_api] +bind_address = "0.0.0.0:1212" +enabled = true +ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_enabled = false +ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + +# Please override the admin token setting the +# `TORRUST_TRACKER_API_ADMIN_TOKEN` +# environmental variable! + +[http_api.access_tokens] +admin = "MyAccessToken" diff --git a/config-tracker.local.toml b/share/default/config/tracker.container.sqlite3.toml similarity index 56% rename from config-tracker.local.toml rename to share/default/config/tracker.container.sqlite3.toml index 2c7cb704..54cfd402 100644 --- a/config-tracker.local.toml +++ b/share/default/config/tracker.container.sqlite3.toml @@ -1,34 +1,38 @@ -log_level = "info" -mode = "public" -db_driver = "Sqlite3" -db_path = "/var/lib/torrust/tracker/database/torrust_tracker_e2e_testing.db" announce_interval = 120 -min_announce_interval = 120 +db_driver = "Sqlite3" +db_path = "/var/lib/torrust/tracker/database/sqlite3.db" +external_ip = "0.0.0.0" +inactive_peer_cleanup_interval = 600 +log_level = "info" max_peer_timeout = 900 +min_announce_interval = 120 +mode = "public" on_reverse_proxy = false -external_ip = "0.0.0.0" -tracker_usage_statistics = true persistent_torrent_completed_stat = false -inactive_peer_cleanup_interval = 600 remove_peerless_torrents = true +tracker_usage_statistics = true [[udp_trackers]] -enabled = true bind_address = "0.0.0.0:6969" +enabled = false [[http_trackers]] -enabled = false bind_address = "0.0.0.0:7070" +enabled = false +ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" ssl_enabled = false -ssl_cert_path = "" -ssl_key_path = "" +ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" [http_api] -enabled = true bind_address = "0.0.0.0:1212" +enabled = true +ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" ssl_enabled = false -ssl_cert_path = "" -ssl_key_path = "" +ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + +# Please override the admin token setting the +# `TORRUST_TRACKER_API_ADMIN_TOKEN` +# environmental variable! [http_api.access_tokens] admin = "MyAccessToken" diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index d07c3202..49f661ac 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -1,46 +1,62 @@ //! Initialize configuration from file or env var. //! -//! All environment variables are prefixed with `TORRUST_IDX_BACK_`. -use std::env; +//! All environment variables are prefixed with `TORRUST_INDEX_`. // Environment variables -/// The whole `config.toml` file content. It has priority over the config file. +use crate::config::{Configuration, Info}; + +/// The whole `index.toml` file content. It has priority over the config file. /// Even if the file is not on the default path. -pub const ENV_VAR_CONFIG: &str = "TORRUST_IDX_BACK_CONFIG"; +const ENV_VAR_CONFIG: &str = "TORRUST_INDEX_CONFIG"; -/// The `config.toml` file location. -pub const ENV_VAR_CONFIG_PATH: &str = "TORRUST_IDX_BACK_CONFIG_PATH"; +/// Token needed to communicate with the Torrust Tracker +const ENV_VAR_API_ADMIN_TOKEN: &str = "TORRUST_INDEX_TRACKER_API_TOKEN"; -/// If present, CORS will be permissive. -pub const ENV_VAR_CORS_PERMISSIVE: &str = "TORRUST_IDX_BACK_CORS_PERMISSIVE"; +/// The `index.toml` file location. +pub const ENV_VAR_PATH_CONFIG: &str = "TORRUST_INDEX_PATH_CONFIG"; // Default values +pub const DEFAULT_PATH_CONFIG: &str = "./share/default/config/index.development.sqlite3.toml"; -pub const ENV_VAR_DEFAULT_CONFIG_PATH: &str = "./config.toml"; - -use crate::config::Configuration; +/// If present, CORS will be permissive. +pub const ENV_VAR_CORS_PERMISSIVE: &str = "TORRUST_INDEX_BACK_CORS_PERMISSIVE"; -/// Initialize configuration from file or env var. +/// It loads the application configuration from the environment. +/// +/// There are two methods to inject the configuration: +/// +/// 1. By using a config file: `index.toml`. +/// 2. Environment variable: `TORRUST_INDEX_CONFIG`. The variable contains the same contents as the `index.toml` file. +/// +/// Environment variable has priority over the config file. +/// +/// Refer to the [configuration documentation](https://docs.rs/torrust-index-configuration) for the configuration options. /// /// # Panics /// -/// Will panic if configuration is not found or cannot be parsed -pub async fn init_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 config file `{config_path}`"); - - match Configuration::load_from_file(&config_path).await { - Ok(config) => config, - Err(error) => { - panic!("{}", error) - } - } +/// Will panic if it can't load the configuration from either +/// `./index.toml` file or the env var `TORRUST_INDEX_CONFIG`. +#[must_use] +pub fn initialize_configuration() -> Configuration { + 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() +} + +#[cfg(test)] +mod tests { + + #[test] + fn it_should_load_with_default_config() { + use crate::bootstrap::config::initialize_configuration; + + drop(initialize_configuration()); } } diff --git a/src/config.rs b/src/config.rs index 86d7810f..941c3921 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,11 +1,107 @@ //! Configuration for the application. use std::path::Path; +use std::sync::Arc; use std::{env, fs}; use config::{Config, ConfigError, File, FileFormat}; use log::warn; use serde::{Deserialize, Serialize}; +use thiserror::Error; use tokio::sync::RwLock; +use torrust_index_located_error::{Located, LocatedError}; + +/// Information required for loading config +#[derive(Debug, Default, Clone)] +pub struct Info { + index_toml: String, + tracker_api_token: Option, +} + +impl Info { + /// Build Configuration Info + /// + /// # Examples + /// + /// ```no_run + /// # use torrust_index::config::Info; + /// # let (env_var_config, env_var_path_config, default_path_config, env_var_tracker_api_token) = ("".to_string(), "".to_string(), "".to_string(), "".to_string()); + /// let result = Info::new(env_var_config, env_var_path_config, default_path_config, env_var_tracker_api_token); + /// ``` + /// + /// # 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_tracker_api_token: String, + ) -> Result { + let index_toml = if let Ok(index_toml) = env::var(&env_var_config) { + println!("Loading configuration from env var {env_var_config} ..."); + + index_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 tracker_api_token = env::var(env_var_tracker_api_token).ok(); + + Ok(Self { + index_toml, + tracker_api_token, + }) + } +} + +/// Errors that can occur when loading the configuration. +#[derive(Error, Debug)] +pub enum Error { + /// Unable to load the configuration from the environment variable. + /// This error only occurs if there is no configuration file and the + /// `TORRUST_TRACKER_CONFIG` environment variable is not set. + #[error("Unable to load from Environmental Variable: {source}")] + UnableToLoadFromEnvironmentVariable { + 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 { + #[track_caller] + fn from(err: ConfigError) -> Self { + Self::ConfigError { + source: Located(err).into(), + } + } +} /// Information displayed to the user in the website. #[derive(Debug, Clone, Serialize, Deserialize)] @@ -60,6 +156,12 @@ pub struct Tracker { pub token_valid_seconds: u64, } +impl Tracker { + fn override_tracker_api_token(&mut self, tracker_api_token: &str) { + self.token = tracker_api_token.to_string(); + } +} + impl Default for Tracker { fn default() -> Self { Self { @@ -280,6 +382,12 @@ pub struct TorrustIndex { pub tracker_statistics_importer: TrackerStatisticsImporter, } +impl TorrustIndex { + fn override_tracker_api_token(&mut self, tracker_api_token: &str) { + self.tracker.override_tracker_api_token(tracker_api_token); + } +} + /// The configuration service. #[derive(Debug)] pub struct Configuration { @@ -336,29 +444,28 @@ impl Configuration { }) } - /// 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.index_toml` string. + /// + /// Optionally will override the tracker 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 torrust_config: TorrustIndex = config_builder.try_deserialize()?; - Ok(Configuration { - settings: RwLock::new(torrust_config), - config_path: None, - }) - } - Err(_) => Err(ConfigError::Message( - "Unable to load configuration from the configuration environment variable.".to_string(), - )), - } + pub fn load(info: &Info) -> Result { + let config_builder = Config::builder() + .add_source(File::from_str(&info.index_toml, FileFormat::Toml)) + .build()?; + let mut index_config: TorrustIndex = config_builder.try_deserialize()?; + + if let Some(ref token) = info.tracker_api_token { + index_config.override_tracker_api_token(token); + }; + + Ok(Configuration { + settings: RwLock::new(index_config), + config_path: None, + }) } /// Returns the save to file of this [`Configuration`]. diff --git a/src/console/commands/import_tracker_statistics.rs b/src/console/commands/import_tracker_statistics.rs index 8d0c111b..08acbb31 100644 --- a/src/console/commands/import_tracker_statistics.rs +++ b/src/console/commands/import_tracker_statistics.rs @@ -27,7 +27,7 @@ use std::sync::Arc; use derive_more::{Display, Error}; use text_colorizer::Colorize; -use crate::bootstrap::config::init_configuration; +use crate::bootstrap::config::initialize_configuration; use crate::bootstrap::logging; use crate::databases::database; use crate::tracker::service::Service; @@ -88,7 +88,7 @@ pub async fn run_importer() { pub async fn import() { println!("Importing statistics from linked tracker ..."); - let configuration = init_configuration().await; + let configuration = initialize_configuration(); let log_level = configuration.settings.read().await.log_level.clone(); diff --git a/src/bin/main.rs b/src/main.rs similarity index 74% rename from src/bin/main.rs rename to src/main.rs index 68d0b3ea..b09eedb6 100644 --- a/src/bin/main.rs +++ b/src/main.rs @@ -1,10 +1,10 @@ use torrust_index::app; -use torrust_index::bootstrap::config::init_configuration; +use torrust_index::bootstrap::config::initialize_configuration; use torrust_index::web::api::Version; #[tokio::main] async fn main() -> Result<(), std::io::Error> { - let configuration = init_configuration().await; + let configuration = initialize_configuration(); let api_version = Version::V1; diff --git a/tests/e2e/config.rs b/tests/e2e/config.rs index d41621ff..747e0a05 100644 --- a/tests/e2e/config.rs +++ b/tests/e2e/config.rs @@ -1,46 +1,62 @@ //! Initialize configuration for the shared E2E tests environment from a //! config file `config.toml` or env var. //! -//! All environment variables are prefixed with `TORRUST_IDX_BACK_E2E`. -use std::env; - -use torrust_index::config::Configuration; +//! All environment variables are prefixed with `TORRUST_INDEX_E2E_`. // Environment variables -/// If present, E2E tests will run against a shared instance of the server -pub const ENV_VAR_E2E_SHARED: &str = "TORRUST_IDX_BACK_E2E_SHARED"; +use torrust_index::config::{Configuration, Info}; + +/// The whole `index.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_INDEX_E2E_CONFIG"; -/// The whole `config.toml` file content. It has priority over the config file. -pub const ENV_VAR_E2E_CONFIG: &str = "TORRUST_IDX_BACK_E2E_CONFIG"; +/// Token needed to communicate with the Torrust Tracker +const ENV_VAR_API_ADMIN_TOKEN: &str = "TORRUST_INDEX_E2E_TRACKER_API_TOKEN"; -/// The `config.toml` file location. -pub const ENV_VAR_E2E_CONFIG_PATH: &str = "TORRUST_IDX_BACK_E2E_CONFIG_PATH"; +/// The `index.toml` file location. +pub const ENV_VAR_PATH_CONFIG: &str = "TORRUST_INDEX_E2E_PATH_CONFIG"; // Default values +pub const DEFAULT_PATH_CONFIG: &str = "./share/default/config/index.development.sqlite3.toml"; -pub const ENV_VAR_E2E_DEFAULT_CONFIG_PATH: &str = "./config-idx-back.sqlite.local.toml"; +/// If present, E2E tests will run against a shared instance of the server +pub const ENV_VAR_INDEX_SHARED: &str = "TORRUST_INDEX_E2E_SHARED"; -/// Initialize configuration from file or env var. +/// It loads the application configuration from the environment. +/// +/// There are two methods to inject the configuration: +/// +/// 1. By using a config file: `index.toml`. +/// 2. Environment variable: `TORRUST_INDEX_E2E_CONFIG`. The variable contains the same contents as the `index.toml` file. +/// +/// Environment variable has priority over the config file. +/// +/// Refer to the [configuration documentation](https://docs.rs/torrust-index-configuration) for the configuration options. /// /// # Panics /// -/// Will panic if configuration is not found or cannot be parsed -pub async fn init_shared_env_configuration() -> Configuration { - if env::var(ENV_VAR_E2E_CONFIG).is_ok() { - println!("Loading configuration for E2E env from env var `{ENV_VAR_E2E_CONFIG}`"); - - Configuration::load_from_env_var(ENV_VAR_E2E_CONFIG).unwrap() - } else { - let config_path = env::var(ENV_VAR_E2E_CONFIG_PATH).unwrap_or_else(|_| ENV_VAR_E2E_DEFAULT_CONFIG_PATH.to_string()); - - println!("Loading configuration from config file `{config_path}`"); - - match Configuration::load_from_file(&config_path).await { - Ok(config) => config, - Err(error) => { - panic!("{}", error) - } - } +/// Will panic if it can't load the configuration from either +/// `./index.toml` file or the env var `TORRUST_INDEX_CONFIG`. +#[must_use] +pub fn initialize_configuration() -> Configuration { + 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() +} + +#[cfg(test)] +mod tests { + use torrust_index::bootstrap::config::initialize_configuration; + + #[test] + fn it_should_load_with_default_config() { + drop(initialize_configuration()); } } diff --git a/tests/e2e/environment.rs b/tests/e2e/environment.rs index c6f9819e..73652725 100644 --- a/tests/e2e/environment.rs +++ b/tests/e2e/environment.rs @@ -3,7 +3,7 @@ use std::env; use torrust_index::databases::database; use torrust_index::web::api::Version; -use super::config::{init_shared_env_configuration, ENV_VAR_E2E_SHARED}; +use super::config::{initialize_configuration, ENV_VAR_INDEX_SHARED}; use crate::common::contexts::settings::Settings; use crate::environments::{isolated, shared}; @@ -57,7 +57,7 @@ impl TestEnv { /// It starts the test environment. It can be a shared or isolated test /// environment depending on the value of the `ENV_VAR_E2E_SHARED` env var. pub async fn start(&mut self, api_version: Version) { - let e2e_shared = ENV_VAR_E2E_SHARED; // bool + let e2e_shared = ENV_VAR_INDEX_SHARED; // bool if let Ok(_e2e_test_env_is_shared) = env::var(e2e_shared) { // Using the shared test env. @@ -164,7 +164,7 @@ impl TestEnv { } async fn server_settings_for_shared_env(&self) -> Option { - let configuration = init_shared_env_configuration().await; + let configuration = initialize_configuration(); let settings = configuration.settings.read().await; Some(Settings::from(settings.clone())) }