Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

40 func/setup prod #24

Merged
merged 40 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
a64cc94
func: setup docker do projeto
Oct 11, 2024
ab6fa00
func: definindo restart da aplicação junto ao restart da máquina
ryandaraujo Oct 21, 2024
e13dc37
oper: add deploy action e rodando testes em todas branches
iagocpv Oct 23, 2024
862a3ac
oper: alterando extencao do arquivo da action
iagocpv Oct 23, 2024
49f9d47
corr: fix deploy action
iagocpv Oct 23, 2024
1d4c8f0
oper: trocando scp por rsync para ignorar algumas pastas
iagocpv Oct 23, 2024
936c45c
oper: criando arquivo .env
iagocpv Oct 23, 2024
64bbd8e
oper: pegando host e porta do banco no secret
iagocpv Oct 23, 2024
2f119ac
oper: rodando migracoes no dockerfile
iagocpv Oct 23, 2024
407493c
corr: fix url do database
iagocpv Oct 30, 2024
33905ec
corr: adicionando sudo ao comando rsync
iagocpv Oct 30, 2024
b895a47
Merge branch 'main' into 40-func/setup-prod
iagocpv Nov 4, 2024
1c787c2
corr: removendo arquivo de migracao antigo
iagocpv Nov 4, 2024
86ac8dd
oper: adicionando opcao para deletar arquivos antigos no comando rsync
iagocpv Nov 4, 2024
6a35afd
corr: criando .env apos copiar o codigo
iagocpv Nov 4, 2024
7fea241
oper: removendo -d do docker-compose up
iagocpv Nov 4, 2024
89e9be9
corr: fix criacao do dotenv
iagocpv Nov 4, 2024
fdff4a0
oper: criando entrypoint
iagocpv Nov 4, 2024
e071958
oper: copiando entrypoint para o container
iagocpv Nov 4, 2024
c974462
oper: adicionando secret key
iagocpv Nov 4, 2024
167c167
corr: removendo comandos cmd apos o entrypoint
iagocpv Nov 4, 2024
ed606fc
oper: adicionando rebuild do compose
iagocpv Nov 4, 2024
fa0e7c8
oper: adicionando permissoes ao arquivo entrypoint
iagocpv Nov 4, 2024
376bca8
oper: alterando versao do netcat
iagocpv Nov 4, 2024
4b66ddd
oper: juntando teste com deploy
iagocpv Nov 5, 2024
974bd36
oper: testando ci/cd
iagocpv Nov 5, 2024
0e2f0b7
corr: arrumando erro do secrets
iagocpv Nov 5, 2024
d2b3107
corr: alterando postgres teste de service para step
iagocpv Nov 5, 2024
81969c1
oper: teste action
iagocpv Nov 5, 2024
b3f248b
oper: add python 3.10 na matrix
iagocpv Nov 5, 2024
da79d6b
oper: alterando para action rodar em branches que contem /
iagocpv Nov 5, 2024
554e676
oper: alterando python 3.10 para 3.12 na action
iagocpv Nov 5, 2024
d61b595
oper: alterando para rodar testes apenas na versao 3.12
iagocpv Nov 5, 2024
bd7dbfe
corr: corrigindo caminho do script que roda as migracoes
iagocpv Nov 5, 2024
d5f95a1
oper: criando .env na maquina de teste do github
iagocpv Nov 5, 2024
7b4cde9
corr: alterando para rodar teste no banco localhost
iagocpv Nov 5, 2024
7204194
oper: trocando para requirements-dev na action de teste
iagocpv Nov 5, 2024
15c88a6
oper: rodando pytest na pasta correta
iagocpv Nov 5, 2024
91c542d
oper: rodando actions apenas no push
iagocpv Nov 5, 2024
ae3a45a
oper: add teste de integracao
iagocpv Nov 6, 2024
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
66 changes: 0 additions & 66 deletions .github/workflows/django.yml

This file was deleted.

117 changes: 117 additions & 0 deletions .github/workflows/testAndDeploy.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
name: Django CI & Deploy

on:
push:
branches:
- '**' # Trigger on push to any branch

jobs:
build:
runs-on: ubuntu-latest
strategy:
max-parallel: 4
matrix:
python-version: [3.12]
steps:
- uses: actions/checkout@v4

- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}

- name: Install Dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt

- name: Start PostgreSQL service
run: |
docker run --name postgres-db -d \
-e POSTGRES_USER=${{ secrets.DB_USERNAME }} \
-e POSTGRES_PASSWORD=${{ secrets.DB_PASSWORD }} \
-e POSTGRES_DB=${{ secrets.DB_NAME }} \
-p 5432:5432 postgres:13
# Wait until PostgreSQL is ready
until docker exec postgres-db pg_isready -U ${{ secrets.DB_USERNAME }}; do
echo "Waiting for PostgreSQL to be ready...";
sleep 5;
done

- name: Create .env file on git machine
run: |
echo "SECRET_KEY=${{ secrets.SECRET_KEY }}" >> .env
echo "DB_USER=${{ secrets.DB_USERNAME }}" >> .env
echo "DB_PASSWORD=${{ secrets.DB_PASSWORD }}" >> .env
echo "DB_NAME=${{ secrets.DB_NAME }}" >> .env
echo "DB_HOST=localhost" >> .env
echo "DB_PORT=${{ secrets.DB_PORT }}" >> .env

- name: Apply Django Migrations
run: |
python src/tupan/manage.py makemigrations
python src/tupan/manage.py migrate

- name: Run Tests
run: |
cd src/tupan && pytest

- name: Stop PostgreSQL container
run: |
docker stop postgres-db
docker rm postgres-db

# Job for deploying to AWS EC2, only if the build job is successful
deploy:
runs-on: ubuntu-24.04
needs: build # This job will only run if the build job is successful
if: github.ref == 'refs/heads/main' # Run only on push to the main branch
env:
AWS_PRIVATE_KEY: ${{ secrets.KEYAWS }}
SSH_OPTIONS: '-o StrictHostKeyChecking=no -i key.pem ubuntu@98.80.44.121'

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Set permissions for private key
run: |
echo "${{ env.AWS_PRIVATE_KEY }}" > key.pem
chmod 600 key.pem

- name: Stop running containers
run: |
ssh ${{ env.SSH_OPTIONS }} 'if [ -d /home/ubuntu/tupan-back/ ]; then cd /home/ubuntu/tupan-back/ && sudo docker-compose down; fi'

- name: Create target directory on AWS instance
run: |
ssh ${{ env.SSH_OPTIONS }} 'mkdir -p /home/ubuntu/tupan-back/'

- name: Create .env file
run: |
echo "SECRET_KEY=${{ secrets.SECRET_KEY }}" >> .env
echo "DB_USER=${{ secrets.DB_USERNAME }}" >> .env
echo "DB_PASSWORD=${{ secrets.DB_PASSWORD }}" >> .env
echo "DB_NAME=${{ secrets.DB_NAME }}" >> .env
echo "DB_HOST=${{ secrets.DB_HOST }}" >> .env
echo "DB_PORT=${{ secrets.DB_PORT }}" >> .env

- name: Transfer code to AWS instance
run: |
rsync -av --delete --exclude='.git' --exclude='.github' --exclude='.husky' -e "ssh -o StrictHostKeyChecking=no -i key.pem" --rsync-path="sudo rsync" ./ ubuntu@98.80.44.121:/home/ubuntu/tupan-back

- name: Set permissions for entrypoint
run: |
ssh ${{ env.SSH_OPTIONS }} 'cd /home/ubuntu/tupan-back/ && sudo chmod +x entrypoint.sh'

- name: Build Docker Compose
run: |
ssh ${{ env.SSH_OPTIONS }} 'cd /home/ubuntu/tupan-back/ && sudo docker-compose build'

- name: Run Docker Compose
run: |
ssh ${{ env.SSH_OPTIONS }} 'cd /home/ubuntu/tupan-back/ && sudo docker-compose up -d'

- name: Cleanup SSH key
run: |
rm -f key.pem
28 changes: 28 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
FROM python:3.11

# Definir o diretório de trabalho dentro do container
WORKDIR /app

# Instalar netcat (openbsd)
RUN apt-get update && apt-get install -y netcat-openbsd

# Copiar o arquivo de requisitos para o container
COPY requirements.txt /app/
COPY entrypoint.sh /app/

