diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..1d3a428e272dc04736f0722289629a5b952a550b --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,35 @@ +# Define the stages for the CI/CD pipeline +stages: + - build + +# Define the build job +build_image: + # Specify the stage in which the job should run + image: docker:latest # Use the latest version of Docker as the base image for this job + stage: build + services: + - docker:dind # Enable Docker-in-Docker service for building and pushing Docker images + # Set up tasks to be executed before each job + before_script: + # Log in to the GitLab Container Registry using CI/CD environment variables -- these are set up automatically + - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY + # Specify the tasks to be executed in the job + script: + - | + if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then + tag="" + echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = 'latest'" + else + tag=":$CI_COMMIT_REF_SLUG" + echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag" + fi + # Build the Docker image with the specified name and tag + - docker build --pull -t "$CI_REGISTRY_IMAGE${tag}" . + - docker push "$CI_REGISTRY_IMAGE${tag}" + + # Define rules to trigger the job only when specific files change + rules: + - if: $CI_COMMIT_BRANCH + - changes: + - Dockerfile + - requirements.txt \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bdbc2e8c5370c8a892b52d1c816c0e3c8ae593e5 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM copas-market.cerit-sc.cz/afolab/poc-python-kafka-minio-base:main-6f6f9460 AS build + +WORKDIR /app + +COPY . . + + +RUN pip install --no-cache-dir -r requirements.txt -r requirements.txt + +ENV PYTHONPATH "${PYTHONPATH}:/app" + +CMD [ "bash", "server.sh" ] diff --git a/README.md b/README.md index e943c81b4c16d2f6d57fdb72bb3e58b81821bfa5..5441074936f496cf81e8f46d14e7cdb2c4774c36 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,4 @@ -# rtc-api - - - -## Getting started - -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://gitlab.ics.muni.cz/469319/rtc-api.git -git branch -M master -git push -uf origin master -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab.ics.muni.cz/469319/rtc-api/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +RUN LOCALLY: +docker build - t <name> . +docker run -p 8443:443 <name> +Access via http://localhost:8443 \ No newline at end of file diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/config/__init__.py b/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/config/configuration.py b/config/configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..0840361ff73377c5e157bc15fc990f86d3f7d097 --- /dev/null +++ b/config/configuration.py @@ -0,0 +1,24 @@ +import os +from dataclasses import dataclass, field +from functools import partial + + +@dataclass +class PocConfiguration: + MINIO_URL: str = field(default_factory=partial(os.environ.get, "MINIO_URL", "localhost:9001")) + CA_CERT_LOCATION: str = field(default_factory=partial(os.environ.get, "CA_CERT_LOCATION", "/tls/tls.crt")) + OAUTH_CLIENT_ID: str = field(default_factory=partial(os.environ.get, "CLIENT_ID", "client")) + OAUTH_CLIENT_SECRET: str = field(default_factory=partial(os.environ.get, "CLIENT_SECRET", "secret")) + BROKER_URLS: str = field(default_factory=partial(os.environ.get, "BROKERS", "localhost:8000")) + AUTH_PROVIDER_URL: str = field(default_factory=partial(os.environ.get, "AUTH_PROVIDER_URL", "localhost:9000")) + TLS_KEY_LOCATION: str = field(default_factory=partial(os.environ.get, "TLS_KEY_LOCATION", "/tls/tls.crt")) + TLS_CERT_LOCATION: str = field(default_factory=partial(os.environ.get, "TLS_CERT_LOCATION", "/tls/tls.key")) + + +class ConfigurationProvider: + __configuration = PocConfiguration() + + @staticmethod + def get_config() -> PocConfiguration: + return ConfigurationProvider.__configuration + diff --git a/config/dto.py b/config/dto.py new file mode 100644 index 0000000000000000000000000000000000000000..3067a363fff11996a709c3c3c68478d7b74aab78 --- /dev/null +++ b/config/dto.py @@ -0,0 +1,7 @@ +from dataclasses import dataclass + + +@dataclass +class NotificationDto: + bucket: str + file: str diff --git a/config/shared.py b/config/shared.py new file mode 100644 index 0000000000000000000000000000000000000000..c21515365203a59b6d9e4aed2bd16d9f26522dcf --- /dev/null +++ b/config/shared.py @@ -0,0 +1,169 @@ +import functools +import logging +import time +from typing import Any, Dict +from xml.etree import ElementTree + +import confluent_kafka +import requests +import urllib3 +from confluent_kafka.admin import AdminClient +from confluent_kafka.cimpl import NewTopic +from minio import Minio + +from config.configuration import ConfigurationProvider, PocConfiguration + + +# Adapted from https://github.com/confluentinc/confluent-kafka-python/blob/master/examples/oauth_producer.py + +def get_oauth_token(config: PocConfiguration): + logger = logging.getLogger(__name__) + payload = { + 'grant_type': 'client_credentials' + } + logger.info(f"Sending payload: {payload} to {config.AUTH_PROVIDER_URL}") + try: + resp = requests.post(config.AUTH_PROVIDER_URL, + auth=(config.OAUTH_CLIENT_ID, config.OAUTH_CLIENT_SECRET), + data=payload, verify=config.CA_CERT_LOCATION) + except requests.exceptions.RequestException as e: + logger.error(e) + raise SystemExit("Error") + + if not resp.ok: + logger.error(f"Bad request: {resp}") + raise SystemExit("Error") + + token = resp.json() + + return token['access_token'], time.time() + float(token['expires_in']) + + +def kafka_auth_token_callback(config: PocConfiguration, _): + return get_oauth_token(config) + + +def on_delivery(err: confluent_kafka.KafkaError, msg: confluent_kafka.Message): + logger = logging.getLogger() + if err: + logger.error(err.str()) + if msg: + err = msg.error() + if not err: + logger.info(f"Sent message: {msg.value()}") + return + + logger.error(err.str()) + + +def get_shared_config(brokers: str) -> Dict[str, Any]: + config = ConfigurationProvider.get_config() + logger = logging.getLogger() + logger.addHandler(logging.StreamHandler()) + + return { + 'bootstrap.servers': brokers, + 'security.protocol': 'sasl_ssl', + 'sasl.mechanisms': 'OAUTHBEARER', + 'oauth_cb': functools.partial(kafka_auth_token_callback, config), + 'logger': logger, + 'ssl.ca.location': config.CA_CERT_LOCATION, + 'ssl.key.location': config.TLS_KEY_LOCATION, + 'ssl.certificate.location': config.TLS_CERT_LOCATION, + } + + +def get_producer_config(brokers: str) -> Dict[str, Any]: + shared_config = get_shared_config(brokers) + + return { + **shared_config, + 'on_delivery': on_delivery + } + + +def get_consumer_config(brokers: str) -> Dict[str, Any]: + shared_config = get_shared_config(brokers) + + return { + **shared_config, + 'group.id': "g0" + } + + +def get_minio_auth_data(oauth_access_token: str, configuration: PocConfiguration): + result = requests.post( + url=configuration.MINIO_URL, + headers={"Content-Type": "application/x-www-form-urlencoded"}, + params={"Action": "AssumeRoleWithWebIdentity", + "Version": "2011-06-15", + "DurationSeconds": "86000", + "WebIdentityToken": oauth_access_token + }, + verify=configuration.CA_CERT_LOCATION, + timeout=10, + ) + + if not result.ok: + logger = logging.getLogger("get_minio_auth_data") + logger.error(f"Error getting minio auth data: {result.text}") + raise Exception() + + ns_map = {"": "https://sts.amazonaws.com/doc/2011-06-15/"} + + result_xml = ElementTree.fromstring(result.content) + credentials = result_xml.find(".//Credentials", ns_map) + access_key = credentials.find("AccessKeyId", ns_map).text + secret_access_key = credentials.find("SecretAccessKey", ns_map).text + session_token = credentials.find("SessionToken", ns_map).text + + return access_key, secret_access_key, session_token + + +def configure_minio() -> Minio: + configuration = ConfigurationProvider.get_config() + token, _ = get_oauth_token(configuration) + access_key, secret_access_key, session_token = get_minio_auth_data(token, configuration) + + client = initialize_minio_client(access_key, configuration, secret_access_key, session_token) + + return client + + +def initialize_minio_client(access_key, configuration, secret_access_key, session_token): + http_client = urllib3.PoolManager( + timeout=urllib3.util.Timeout(connect=10, read=10), + maxsize=10, + cert_reqs='CERT_REQUIRED', + ca_certs=configuration.CA_CERT_LOCATION, + retries=urllib3.Retry( + total=5, + backoff_factor=0.2, + status_forcelist=[500, 502, 503, 504] + ) + ) + client = Minio( + configuration.MINIO_URL.lstrip("https://").lstrip("http://"), + access_key=access_key, + secret_key=secret_access_key, + session_token=session_token, + secure=True, + http_client=http_client + ) + return client + + +def create_bucket_if_not_exists(client: Minio, bucket_name: str): + if not client.bucket_exists(bucket_name=bucket_name): + client.make_bucket(bucket_name=bucket_name) + + +def create_topic_if_not_exists(brokers: str, topic_name: str): + shared_config = get_shared_config(brokers) + admin = AdminClient(shared_config) + topics = admin.list_topics() + + if topic_name not in topics.topics.keys(): + result = admin.create_topics(new_topics=[NewTopic(topic_name)]) + result[topics].result(10) + diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..97007f69447759e79eddbb392246b4b0964a09cd --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +requests +confluent_kafka==2.3.0 +minio +python-dotenv +fastapi +uvicorn[standard] \ No newline at end of file diff --git a/server.sh b/server.sh new file mode 100644 index 0000000000000000000000000000000000000000..09570bc588e7191f89a6ae331f254ebf432b4b62 --- /dev/null +++ b/server.sh @@ -0,0 +1,2 @@ +#!/bin/bash +uvicorn server.server:app --host 0.0.0.0 --port 443 --ssl-certfile "$TLS_CERT_LOCATION" --ssl-keyfile "$TLS_KEY_LOCATION" --ssl-ca-certs "$CA_CERT_LOCATION" \ No newline at end of file diff --git a/server/__init__.py b/server/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/server/configuration.py b/server/configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..fe5936a353e33a9522a8152b5f311c148e3fdcb3 --- /dev/null +++ b/server/configuration.py @@ -0,0 +1,17 @@ +from fastapi import Request, HTTPException +from minio import Minio + +from config.configuration import ConfigurationProvider +from config.shared import get_minio_auth_data, initialize_minio_client + + +def configure_minio_for_server(request: Request) -> Minio: + configuration = ConfigurationProvider.get_config() + + token = request.headers.get("Authorization", "").removeprefix("Bearer ") + if not token: + raise HTTPException(status_code=401, detail="Unauthorized") + + access_key, secret_access_key, session_token = get_minio_auth_data(token, configuration) + + return initialize_minio_client(access_key, configuration, secret_access_key, session_token) \ No newline at end of file diff --git a/server/data_access.py b/server/data_access.py new file mode 100644 index 0000000000000000000000000000000000000000..fc27485a4e829691e7c29c0576ab205bf6f4a581 --- /dev/null +++ b/server/data_access.py @@ -0,0 +1,32 @@ +import io + +from fastapi import Depends, HTTPException +from minio import Minio + +from server.configuration import configure_minio_for_server +from config.shared import create_bucket_if_not_exists + + +class MinIoDal: + INPUT_BUCKET = "module-input" + OUTPUT_BUCKET = "module-output" + + def __init__(self, minio_client: Minio = Depends(configure_minio_for_server)): + self.minio_client = minio_client + + create_bucket_if_not_exists(self.minio_client, MinIoDal.INPUT_BUCKET) + create_bucket_if_not_exists(self.minio_client, MinIoDal.OUTPUT_BUCKET) + + def get_object(self, object_name: str) -> bytes: + try: + response = self.minio_client.get_object(MinIoDal.OUTPUT_BUCKET, object_name) + return response.read() + except Exception: + raise HTTPException(status_code=404, detail="Object not found") + finally: + response.close() + response.release_conn() + + def put_object(self, object_name: str, data: bytes) -> None: + byte_stream = io.BytesIO(data) + self.minio_client.put_object(MinIoDal.INPUT_BUCKET, object_name, byte_stream, len(data), "text/plain") diff --git a/server/server.py b/server/server.py new file mode 100644 index 0000000000000000000000000000000000000000..2fe8deb4d4ef2f527ca42c567f92f3339009ec54 --- /dev/null +++ b/server/server.py @@ -0,0 +1,20 @@ +import fastapi +from fastapi import Request, Depends +from server.data_access import MinIoDal + +app = fastapi.FastAPI() + + +@app.get('/product') +async def get_product(): + return {"data": "hello world"} + + +@app.get('/counter/{item_id}') +async def read_item(item_id: str, dal: MinIoDal = Depends(MinIoDal)): + return {"data": dal.get_object(item_id).decode("utf-8")} + + +@app.post('/counter/{item_id}', status_code=201) +async def post_item(item_id: str, request: Request, dal: MinIoDal = Depends(MinIoDal)): + dal.put_object(item_id, await request.body())