From a7fec189d63c8bfaada2a8efbadf32b4e6691374 Mon Sep 17 00:00:00 2001 From: Vitor Lima Date: Sun, 16 Jun 2024 10:47:13 -0300 Subject: [PATCH] feat: added the github workflows --- .github/macos-build-entitlements.plist | 10 + .github/workflows/build-alpine-arm64.yml | 44 +++++ .github/workflows/build-alpine-x64.yml | 44 +++++ .github/workflows/build-dockerhub.yml | 31 ++++ .github/workflows/build-macos-x64.yml | 66 +++++++ .github/workflows/build-win-x64.yml | 47 +++++ .github/workflows/tests.yml | 31 ++-- Cargo.lock | 15 ++ Cargo.toml | 3 +- Dockerfile | 4 +- LICENSE | 201 +++++++++++++++++++++ README.md | 166 +++++++++++++++-- config.toml | 15 -- dockerhub.sh | 26 +++ examples/docker-compose/docker-compose.yml | 8 + src/main.rs | 13 +- src/relay.rs | 42 +++-- src/services/mqttrelay.rs | 2 +- src/utils.rs | 2 +- 19 files changed, 701 insertions(+), 69 deletions(-) create mode 100644 .github/macos-build-entitlements.plist create mode 100644 .github/workflows/build-alpine-arm64.yml create mode 100644 .github/workflows/build-alpine-x64.yml create mode 100644 .github/workflows/build-dockerhub.yml create mode 100644 .github/workflows/build-macos-x64.yml create mode 100644 .github/workflows/build-win-x64.yml create mode 100644 LICENSE delete mode 100644 config.toml create mode 100644 dockerhub.sh create mode 100644 examples/docker-compose/docker-compose.yml diff --git a/.github/macos-build-entitlements.plist b/.github/macos-build-entitlements.plist new file mode 100644 index 0000000..957352b --- /dev/null +++ b/.github/macos-build-entitlements.plist @@ -0,0 +1,10 @@ + + + + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + + \ No newline at end of file diff --git a/.github/workflows/build-alpine-arm64.yml b/.github/workflows/build-alpine-arm64.yml new file mode 100644 index 0000000..914a364 --- /dev/null +++ b/.github/workflows/build-alpine-arm64.yml @@ -0,0 +1,44 @@ +name: Build for alpine-arm64 + +on: workflow_dispatch + +jobs: + build: + runs-on: ubuntu-latest + + steps: + # Checkout the code + - name: Checkout the code + uses: actions/checkout@v1 + + # Setup Docker for cross platform build + - name: Set up QEMU + uses: docker/setup-qemu-action@v1 + + # Setup Docker for cross platform build + - name: Set up docker buildx + id: buildx + uses: docker/setup-buildx-action@v1 + + # Build docker image + - name: Run build + run: docker buildx build --load --platform linux/arm64 -f ./docker/Dockerfile.alpine-arm64 . -t tagocore-container + + # Pull binary out of docker container + - name: Extract tagocore binary out of docker + run: docker cp $(docker create tagocore-container):/usr/src/app/__build__binary__/tagocore ./tagocore + + # Set binary as executable + - name: Chmod + run: chmod +x ./tagocore + + # Zip the binary + - name: Generate tar.gz + run: tar cvf - tagocore | gzip > ./tagocore-alpine-arm64.tar.gz + + # Upload the zip file as an artifact + - name: Upload artifact + uses: actions/upload-artifact@v2 + with: + name: mqttrelay-alpine-arm64 + path: ../tagocore.zip diff --git a/.github/workflows/build-alpine-x64.yml b/.github/workflows/build-alpine-x64.yml new file mode 100644 index 0000000..2cb9952 --- /dev/null +++ b/.github/workflows/build-alpine-x64.yml @@ -0,0 +1,44 @@ +name: Build for alpine-x64 + +on: workflow_dispatch + +jobs: + build: + runs-on: ubuntu-latest + + steps: + # Checkout the code + - name: Checkout the code + uses: actions/checkout@v1 + + # Setup Docker for cross platform build + - name: Set up QEMU + uses: docker/setup-qemu-action@v1 + + # Setup Docker for cross platform build + - name: Set up docker buildx + id: buildx + uses: docker/setup-buildx-action@v1 + + # Build docker image + - name: Run build + run: docker buildx build --load --platform linux/arm64 -f ./docker/Dockerfile.alpine-arm64 . -t tagocore-container + + # Pull binary out of docker container + - name: Extract tagocore binary out of docker + run: docker cp $(docker create tagocore-container):/usr/src/app/__build__binary__/tagocore ./tagocore + + # Set binary as executable + - name: Chmod + run: chmod +x ./tagocore + + # Zip the binary + - name: Generate tar.gz + run: tar cvf - tagocore | gzip > ./tagocore-alpine-arm64.tar.gz + + # Upload the zip file as an artifact + - name: Upload artifact + uses: actions/upload-artifact@v2 + with: + name: mqttrelay-alpine-arm64 + path: ../tagocore.zip diff --git a/.github/workflows/build-dockerhub.yml b/.github/workflows/build-dockerhub.yml new file mode 100644 index 0000000..f30a5b0 --- /dev/null +++ b/.github/workflows/build-dockerhub.yml @@ -0,0 +1,31 @@ +name: Deplot to DockerHub + +on: + workflow_dispatch: + inputs: + version: + description: "Version" + required: true + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Checkout the code + uses: actions/checkout@v1 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v2 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Build and deploy images + run: bash dockerhub.sh ${{ github.event.inputs.version }} diff --git a/.github/workflows/build-macos-x64.yml b/.github/workflows/build-macos-x64.yml new file mode 100644 index 0000000..018bd4e --- /dev/null +++ b/.github/workflows/build-macos-x64.yml @@ -0,0 +1,66 @@ +name: Build for mac-x64 + +on: workflow_dispatch + +jobs: + build: + runs-on: macos-11 + + steps: + # Checkout the code + - name: Checkout code + uses: actions/checkout@v4 + + - name: Install Rust toolchain + run: | + rustup update --no-self-update stable + rustup component add --toolchain stable rustfmt + rustup default stable + + # Build the modules + - name: Build + run: cargo build --verbose --release + + - name: Run tests + run: cargo test --verbose + + # # Sign the executable + # - name: Codesign binary + # env: + # MACOS_CERTIFICATE: ${{ secrets.MACOS_CERTIFICATE }} + # MACOS_CERTIFICATE_PWD: ${{ secrets.MACOS_CERTIFICATE_PWD }} + # MACOS_FULL_IDENTITY: ${{ secrets.MACOS_FULL_IDENTITY }} + # run: | + # echo $MACOS_CERTIFICATE | openssl base64 -d -A > certificate.p12 + # security create-keychain -p $MACOS_CERTIFICATE_PWD build.keychain + # security default-keychain -s build.keychain + # security unlock-keychain -p $MACOS_CERTIFICATE_PWD build.keychain + # security import certificate.p12 -k build.keychain -P $MACOS_CERTIFICATE_PWD -T /usr/bin/codesign + # security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k $MACOS_CERTIFICATE_PWD build.keychain + # cd __build__binary__ + # /usr/bin/codesign -f -s "$MACOS_FULL_IDENTITY" --entitlements ../.github/macos-build-entitlements.plist --options=runtime --timestamp ./tagocore + # zip ./tagocore.zip ./tagocore + # /usr/bin/codesign -f -s "$MACOS_FULL_IDENTITY" --options=runtime --timestamp ./tagocore.zip + + # # Notarize app using xcrun altool + # - name: Notarize binary + # env: + # MACOS_DEVELOPER_EMAIL: ${{ secrets.MACOS_DEVELOPER_EMAIL }} + # MACOS_DEVELOPER_PWD: ${{ secrets.MACOS_DEVELOPER_PWD }} + # MACOS_BUNDLE_ID: ${{ secrets.MACOS_BUNDLE_ID }} + # MACOS_ASC_PROVIDER: ${{ secrets.MACOS_ASC_PROVIDER }} + # run: xcrun altool --notarize-app --primary-bundle-id "$MACOS_BUNDLE_ID" -u "$MACOS_DEVELOPER_EMAIL" -p "$MACOS_DEVELOPER_PWD" --asc-provider "$MACOS_ASC_PROVIDER" -f ./__build__binary__/tagocore.zip + + # Zip the binary + - name: Generate tar.gz + run: | + cd __build__binary__ + unzip -o tagocore.zip + tar cvf - tagocore | gzip > ../tagocore-mac-x64.tar.gz + + # Upload the zip file as an artifact + - name: Upload artifact + uses: actions/upload-artifact@v2 + with: + name: mqttrelay-macos-x64 + path: ../tagocore.zip diff --git a/.github/workflows/build-win-x64.yml b/.github/workflows/build-win-x64.yml new file mode 100644 index 0000000..4b9eca8 --- /dev/null +++ b/.github/workflows/build-win-x64.yml @@ -0,0 +1,47 @@ +name: Build for win-x64 + +on: workflow_dispatch + +jobs: + build: + runs-on: ubuntu-latest + + steps: + # Checkout the code + - name: Checkout the code + uses: actions/checkout@v1 + + # Install dependencies + - name: Install dependencies + run: npm install + + # Build the modules + - name: Run build + run: npm run build + + # Manually copy the bin file of sdk to the .bin folder to use the local copy of the sdk + - name: Override tcore-plugin .bin file + run: cd ./node_modules/.bin; ln -s ../../packages/tcore-sdk/build/Bin/Bin.js tcore-plugin; chmod +x tcore-plugin; cd ../../ + + # Pack Plugin Store, TagoIO Integration, and Local Filesystem into a .tcore file + - name: Pack built-in plugins + run: npm run pack + + # Add the packed .tcore files to the /plugins folder + - name: Move built-in plugins to plugins folder + run: npm run plugin:add + + # Generate the executable + - name: Generate executable + run: ./node_modules/.bin/pkg package.json -t node16-win-x64 --public-packages "*" --no-bytecode --public --compress Brotli + + # Zip the executable + - name: Generate zip + run: cd __build__binary__; zip ../tagocore.zip ./tagocore.exe + + # Upload the zip file as an artifact + - name: Upload artifact + uses: actions/upload-artifact@v2 + with: + name: mqttrelay-windows-x64 + path: ../tagocore.zip diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 66e321d..ffd16bc 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -10,24 +10,23 @@ jobs: runs-on: ubuntu-latest steps: - - name: Checkout code - uses: actions/checkout@v4 + - name: Checkout code + uses: actions/checkout@v4 - - name: Install Rust toolchain - run: | - rustup update --no-self-update stable - rustup component add --toolchain stable rustfmt - rustup default stable + - name: Install Rust toolchain + run: | + rustup update --no-self-update stable + rustup component add --toolchain stable rustfmt + rustup default stable - - name: Build - run: cargo build --verbose + - name: Build + run: cargo build --verbose - - name: Run tests - run: cargo test --verbose + - name: Run tests + run: cargo test --verbose - - name: Run clippy - run: cargo clippy -- -D warnings - - - name: Run fmt check - run: cargo fmt -- --check + - name: Run clippy + run: cargo clippy -- -D warnings + - name: Run fmt check + run: cargo fmt -- --check diff --git a/Cargo.lock b/Cargo.lock index f9dbaff..15b92a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -216,10 +216,12 @@ dependencies = [ "http-body-util", "hyper 1.3.1", "hyper-util", + "openssl", "pin-project-lite", "rustls 0.21.12", "rustls-pemfile", "tokio", + "tokio-openssl", "tokio-rustls 0.24.1", "tower", "tower-service", @@ -2000,6 +2002,7 @@ dependencies = [ "log", "mockito", "once_cell", + "openssl", "rand", "regex", "reqwest", @@ -2108,6 +2111,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-openssl" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ffab79df67727f6acf57f1ff743091873c24c579b1e2ce4d8f53e47ded4d63d" +dependencies = [ + "futures-util", + "openssl", + "openssl-sys", + "tokio", +] + [[package]] name = "tokio-rustls" version = "0.24.1" diff --git a/Cargo.toml b/Cargo.toml index 5e3541a..0f6c7dd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ mockito = "1.4.0" [dependencies] anyhow = "1.0.86" axum = "0.7.5" -axum-server = { version = "0.6", features = ["tls-rustls"] } +axum-server = { version = "0.6.0", features = ["tls-rustls", "tls-openssl"] } clap = { version = "4.5.4", features = ["derive"] } config = "0.14.0" dotenvy = "0.15.7" @@ -18,6 +18,7 @@ env_logger = "0.11.3" home = "0.5.9" log = "0.4.21" once_cell = "1.19.0" +openssl = "0.10.64" rand = "0.8.5" regex = "1.10.4" reqwest = { version = "0.12.4", features = ["rustls-tls", "json"] } diff --git a/Dockerfile b/Dockerfile index df97b56..102b4e8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -20,6 +20,8 @@ RUN apt-get clean && rm -rf /var/lib/apt/lists/* RUN mkdir -p ${TAGOIO_SOURCE_FOLDER} WORKDIR ${TAGOIO_SOURCE_FOLDER} COPY --from=build ${TAGOIO_SOURCE_FOLDER}/target/release/tagoio-mqtt-relay . -COPY --from=build ${TAGOIO_SOURCE_FOLDER}/config.toml config.toml + +RUN /tago-io/tagoio-mqtt-relay init ENTRYPOINT ["/tago-io/tagoio-mqtt-relay"] +CMD ["start"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f49a4e1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md index 350d60f..a8f774b 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,160 @@ +# TagoIO MQTT Relay -Welcome to the **MQTT Bridge of Doom**! This is the place where we try to build a bridge between TagoIO and customer brokers without losing our sanity. +Welcome to the TagoIO MQTT Relay! This software bridges your MQTT Broker and the TagoIO platform, allowing seamless integration and data flow. It's a fast, open-source, and scalable solution written in Rust. -## What is this? +## Table of Contents -This is a Rust-powered, always-running, MQTT Bridge between TagoIO and customer brokers. πŸš€ +- [Introduction](#introduction) +- [Features](#features) +- [Getting Started](#getting-started) + - [Prerequisites](#prerequisites) + - [Installation](#installation) + - [Configuration](#configuration) + - [Running the Relay](#running-the-relay) +- [Docker Setup](#docker-setup) +- [CLI Commands](#cli-commands) +- [Configuration File](#configuration-file) +- [License](#license) -## Why does it exist? -Imagine this: TagoIO's broker is having heart attacks, and we need to save the day by building a bridge. Sounds heroic, right? +## Introduction -## Current Status +The TagoIO MQTT Relay connects to your MQTT Broker on predefined topics and redirects the information to TagoIO Devices. It uses TagoIO Integration Network and Connector, alongside an Authorization Key from your TagoIO Profile. -### Prototype Phase πŸ› οΈ +## Features -- **MQTT Connection:** βœ… -- **Asynchronous Updates:** βœ… -- **Sanity:** ❓ (Still under investigation) +- **Written in Rust**: Fast and reliable performance. +- **Open Source**: Available on GitHub for community contributions. +- **Scalable**: Easily handles increasing data loads. +- **Docker Support**: Simplifies deployment and scaling. -## The Journey So Far +## Getting Started -- **Hours Spent:** 10 ⏳ -- **Brain Cells Lost:** Countless 🧠πŸ’₯ -- **Coffee Consumed:** Gallons β˜•οΈ -- **Rust Compiler Errors:** Infinite ♾️ \ No newline at end of file +### Prerequisites + +Before you begin, ensure you have: + +- A TagoIO account. +- Access to an MQTT Broker (e.g., HiveMQ, EMQX). + +### Installation + +1. **Download the Binary**: Get the `tagoio-relay` binary from the [GitHub releases page](./releases/latest). +2. **Set Permission Rights**: Give the binary executable permissions: + ```sh + chmod +x tagoio-relay + ``` +3. **Resolve Malicious Software Alert (macOS)**: Follow [Apple Support](https://support.apple.com) instructions if you encounter a malicious software alert. +4. **Verify Installation**: Check if the `tagoio-relay` is working properly: + ```sh + ./tagoio-relay --help + ``` + +### Configuration + +1. **Create a Network in TagoIO**: + - Navigate to Integrations in your TagoIO Profile and create a new Network. + - Enable Serial and write a Payload Parser: + ```js + if (Array.isArray(payload)) { + const payload_received = payload.find(x => x.variable === "payload"); + serial = payload_received?.metadata.topic.split("/").pop(); + } + ``` +2. **Generate Network Token**: Generate and save the Network Token. +3. **Create a Connector**: Create a Connector for your Network. +4. **Generate Authorization**: Navigate to Devices > Authorizations in TagoIO and generate an authorization token. +5. **Create a Device**: Create a Device with a Serial to use later on the Broker. +6. **Set Up an MQTT Broker**: Create or use a public MQTT Broker. +7. **Gather Broker Details**: Obtain the Address, Port, and Credentials of your MQTT Broker. + +### Running the Relay + +1. **Initialize Config File**: + ```sh + ./tagoio-relay init + ``` +2. **Edit Config File**: Modify the generated `config.toml`: + ```toml + [relay] + network_token="Your-Network-Token" + authorization_token="Your-Authorization-Token" + tagoio_url="https://api.tago.io" + downlink_port="3001" + + [relay.mqtt] + client_id="tagoio-relay" + tls_enabled=false + address="localhost" + port=1883 + subscribe=["/tago/#", "/topic/+"] + username="my-username" + password="my-password" + ``` +3. **Start the Relay**: + ```sh + ./tagoio-relay start + ``` +4. **Publish Messages to Broker**: Publish messages to the Broker on your chosen topics and see them forwarded to your TagoIO device. + +## Docker Setup + +To run the TagoIO MQTT Relay using Docker, use the following command: + +```sh +docker run -p 3001:3001 -it --rm --name my-test tagoio/tagorelay start --no-daemon +``` + +### Image Variants + +- **tagoio/tagocore:**: Main image for general use. +- **tagoio/tagocore:alpine**: Based on Alpine Linux, ideal for smaller image sizes. +- **tagoio/tagocore:bullseye**: Based on Debian 11. + +## CLI Commands + +The CLI has two main commands: `init` and `start`. + +### `init` + +Generates the `config.toml` file required for setting up the Relay. + +```sh +tagoio-relay init [--config-path /path/to/config] +``` + +### `start` + +Starts the MQTT Relay service. + +```sh +tagoio-relay start [--verbose info,mqtt] [--config-path /path/to/config.toml] +``` + +## Configuration File + +The `config.toml` file contains the Relay parameters. Here is a reference: + +```toml +[relay] +network_token="Your-Network-Token" +authorization_token="Your-Authorization-Token" +tagoio_url="https://api.tago.io" +downlink_port="3001" + +[relay.mqtt] +client_id="tagoio-relay" +tls_enabled=false +address="localhost" +port=1883 +subscribe=["/tago/#", "/topic/+"] +username="my-username" +password="my-password" +``` + +## License + +The TagoIO MQTT Relay is licensed under the Apache License. See the [LICENSE](./LICENSE) file for more details. + +--- + +Thank you for using TagoIO MQTT Relay! If you have any questions or need further assistance, feel free to reach out via [GitHub Issues](#) or our [community forum](#). πŸš€ \ No newline at end of file diff --git a/config.toml b/config.toml deleted file mode 100644 index d15b571..0000000 --- a/config.toml +++ /dev/null @@ -1,15 +0,0 @@ -[relay] -network_token="Your-Network-Token" # Generate a Network Token under your TagoIO Network Settings -authorization_token="Your-Authorization-Token" # Generate an Authorization Token under your TagoIO > Devices > Authorizations -tagoio_url="https://api.tago.io" # Default -api_port="3000" # Default is 3000 - -[relay.mqtt] -client_id="tagoio-relay" # Default is tagoio-relay -tls_enabled=false -address="localhost" -port=1883 -subscribe=["/tago/#", "/device/+"] # MQTT topics to subscribe to -username="my-username" -password="my-passowrd" -authentication_certificate_file="certs/ca.crt" # Path to the CA certificate file. Alternative to username and password diff --git a/dockerhub.sh b/dockerhub.sh new file mode 100644 index 0000000..5f2fe17 --- /dev/null +++ b/dockerhub.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +FULL_VERSION=$1 + +SPLIT=(${FULL_VERSION//./ }) +MAJOR=${SPLIT[0]} +MINOR=${SPLIT[1]} +PATCH=${SPLIT[2]} + +# Alpine +# docker buildx build --push --build-arg TAGORELAY_VERSION=${FULL_VERSION} \ +# --platform linux/arm64/v8,linux/amd64 \ +# --tag tagoio/tagorelay:alpine \ +# --tag tagoio/tagorelay:${MAJOR}.${MINOR}-alpine \ +# --tag tagoio/tagorelay:${MAJOR}.${MINOR}.${PATCH}-alpine . + +# Debian +docker buildx build --push --build-arg TAGORELAY_VERSION=${FULL_VERSION} \ + --platform linux/arm/v7,linux/arm64/v8,linux/amd64 \ + --tag tagoio/tagorelay \ + --tag tagoio/tagorelay:debian \ + --tag tagoio/tagorelay:bullseye \ + --tag tagoio/tagorelay:${MAJOR}.${MINOR}-bullseye \ + --tag tagoio/tagorelay:${MAJOR}.${MINOR}.${PATCH}-bullseye \ + --tag tagoio/tagorelay:${MAJOR}.${MINOR} \ + --tag tagoio/tagorelay:${MAJOR}.${MINOR}.${PATCH} . diff --git a/examples/docker-compose/docker-compose.yml b/examples/docker-compose/docker-compose.yml new file mode 100644 index 0000000..6cb6c66 --- /dev/null +++ b/examples/docker-compose/docker-compose.yml @@ -0,0 +1,8 @@ +services: + my-eclipse: + image: tagoio/tago-relay:latest + restart: always + ports: + - "3001:3001" + volumes: + - ./config.toml:/root/.config/.tagoio-mqtt-relay.toml diff --git a/src/main.rs b/src/main.rs index d1abfc4..58986ba 100644 --- a/src/main.rs +++ b/src/main.rs @@ -72,16 +72,23 @@ async fn main() { init_config(config_path.as_deref()); } Commands::Start { verbose, config_path } => { + let log_level: String = verbose + .as_ref() + .map(|v| v.to_string()) + .unwrap_or_else(|| "error,info".to_string()); + + env_logger::init_from_env(env_logger::Env::new().default_filter_or(log_level)); + let config = utils::fetch_config_file(config_path.clone()); if let Some(config) = config { *CONFIG_FILE.write().unwrap() = Some(config); } else { - eprintln!("Failed to load configuration file."); + log::error!("Failed to load configuration file."); std::process::exit(1); } - if let Err(e) = relay::start_relay(verbose.as_deref()).await { - eprintln!("Error starting relay: {}", e); + if let Err(e) = relay::start_relay().await { + log::error!("Error starting relay: {}", e); } } } diff --git a/src/relay.rs b/src/relay.rs index 99acad8..c10b55a 100644 --- a/src/relay.rs +++ b/src/relay.rs @@ -13,7 +13,13 @@ use axum::{ routing::post, Extension, Json, Router, }; -use axum_server::tls_rustls::RustlsConfig; + +use axum_server::tls_openssl::OpenSSLConfig; +use openssl::{ + pkey::PKey, + ssl::{SslAcceptor, SslMethod, SslVerifyMode}, + x509::X509, +}; use dotenvy_macro::dotenv; use serde_json::json; @@ -34,26 +40,29 @@ const HOST_ADDRESS: &str = "127.0.0.1"; #[cfg(not(debug_assertions))] const HOST_ADDRESS: &str = "::"; // ? External IPv4/IPv6 support -async fn build_rustls_server_config() -> Arc { - let cert = dotenv!("SERVER_CA_CERT").as_bytes().to_vec(); - let key = dotenv!("SERVER_CA_KEY").as_bytes().to_vec(); +fn create_ssl_acceptor() -> Result, openssl::error::ErrorStack> { + let cert = dotenv!("SERVER_SSL_CERT").as_bytes(); + let key = dotenv!("SERVER_SSL_KEY").as_bytes(); + let ca = dotenv!("SERVER_SSL_CA").as_bytes(); + + let cert = X509::from_pem(cert)?; + let key = PKey::private_key_from_pem(key)?; + let ca = X509::from_pem(ca)?; - let config = RustlsConfig::from_pem(cert, key).await.unwrap(); + let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls())?; + acceptor.set_private_key(&key)?; + acceptor.set_certificate(&cert)?; + acceptor.add_extra_chain_cert(ca)?; + acceptor.check_private_key()?; - Arc::new(config) + acceptor.set_verify(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT); + Ok(Arc::new(acceptor.build())) } /** * Start the MQTT Relay service */ -pub async fn start_relay(verbose: Option>) -> Result<()> { - let log_level: String = verbose - .as_ref() - .map(|v| v.as_ref().to_string()) - .unwrap_or_else(|| "error,info".to_string()); - - env_logger::init_from_env(env_logger::Env::new().default_filter_or(log_level)); - +pub async fn start_relay() -> Result<()> { // Simulate fetching relay configurations let relay_list = get_relay_list().await?; let relay_list = Arc::new(RwLock::new(relay_list)); @@ -83,7 +92,8 @@ pub async fn start_relay(verbose: Option>) -> Result<()> { .unwrap_or("3000".to_string()) }; - let rustls_config = build_rustls_server_config().await; + let test = create_ssl_acceptor().unwrap(); + let acceptor = OpenSSLConfig::from_acceptor(test); // let listener = match tokio::net::TcpListener::bind(format!("{}:{}", HOST_ADDRESS, api_port)).await { // Ok(listener) => listener, @@ -100,7 +110,7 @@ pub async fn start_relay(verbose: Option>) -> Result<()> { tokio::spawn(async move { log::info!(target: "info", "Starting Publish API on: {}", addr); - axum_server::tls_rustls::bind_rustls(addr, (*rustls_config).clone()) + axum_server::bind_openssl(addr, acceptor) .serve(app.into_make_service()) .await .unwrap(); diff --git a/src/services/mqttrelay.rs b/src/services/mqttrelay.rs index 9ca7a07..3fd9726 100644 --- a/src/services/mqttrelay.rs +++ b/src/services/mqttrelay.rs @@ -131,7 +131,7 @@ async fn handle_mqtt_connection(eventloop: &mut rumqttc::EventLoop) -> Result<() match eventloop.poll().await { Ok(notification) => { if let rumqttc::Event::Incoming(rumqttc::Packet::ConnAck(_)) = notification { - println!("Connection to MQTT broker was successful"); + log::info!("Connection to MQTT broker was successful"); } Ok(()) } diff --git a/src/utils.rs b/src/utils.rs index 0bee6aa..06db67c 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -45,7 +45,7 @@ pub fn init_config(user_path: Option>) { std::fs::write(&config_path, DEFAULT_CONFIG).expect("Failed to create default config file"); - println!("Configuration file created at {}", config_path.display()); + log::info!("Configuration file created at {}", config_path.display()); } /**