# Instalar as dependências
RUN pip install --upgrade pip && pip install -r requirements.txt

# Copiar o código da aplicação
COPY . /app/

# Criar um script de entrada
COPY entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh

# Expôr a porta que o Django vai usar
EXPOSE 8000

# Comando para rodar o script de entrada
CMD ["/app/entrypoint.sh"]

28 changes: 28 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
version: '3'

services:
web:
image: tupan-back
build: .
volumes:
- .:/app
ports:
- "8000:8000"
environment:
- DEBUG=True
- DATABASE_URL=postgres://postgres:fatec@db:5432/tupan
restart: always
db:
image: postgres
environment:
POSTGRES_DB: tupan
POSTGRES_USER: postgres
POSTGRES_PASSWORD: fatec
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data/
restart: always
volumes:
postgres_data:

15 changes: 15 additions & 0 deletions entrypoint.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/bin/bash

# Aguarde o PostgreSQL estar pronto
echo "Aguardando o PostgreSQL estar pronto..."
while ! nc -z db 5432; do
sleep 0.1 # espera 1/10 de segundo
done
echo "PostgreSQL está pronto!"

# Rodar migrações
python src/tupan/manage.py makemigrations
python src/tupan/manage.py migrate --noinput

# Iniciar o servidor
exec python src/tupan/manage.py runserver 0.0.0.0:8000
71 changes: 0 additions & 71 deletions src/tupan/alertas/tests.py
Original file line number Diff line number Diff line change
@@ -1,73 +1,2 @@
import pytest
import json
from django.urls import reverse
from .models import Alerta, HistoricoAlerta

@pytest.fixture
def alerta_auxiliar():
alerta = {
"nome": "Alerta1",
"condicao": "<2",
}
return alerta


class TestAlerta:
@pytest.mark.django_db
def teste_criar_alerta(self, alerta_auxiliar):
Alerta.objects.create(**alerta_auxiliar)

assert Alerta.objects.count() == 1
alerta_no_banco = Alerta.objects.first()

assert alerta_no_banco.pk == 1
assert alerta_no_banco.nome == alerta_auxiliar['nome']
assert alerta_no_banco.condicao == alerta_auxiliar['condicao']
assert alerta_no_banco.ativo == True

@pytest.mark.django_db
def teste_url_listar_alertas(self, client, alerta_auxiliar):
Alerta.objects.create(**alerta_auxiliar)

url = reverse("alertas")
response = client.get(url)

json_data = response.json()

assert response.status_code == 200
assert len(json_data) == 1
assert json_data[0]['nome'] == "Alerta1"
assert json_data[0]['condicao'] == "<2"

@pytest.mark.django_db
def teste_url_cadastrar_alerta(self, client, alerta_auxiliar):

url = reverse("alertas")
response = client.post(url, data=json.dumps(alerta_auxiliar), content_type="application/json")

json_data = response.json()
assert response.status_code == 201
assert json_data['nome'] == 'Alerta1'
assert json_data['ativo'] == True


class TestHistoricoAlerta:
@pytest.fixture
def historico_alerta_auxiliar(self, alerta_auxiliar):
alerta = Alerta.objects.create(**alerta_auxiliar)
hist = {
"timestamp": 1726067292,
"alerta": alerta
}
return hist

@pytest.mark.django_db
def teste_criar_historico(self, historico_alerta_auxiliar):
HistoricoAlerta.objects.create(**historico_alerta_auxiliar)

assert HistoricoAlerta.objects.count() == 1
historico_no_banco = HistoricoAlerta.objects.first()

assert historico_no_banco.pk == 1
assert historico_no_banco.timestamp == historico_alerta_auxiliar['timestamp']
assert historico_no_banco.alerta == historico_alerta_auxiliar['alerta']
7 changes: 2 additions & 5 deletions src/tupan/tupan/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []
ALLOWED_HOSTS = ["*"]

AUTH_USER_MODEL = 'usuarios.Usuario'

Expand Down Expand Up @@ -88,10 +88,7 @@
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ALLOWED_ORIGINS = [
'http://localhost:3000',
]

CORS_ALLOW_ALL_ORIGINS = True
ROOT_URLCONF = 'tupan.urls'

TEMPLATES = [
Expand Down
Loading
Loading