Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
199 changes: 199 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
name: Main Taski workflow

on:
push:
branches:
- main

jobs:
tests:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:13.10
env:
POSTGRES_USER: django_user
POSTGRES_PASSWORD: django_password
POSTGRES_DB: django_db
ports:
- 5432:5432
options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5

steps:
- uses: actions/checkout@v3

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: 3.12

- name: Install dependencies
run: |
python -m pip install --upgrade pip setuptools
pip install flake8==6.0.0 flake8-isort==6.0.0
pip install -r ./backend/requirements.txt

- name: Test with flake8 and django tests
env:
POSTGRES_USER: django_user
POSTGRES_PASSWORD: django_password
POSTGRES_DB: django_db
DB_HOST: 127.0.0.1
DB_PORT: 5432
run: |
python -m flake8 backend/
cd backend/
python manage.py test

build_and_push_to_docker_hub:
name: Push Docker image to DockerHub
runs-on: ubuntu-latest
needs: tests

steps:
- name: Check out the repo
uses: actions/checkout@v3

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2

- name: Login to Docker
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}

- name: Push to DockerHub
uses: docker/build-push-action@v4
with:
context: ./backend/
push: true
tags: zulkex93/taski_backend:latest

frontend_tests:
runs-on: ubuntu-latest
needs: tests

steps:
- uses: actions/checkout@v3

- name: Set up nodeJS
uses: actions/setup-node@v3
with:
node-version: 18

- name: Install dependencies
run: |
cd frontend/
npm ci

- name: Test frontend
run: |
cd frontend/
npm run test

build_frontend_and_push_to_docker_hub:
name: Push frontend Docker image to DockerHub
runs-on: ubuntu-latest
needs: frontend_tests

steps:
- name: Check out the repo
uses: actions/checkout@v3

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2

- name: Login to Docker
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}

- name: Push to DockerHub
uses: docker/build-push-action@v4
with:
context: ./frontend/
push: true
tags: zulkex93/taski_frontend:latest

build_gateway_and_push_to_docker_hub:
name: Push gateway Docker image to DockerHub
runs-on: ubuntu-latest

steps:
- name: Check out the repo
uses: actions/checkout@v3

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2

- name: Login to Docker
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}

- name: Push to DockerHub
uses: docker/build-push-action@v4
with:
context: ./gateway/
push: true
tags: zulkex93/taski_gateway:latest

deploy:
runs-on: ubuntu-latest
needs:
- build_and_push_to_docker_hub
- build_frontend_and_push_to_docker_hub
- build_gateway_and_push_to_docker_hub

steps:
- name: Checkout repo
uses: actions/checkout@v3

- name: Copy docker-compose.yml via ssh
uses: appleboy/scp-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USER }}
key: ${{ secrets.SSH_KEY }}
passphrase: ${{ secrets.SSH_PASSPHRASE }}
source: "docker-compose.production.yml"
target: "taski"

- name: Executing remote ssh commands to deploy
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USER }}
key: ${{ secrets.SSH_KEY }}
passphrase: ${{ secrets.SSH_PASSPHRASE }}
script: |
cd taski
sudo docker compose -f docker-compose.production.yml pull
sudo docker compose -f docker-compose.production.yml down
sudo docker compose -f docker-compose.production.yml up -d
# Даем контейнерам время на запуск
sleep 10
# Выполняем миграции
sudo docker compose -f docker-compose.production.yml exec backend python manage.py migrate
# Собираем статику
sudo docker compose -f docker-compose.production.yml exec backend python manage.py collectstatic --noinput
# Копируем статику в нужную директорию
sudo docker compose -f docker-compose.production.yml exec backend cp -r /app/collected_static/. /backend_static/static/

send_message:
runs-on: ubuntu-latest
needs: deploy

steps:
- name: Send Telegram notification
uses: appleboy/telegram-action@master
with:
to: ${{ secrets.TELEGRAM_TO }}
token: ${{ secrets.TELEGRAM_TOKEN }}
message: |
✅ Деплой проекта Taski успешно выполнен!
🚀 Образы обновлены и контейнеры перезапущены
📅 $(date -u)
4 changes: 4 additions & 0 deletions backend/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Файл .dockerignore
venv
.git
db.sqlite3
30 changes: 30 additions & 0 deletions backend/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Создать образ на основе базового слоя,
# который содержит файлы ОС и интерпретатор Python 3.12.
FROM python:3.12

# Переходим в образе в директорию /app: в ней будем хранить код проекта.
# Если директории с указанным именем нет, она будет создана.
# Название директории может быть любым.
WORKDIR /app
# Дальнейшие инструкции будут выполняться в директории /app

