Skip to content

Commit

Permalink
feat: basic deployment flow and logic setup
Browse files Browse the repository at this point in the history
  • Loading branch information
tushar5526 committed Dec 27, 2023
0 parents commit bb38ef4
Show file tree
Hide file tree
Showing 15 changed files with 594 additions and 0 deletions.
19 changes: 19 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: Testing

on:
push:
branches:
- main

jobs:
Test:
runs-on: ubuntu-latest
name: Testing the action
steps:
- name: Checkout
uses: actions/checkout@v2

- name: Run action
uses: ./action
with:
name: 'John'
21 changes: 21 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

.idea**

server/deployments/*
server/nginx-confs/*
8 changes: 8 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright (c) 2023, Tushar Gupta

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.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
## Sarthi <img alt="action-badge" src="https://img.shields.io/badge/Sarthi-white?logo=github-actions&label=GitHub%20Action&labelColor=white&color=0064D7"> <a href="https://github.com/lnxpy/cookiecutter-pyaction"><img alt="cookiecutter-pyaction" src="https://img.shields.io/badge/cookiecutter--pyaction-white?logo=cookiecutter&label=Made%20with&labelColor=white&color=0064D7"></a>

Easy to setup Docker based empheral previews!

### Usage
```yml
example usage..
```

### License
This action is licensed under some specific terms. Check [here](LICENSE) for more information.


# TODOs

1. Grafana + Loki + Prometheus Setup in docker compose
2. Dockerize the project
3. Vault Setup
4. GitHub Actions Setup
5. Tests
27 changes: 27 additions & 0 deletions action/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Ignore all files and folders that start with a dot.
**/*.

# Ignore all virtual envs'
venv/

# Ignore all Python bytecode files.
__pycache__/

# Ignore all temporary files.
*.tmp
*.swp

# Ignore all build artifacts.
build/
dist/

# Ignore all pyaction-related files.
README.md
CONTRIBUTING.md
CHANGELOG.md
LICENSE
Dockerfile
.env
.github/

.git/
11 changes: 11 additions & 0 deletions action/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# setting the base-image to alpine
FROM python:3-slim

# importing the action
COPY . /action

# installing the requirements
RUN pip install -U pip -r /action/requirements.txt

# running the main.py file
CMD [ "python", "/action/main.py" ]
23 changes: 23 additions & 0 deletions action/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Sarthi
description: Easy to setup Docker based empheral previews!
author: Tushar Gupta

branding:
icon: check
color: blue

runs:
using: docker
image: Dockerfile

# == inputs and outputs ==

inputs:
name:
required: false
description: the person/thing you want to greet
default: World

outputs:
phrase:
description: output variable
23 changes: 23 additions & 0 deletions action/io.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import os
from typing import Dict

BUFFER_PATH = os.environ["GITHUB_OUTPUT"]


def write_to_output(context: Dict[str, str]) -> None:
"""writes the keys (as variables) and values (as values) to the output buffer
Args:
context: variables and values
Examples:
In your project, use this function like:
>>> write_to_output({"name": "John", ...})
``name`` will be the variable name and ``John`` is the value.
"""

with open(BUFFER_PATH, "a") as _buffer:
for var, val in context.items():
_buffer.write(f"{var}={val}\r\n")
23 changes: 23 additions & 0 deletions action/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import os
import sys
import typing


def main(args: typing.List[str]) -> None:
"""main function
Args:
args: STDIN arguments
"""
# GITHUB_REPOSITORY : octocat/Hello-World
project_name = os.environ.get("GITHUB_REPOSITORY").split("/")[1]
branch_name = os.environ.get("GITHUB_HEAD_REF")
username = os.environ.get("INPUT_REMOTE_USER")
password = os.environ.get("INPUT_REMOTE_PASSWORD")
host = os.environ.get("INPUT_REMOTE_HOST")
port = os.environ.get("INPUT_PORT") or 22
deployment_domain = os.environ.get("INPUT_DEPLOYMENT_DOMAIN")


if __name__ == "__main__":
main(sys.argv)
1 change: 1 addition & 0 deletions action/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

52 changes: 52 additions & 0 deletions server/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import logging
import os

