Skip to content
Snippets Groups Projects
Commit 438fd5c8 authored by Adam Chovan's avatar Adam Chovan
Browse files

init server

parent 8779bd84
No related branches found
No related tags found
No related merge requests found
Pipeline #406969 passed
# 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
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" ]
# 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
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
from dataclasses import dataclass
@dataclass
class NotificationDto:
bucket: str
file: str
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)
#!/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
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
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")
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())
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment