Compare commits

...

2 Commits

Author SHA1 Message Date
5ff5bf22b1 lab 3 no swagger 2024-10-10 22:53:30 +04:00
f5ec3f1767 lab2 2024-10-10 18:52:01 +04:00
16 changed files with 307 additions and 0 deletions

5
presnyakova_victoria_lab_2/.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
__pycache__/
*.pyc
*.pyo
*.log
.DS_Store

View File

@ -0,0 +1,5 @@
73
5
99
27
1234

View File

@ -0,0 +1,4 @@
8
102
65
23

View File

@ -0,0 +1,4 @@
34
57
92
14

View File

@ -0,0 +1,18 @@
version: '3.8'
services:
worker1:
build:
context: ./worker-1
volumes:
- ./data:/var/data
- ./result:/var/result
worker2:
build:
context: ./worker-2
volumes:
- ./result:/var/result
depends_on:
- worker1

View File

@ -0,0 +1,19 @@
# Вариант 1:
Сервис 1 ищет в каталоге /var/data файл с наибольшим количеством строк и перекладывает его в /var/result/data.txt.
Сервис 2 ищет набольшее число из файла /var/data/data.txt и сохраняет его вторую степень в /var/result/result.txt.
## Выполнение
Созданы Docker-файлы для обоих приложений:
Также создан файл `docker-compose.yml`, в котором выполнены следующие действия:
- Определены два сервиса
- Для каждого сервиса указана рабочая директория.
- Настроено монтирование папок из хостовой системы.
- Описаны зависимости одного сервиса от другого.
## Видео https://drive.google.com/file/d/1pbz-3jQbwZqLBBkdSeJ4FWIvMafsdIqj/view?usp=sharing

View File

@ -0,0 +1,11 @@
# Используем базовый образ с Python
FROM python:3.9-slim
# Устанавливаем рабочую директорию
WORKDIR /app
# Копируем файл с кодом программы в контейнер
COPY worker-1.py .
# Запускаем приложение
CMD ["python", "worker-1.py"]

View File

@ -0,0 +1,38 @@
import os
import shutil
#Ищет в каталоге /var/data файл с наибольшим количеством строк и перекладывает его в /var/result/data.txt.
def find_file_with_most_lines(data_dir):
max_lines = 0
file_with_most_lines = None
# Перебираем файлы в каталоге
for filename in os.listdir(data_dir):
file_path = os.path.join(data_dir, filename)
# Проверяем, что это файл
if os.path.isfile(file_path):
with open(file_path, 'r') as file:
line_count = sum(1 for _ in file)
if line_count > max_lines:
max_lines = line_count
file_with_most_lines = file_path
return file_with_most_lines
def copy_file_to_result(file_path, result_path):
os.makedirs(os.path.dirname(result_path), exist_ok=True)
shutil.copyfile(file_path, result_path)
if __name__ == "__main__":
data_dir = "/var/data"
result_file = "/var/result/data.txt"
file_with_most_lines = find_file_with_most_lines(data_dir)
if file_with_most_lines:
copy_file_to_result(file_with_most_lines, result_file)
print(f"Copied {file_with_most_lines} to {result_file}")
else:
print("No files found.")

View File

@ -0,0 +1,11 @@
# Используем базовый образ с Python
FROM python:3.9-slim
# Устанавливаем рабочую директорию
WORKDIR /app
# Копируем файл с кодом программы в контейнер
COPY worker-2.py .
# Запускаем приложение
CMD ["python", "worker-2.py"]

View File

@ -0,0 +1,13 @@
input_file = "/var/result/data.txt"
output_file = "/var/result/result.txt"
#Ищет набольшее число из файла /var/data/data.txt и сохраняет его вторую степень в /var/result/result.txt.
with open(input_file, "r") as infile:
numbers = [int(line.strip()) for line in infile if line.strip().isdigit()]
if numbers:
max_number = max(numbers)
result = max_number ** 2
with open(output_file, "w") as outfile:
outfile.write(str(result))

View File

@ -0,0 +1,27 @@
version: '3.8'
services:
event_service:
build:
context: /event_service
dockerfile: Dockerfile
depends_on:
- session_service
expose:
- 8081
session_service:
build:
context: /session_service
dockerfile: Dockerfile
expose:
- 8082
nginx:
image: nginx
ports:
- 8086:8086
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
depends_on:
- event_service
- session_service

View File

