diff --git a/README.md b/README.md new file mode 100644 index 0000000..c93c31d --- /dev/null +++ b/README.md @@ -0,0 +1,24 @@ +### Сервер отчетов + +#### Развертывание + +1. Клонировать репозиторий + +```bash +git clone http://git.hronos.su:8080/sabron/repcofkk.git +``` + +2. Запустить compose + +```bash +docker-compose up -d +``` + +3. Создать суперпользователя + +```bash +docker compose exec web python manage.py createsuperuser +``` + +4. Заполнить переменные в админке +5. Перезапустить сервис `celery` и `gunicorn` \ No newline at end of file diff --git a/app/apps/main/services/accident_stops/service.py b/app/apps/main/services/accident_stops/service.py index 13f0067..c1c08d1 100644 --- a/app/apps/main/services/accident_stops/service.py +++ b/app/apps/main/services/accident_stops/service.py @@ -6,7 +6,7 @@ from apps.main.services.base_service import DashboardBaseService class AccidentStopsService(DashboardBaseService): def get_stops_by_ranges(self) -> dict: - now_date = timezone.now() + now_date = self.get_current_time() start_month = now_date - relativedelta(hours=730) start_week = now_date - relativedelta(hours=168) start_day = now_date - relativedelta(hours=24) diff --git a/app/apps/main/services/base_service.py b/app/apps/main/services/base_service.py index e55bd9b..09543cb 100644 --- a/app/apps/main/services/base_service.py +++ b/app/apps/main/services/base_service.py @@ -1,4 +1,7 @@ +from datetime import timedelta + from django.db.models import Model +from django.utils import timezone class DashboardBaseService: @@ -15,3 +18,7 @@ class DashboardBaseService: def get_latest_value(self): self.model.objects.latest("time") + + @staticmethod + def get_current_time(): + return timezone.now() diff --git a/app/apps/main/services/workstatus/service.py b/app/apps/main/services/workstatus/service.py index 41d2f1f..ddcd155 100644 --- a/app/apps/main/services/workstatus/service.py +++ b/app/apps/main/services/workstatus/service.py @@ -1,4 +1,4 @@ -from datetime import timedelta +from datetime import timedelta, datetime from dateutil.relativedelta import relativedelta from django.utils import timezone @@ -9,29 +9,29 @@ from sabron.util import logging class WorkStatusService(DashboardBaseService): def get_current_status(self): - now_date = timezone.now() + now_date = self.get_current_time() start_month = now_date - relativedelta(hours=730) status_list = list(self.get_qs_by_range(start_month, now_date)) if not status_list: return {"last_status": "WO", "worktime": timedelta(0)} last_status = status_list[-1] - if last_status["time"] < (timezone.now() - timedelta(minutes=5)): + if last_status["time"] < (self.get_current_time() - timedelta(minutes=5)): logging.message( - f"Fabric Stopped {timezone.now()} ({timezone.now() - timedelta(minutes=5)})" + f"Fabric Stopped {self.get_current_time()} ({self.get_current_time() - timedelta(minutes=5)})" ) return { "last_status": "NW", - "worktime": timezone.now() - last_status["time"], + "worktime": self.get_current_time() - last_status["time"], } if len(status_list) < 2: return { "last_status": status_list[0]["status"], - "worktime": timezone.now() - status_list[0]["time"], + "worktime": self.get_current_time() - status_list[0]["time"], } start_status = status_list[-2] while start_status["status"] == last_status["status"] and len(status_list) >= 1: start_status = status_list.pop() - now_date = timezone.now() + now_date = self.get_current_time() duration = now_date - last_status["time"] status_worktime = last_status["time"] - start_status["time"] + duration return {"last_status": last_status["status"], "worktime": status_worktime} diff --git a/app/apps/main/services/worktime/service.py b/app/apps/main/services/worktime/service.py index a161e86..991ce39 100644 --- a/app/apps/main/services/worktime/service.py +++ b/app/apps/main/services/worktime/service.py @@ -9,8 +9,8 @@ from apps.main.tasks import create_worktime_data class FabricWorkTimeService(DashboardBaseService): - @staticmethod - def calculate_work_time(qs: list, return_duration: bool = False) -> dict: + @classmethod + def calculate_work_time(cls, qs: list, return_duration: bool = False) -> dict: status_durations = {"WO": timedelta(0), "WA": timedelta(0), "NW": timedelta(0)} if not qs: @@ -29,7 +29,7 @@ class FabricWorkTimeService(DashboardBaseService): previous_time = current_time previous_status = current_status - now_date = timezone.now() + now_date = cls.get_current_time() duration = now_date - previous_time status_durations[previous_status] += duration if return_duration: @@ -41,7 +41,7 @@ class FabricWorkTimeService(DashboardBaseService): return status_durations_hours def return_worktime(self, return_durations: bool = False): - now_date = timezone.now() + now_date = self.get_current_time() start_month = now_date - relativedelta(hours=730) start_week = now_date - relativedelta(hours=168) start_day = now_date - relativedelta(hours=24) diff --git a/app/apps/main/tasks.py b/app/apps/main/tasks.py index a53ff8e..033cfdd 100644 --- a/app/apps/main/tasks.py +++ b/app/apps/main/tasks.py @@ -1,8 +1,7 @@ import decimal import os import traceback -from datetime import datetime, timedelta -from typing import Any +from datetime import timedelta from dateutil.relativedelta import relativedelta @@ -83,13 +82,21 @@ def create_scales_control_data(): def thin_out_scales(): positions = Position.objects.all() for position in positions: - print(position) - thin_out_scale(position.aver_smena_tag) - thin_out_scale(position.aver_pred_smena_tag) - thin_out_scale(position.smena_tag) - thin_out_scale(position.pred_smena_tag) - thin_out_scale(position.month_tag) - thin_out_scale(position.sutki_tag) + pos_tags = [position.aver_smena_tag, + position.aver_pred_smena_tag, + position.smena_tag, + position.pred_smena_tag, + position.month_tag, + position.sutki_tag] + for tag in pos_tags: + try: + res = thin_out_scale(tag) + if not res: + return 'No scales Data' + return f'Success. Deleted: {res}' + except Exception: + logging.error(f'Celery: {traceback.format_exc()} \n on tag {tag}') + return f'Exception: {traceback.format_exc()}' @shared_task @@ -97,14 +104,17 @@ def thin_out_worktime(): worktime_qs = FabricWorkTime.objects.filter( time__lt=timezone.now() - timedelta(hours=12) ).order_by("time") + if not worktime_qs: + return 'No worktime' prev = worktime_qs[0] for cur_obj in worktime_qs[1:]: if cur_obj.status == prev.status: cur_obj.delete() prev = cur_obj + return f'Success. Deleted: {len(worktime_qs)} rows' -def thin_out_scale(tag): +def thin_out_scale(tag) -> bool | int: qs = list( ScalesControl.objects.filter( name=tag, time__lte=timezone.now() - timedelta(hours=12) @@ -112,7 +122,7 @@ def thin_out_scale(tag): ) if len(qs) <= 2: - return + return False i = 0 current_obj = qs[i] latest_obj = qs[-1] @@ -129,9 +139,11 @@ def thin_out_scale(tag): continue first_in_range = rang.first() last_in_range = rang.last() - rang.exclude(time=first_in_range.time).exclude(time=last_in_range.time).delete() + to_delete = rang.exclude(time=first_in_range.time).exclude(time=last_in_range.time) + to_delete.delete() current_obj = last_in_range i += 1 + return len(to_delete) def get_scales_data() -> bool | list: diff --git a/app/entrypoint.sh b/app/entrypoint.sh deleted file mode 100644 index fd8daba..0000000 --- a/app/entrypoint.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/sh - -pip install -r req.txt - -python ./manage.py migrate --no-input -python ./manage.py collectstatic --no-input - -DJANGO_SUPERUSER_PASSWORD=$SUPER_USER_PASSWORD python ./manage.py createsuperuser --username $SUPER_USER_NAME --email $SUPER_USER_EMAIL --noinput - -gunicorn ./repcofkk.wsgi:application --bind 0.0.0.0:8000 - diff --git a/app/repcofkk/settings.py b/app/repcofkk/settings.py index 1c839a8..2418d21 100644 --- a/app/repcofkk/settings.py +++ b/app/repcofkk/settings.py @@ -95,7 +95,7 @@ LOGIN_REDIRECT_URL = "/" logging.set() -APP_VERSION = "0.3" +APP_VERSION = "0.4" from .app_settings import * diff --git a/docker-compose-dev.yml b/docker-compose-dev.yml new file mode 100644 index 0000000..8360431 --- /dev/null +++ b/docker-compose-dev.yml @@ -0,0 +1,67 @@ +version: '3.9' + +services: + celery: + build: ./app + command: celery -A repcofkk worker -l info + volumes: + - code_volume:/home/app/web/ + env_file: + - .env + depends_on: + redis: + condition: service_started + + celery-beat: + build: ./app + command: celery -A repcofkk beat -l info + volumes: + - code_volume:/home/app/web/ + env_file: + - .env + depends_on: + redis: + condition: service_started + + redis: + container_name: redis + image: redis + restart: always + volumes: + - ./redis:/data + ports: + - "6379:6379" + healthcheck: + test: [ "CMD-SHELL", "redis-cli ping | grep PONG" ] + interval: 1s + timeout: 3s + retries: 5 + + postgres: + image: postgres:12 + volumes: + - postgres_data:/var/lib/postgresql/data/ + env_file: + - .env + ports: + - '5432:5432' + healthcheck: + test: [ "CMD-SHELL", "pg_isready -d $${POSTGRES_DB} -U $${POSTGRES_USER}" ] + interval: 10s + timeout: 60s + retries: 3 + start_period: 10s + + flower: + image: mher/flower + ports: + - "5555:5555" + depends_on: + celery: + condition: service_started + environment: + - CELERY_BROKER_URL=redis://redis:6379/0 +volumes: + postgres_data: + static_volume: + code_volume: \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 7bedd7a..2ce6369 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -24,13 +24,23 @@ services: nginx: build: ./nginx + volumes: + - static_volume:/home/app/web/static/ + - /etc/letsencrypt/:/etc/letsencrypt/ + - /certbot/www:/var/www/certbot + - ./nginx/options-ssl-nginx.conf:/etc/letsencrypt/options-ssl-nginx.conf ports: - - '8080:80' + - "80:80" + - "443:443" depends_on: web: condition: service_started + certbot: + image: certbot/certbot volumes: - - static_volume:/home/app/web/static/ + - ./certbot/conf:/etc/letsencrypt + - ./certbot/www:/var/www/certbot + entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'" celery: build: ./app @@ -99,4 +109,4 @@ services: volumes: postgres_data: static_volume: - code_volume: \ No newline at end of file + code_volume: diff --git a/nginx/nginx.conf b/nginx/nginx.conf index 7e430b3..9cde24b 100644 --- a/nginx/nginx.conf +++ b/nginx/nginx.conf @@ -3,8 +3,26 @@ upstream gunicorn { } server { - listen 80; + server_name rp.cofkk.ru; + + location /.well-known/acme-challenge/ { + root /var/www/certbot; + } + + location / { + return 301 https://$host$request_uri; + } +} + +server { + listen 443 ssl; + server_name rp.cofkk.ru; + + ssl_certificate /etc/letsencrypt/live/rp.cofkk.ru/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/rp.cofkk.ru/privkey.pem; + include /etc/letsencrypt/options-ssl-nginx.conf; + ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; location / { proxy_pass http://gunicorn; @@ -16,5 +34,4 @@ server { location /static/ { alias /home/app/web/static/; } - } \ No newline at end of file diff --git a/nginx/options-ssl-nginx.conf b/nginx/options-ssl-nginx.conf new file mode 100644 index 0000000..bdc14f1 --- /dev/null +++ b/nginx/options-ssl-nginx.conf @@ -0,0 +1,3 @@ +ssl_protocols TLSv1.2 TLSv1.3; +ssl_prefer_server_ciphers on; +ssl_ciphers 'ECDHE-ECDSA:AES128-GCM-SHA256:ECDHE-RSA:AES256-GCM-SHA384'; \ No newline at end of file