import jwt
from dotenv import load_dotenv
from flask import Flask, jsonify, request
from flask_httpauth import HTTPTokenAuth

from deployer import Deployer, DeploymentConfig

load_dotenv()

if os.environ.get("ENV").lower() == "local":
logging.basicConfig(level=logging.NOTSET)


app = Flask(__name__)
auth = HTTPTokenAuth("Bearer")
app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY")


@auth.verify_token
def verify_token(token):
try:
data = jwt.decode(token, app.config["SECRET_KEY"], algorithms=["HS256"])
except: # noqa: E722
return False
return "root"


# Your deployment endpoint
@app.route("/deploy", methods=["POST"])
# @auth.login_required
def deploy():
data = request.get_json()

# Create DeploymentConfig object
project_url_split = data.get("project_git_url").split('/')
config = DeploymentConfig(
project_name=f'{project_url_split[-2]}_{project_url_split[-1]}',
branch_name=data.get("branch_name"),
project_git_url=data.get("project_git_url"),
compose_file_location=data.get("compose_file_location") or "docker-compose.yml",
)

deployer = Deployer(config)
urls = deployer.deploy()
return jsonify(urls)


if __name__ == "__main__":
app.run(debug=True, use_reloader=False)
86 changes: 86 additions & 0 deletions server/deployer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import logging
import os
import shutil
import subprocess
import typing

from utils import ComposeHelper, DeploymentConfig, NginxHelper

logger = logging.getLogger(__name__)


class Deployer:
def __init__(self, config: DeploymentConfig):
self._config = config
self._BASE_DIR: typing.Final[str] = os.environ.get("BASE_DIR")
self._project_path: typing.Final[str] = os.path.join(
self._BASE_DIR, config.get_project_hash()
)
self._setup_project()

self._compose_helper = ComposeHelper(
os.path.join(self._project_path, config.compose_file_location)
)
self._nginx_helper = NginxHelper(config)
self._deployment_namespace = config.get_project_hash()
self._outer_proxy_conf_location = (
os.environ.get("NGINX_PROXY_CONF_LOCATION") or "/etc/nginx/conf.d"
)

def _clone_project(self):
process = subprocess.Popen(
[
"git",
"clone",
"-b",
self._config.branch_name,
self._config.project_git_url,
self._project_path,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)

stdout, stderr = process.communicate()

if process.returncode == 0:
logger.info("Git clone successful.")
else:
logger.error(f"Git clone failed. Return code: {process.returncode}")
logger.error("Standard Output:")
logger.error(stdout.decode())
logger.error("Standard Error:")
logger.error(stderr.decode())
raise Exception("Git clone failed")

def _setup_project(self):
if os.path.exists(self._project_path):
# TODO: Run docker compose down -v
logger.debug(f"Removing older project path {self._project_path}")
shutil.rmtree(self._project_path)
self._clone_project()

def _configure_outer_proxy(self):
if not self._project_nginx_port:
raise Exception("Project Proxy not deployed, project_nginx_port is None")
self._nginx_helper.generate_outer_proxy_conf_file(
self._project_nginx_port, self._outer_proxy_conf_location
)
self._nginx_helper.reload_nginx()

def _deploy_project(self):
services = self._compose_helper.get_service_ports_config()
conf_file_path, urls = self._nginx_helper.generate_project_proxy_conf_file(
services, self._project_path
)
# TODO: Keep retrying finding a new port for race conditions
self._project_nginx_port = self._nginx_helper.find_free_port()
self._compose_helper.start_services(
self._project_nginx_port, conf_file_path, self._deployment_namespace
)
return urls

def deploy(self):
urls = self._deploy_project()
self._configure_outer_proxy()
return urls
10 changes: 10 additions & 0 deletions server/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version: '3'

services:
nginx:
image: nginx:latest
container_name: sarthi_nginx
ports:
- "80:80"
volumes:
- ./nginx-confs:/etc/nginx/conf.d
4 changes: 4 additions & 0 deletions server/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pyyaml
flask
pyjwt
Flask - HTTPAuth
Loading

0 comments on commit bb38ef4

Please sign in to comment.