@ -0,0 +1,11 @@
FROM python:3.9
EXPOSE 8081
RUN pip install Flask requests flasgger
WORKDIR /work
COPY event_service.py ./
CMD ["python", "event_service.py"]

View File

@ -0,0 +1,48 @@
from flask import Flask, jsonify, request, Response
from datetime import datetime
app = Flask(__name__)
events = {0: {'id': 0, 'session': 0, 'info': '{"defects": 1}', 'dt': datetime(2024, 10, 10, 8, 0)},
1: {'id': 1, 'session': 1, 'info': '{"defects": 1}', 'dt': datetime(2024, 10, 10, 8, 5)},
2: {'id': 2, 'session': 0, 'info': '{"defects": 1}', 'dt': datetime(2024, 10, 10, 8, 10)},
3: {'id': 3, 'session': 1, 'info': '{"defects": 1}', 'dt': datetime(2024, 10, 10, 8, 15)}}
@app.route('/', methods=['GET', 'POST'])
def get_all():
if request.method == 'POST':
dto = request.get_json()['dto']
new_id = max(events.keys()) + 1
events[new_id] = {
'id': new_id,
'session': dto['session'],
'info': dto['info'],
'dt': datetime.now()
}
return jsonify(events[new_id])
return jsonify(events)
@app.route('/<int:msg_id>', methods=['GET', 'PUT', 'DELETE'])
def get_by_id(msg_id):
if msg_id not in events.keys():
return Response(status=404)
if request.method == 'PUT':
dto = request.get_json()['dto']
events[msg_id] = {
'session': dto['session'],
'info': dto['info'],
'dt': datetime.now()
}
return events[msg_id]
elif request.method == 'DELETE':
events.pop(msg_id)
return Response(status=200)
return jsonify(events[msg_id])
if __name__ == '__main__':
app.run(host='0.0.0.0', use_reloader=False, port=8081)

View File

@ -0,0 +1,28 @@
events {
worker_connections 1024;
}
http {
server {
listen 8086;
listen [::]:8086;
server_name localhost;
location /event_service/ {
proxy_pass http://event_service:8081/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Prefix $scheme;
}
location /session_service/ {
proxy_pass http://session_service:8082/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Prefix $scheme;
}
}
}

View File

@ -0,0 +1,11 @@
FROM python:3.9
EXPOSE 8082
RUN pip install Flask requests flasgger
WORKDIR /work
COPY session_service.py ./
CMD ["python", "session_service.py"]

View File

@ -0,0 +1,54 @@
from flask import Flask, jsonify, request, Response
from datetime import datetime
app = Flask(__name__)
sessions = {0: {'id': 0, 'info': '{"distance": 1}', 'dt_start': datetime(2024, 10, 10, 8, 0),
'dt_end': datetime(2024, 10, 11, 8, 0)},
1: {'id': 1, 'info': '{"distance": 1}', 'dt_start': datetime(2024, 10, 12, 8, 0),
'dt_end': datetime(2024, 10, 13, 8, 0)},
2: {'id': 2, 'info': '{"distance": 1}', 'dt_start': datetime(2024, 10, 14, 8, 0),
'dt_end': datetime(2024, 10, 15, 8, 0)},
3: {'id': 3, 'info': '{"distance": 1}', 'dt_start': datetime(2024, 10, 16, 8, 0),
'dt_end': datetime(2024, 10, 17, 8, 0)},
}
@app.route('/', methods=['GET', 'POST'])
def get_all():
if request.method == 'POST':
dto = request.get_json()['dto']
new_id = max(sessions.keys()) + 1
sessions[new_id] = {
'id': new_id,
'info': dto['info'],
'dt_start': datetime.now(),
'dt_end': datetime.now() + datetime.timedelta(days=1)
}
return jsonify(sessions[new_id])
return jsonify(sessions)
@app.route('/<int:msg_id>', methods=['GET', 'PUT', 'DELETE'])
def get_by_id(msg_id):
if msg_id not in sessions.keys():
return Response(status=404)
if request.method == 'PUT':
dto = request.get_json()['dto']
sessions[msg_id] = {
'info': dto['info'],
'dt_start': datetime.now(),
'dt_end': datetime.now() + datetime.timedelta(days=1)
}
return sessions[msg_id]
elif request.method == 'DELETE':
sessions.pop(msg_id)
return Response(status=200)
return jsonify(sessions[msg_id])
if __name__ == '__main__':
app.run(host='0.0.0.0', use_reloader=False, port=8082)