# Обновляем pip и устанавливаем setuptools (включает distutils)
RUN pip install --upgrade pip setuptools

RUN pip install gunicorn==23.0.0
# Скопировать с локального компьютера файл зависимостей
# в текущую директорию (текущая директория — это /app).
COPY requirements.txt .

# Выполнить в текущей директории команду терминала
# для установки зависимостей.
RUN pip install -r requirements.txt --no-cache-dir

# Скопировать всё необходимое содержимое
# той директории локального компьютера, где сохранён Dockerfile,
# в текущую рабочую директорию образа — /app.
COPY . .

# При старте контейнера запустить сервер разработки.
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "backend.wsgi"]

22 changes: 22 additions & 0 deletions backend/api/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# backend/api/tests.py
from http import HTTPStatus

from api import models
from django.test import Client, TestCase


class TaskiAPITestCase(TestCase):
def setUp(self):
self.guest_client = Client()

def test_list_exists(self):
"""Проверка доступности списка задач."""
response = self.guest_client.get('/api/tasks/')
self.assertEqual(response.status_code, HTTPStatus.OK)

def test_task_creation(self):
"""Проверка создания задачи."""
data = {'title': 'Test', 'description': 'Test'}
response = self.guest_client.post('/api/tasks/', data=data)
self.assertEqual(response.status_code, HTTPStatus.CREATED)
self.assertTrue(models.Task.objects.filter(title='Test').exists())
20 changes: 16 additions & 4 deletions backend/backend/settings.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent


SECRET_KEY = 'django-insecure-j_89af+30&&4qm*8z9_(^zz8p4-ho8z_m6ylm0s$h!-p@on1_^'

DEBUG = True
DEBUG = False

ALLOWED_HOSTS = []
ALLOWED_HOSTS = ['*']


# Application definition
Expand Down Expand Up @@ -61,8 +62,12 @@

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ.get('POSTGRES_DB', 'django'),
'USER': os.environ.get('POSTGRES_USER', 'django_user'),
'PASSWORD': os.environ.get('POSTGRES_PASSWORD', 'mysecretpassword'),
'HOST': os.environ.get('DB_HOST', 'db'),
'PORT': os.environ.get('DB_PORT', '5432'),
}
}

Expand Down Expand Up @@ -103,7 +108,14 @@
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

# При планировании архитектуры было решено,
# что статические файлы Django должны быть доступны по адресу /static/
STATIC_URL = '/static/'
# Указываем корневую директорию для сборки статических файлов;
# в контейнере это будет /app/collected_static
STATIC_ROOT = '/app/collected_static'
# Теперь при вызове команды python manage.py collectstatic
# Django будет копировать все статические файлы в директорию collected_static

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
Expand Down
Binary file added backend/db.sqlite3.bak
Binary file not shown.
3 changes: 2 additions & 1 deletion backend/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
Django==3.2.3
djangorestframework==3.12.4
django-cors-headers==3.13.0
django-cors-headers==3.13.0
psycopg2-binary==2.9.11
30 changes: 30 additions & 0 deletions docker-compose.production.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# docker-compose.production.yml

volumes:
pg_data_production:
static_volume:

services:
db:
image: postgres:13.10
env_file: .env
volumes:
- pg_data_production:/var/lib/postgresql/data
backend:
image: zulkex93/taski_backend
env_file: .env
volumes:
- static_volume:/backend_static
frontend:
image: zulkex93/taski_frontend
env_file: .env
command: cp -r /app/build/. /frontend_static/
volumes:
- static_volume:/frontend_static
gateway:
image: zulkex93/taski_gateway
env_file: .env
volumes:
- static_volume:/staticfiles/
ports:
- 8000:80
34 changes: 34 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Файл docker-compose.yml
version: '3.8'

# Перечень volume
volumes:
pg_data:
static:

services:
db:
image: postgres:13
env_file: .env
volumes:
- pg_data:/var/lib/postgresql/data
backend:
build: ./backend/
env_file: .env
volumes:
- static:/backend_static

frontend:
env_file: .env
build: ./frontend/
command: cp -r /app/build/. /frontend_static/
volumes:
- static:/frontend_static

gateway:
build: ./gateway/
env_file: .env
volumes:
- static:/staticfiles
ports:
- 8000:80
4 changes: 4 additions & 0 deletions frontend/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# frontend/.dockerignore
node_modules
build
.env
1 change: 1 addition & 0 deletions frontend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

# misc
.DS_Store
.env
.env.local
.env.development.local
.env.test.local
Expand Down
Loading