diff --git a/ismailov_rovshan_lab_2/.gitignore b/ismailov_rovshan_lab_2/.gitignore new file mode 100644 index 0000000..645eb4a --- /dev/null +++ b/ismailov_rovshan_lab_2/.gitignore @@ -0,0 +1,5 @@ +data/ +result/ +result_first/ +result_second/ +datagen.py \ No newline at end of file diff --git a/ismailov_rovshan_lab_2/README.md b/ismailov_rovshan_lab_2/README.md new file mode 100644 index 0000000..b6a197a --- /dev/null +++ b/ismailov_rovshan_lab_2/README.md @@ -0,0 +1,43 @@ +# Лабораторная работа №2 +## Описание + +Этот проект предоставляет 2 контейнера с простыми python-скриптами такими, что результат первого является исходными данными для второго. +### 1. Варианты + +Для обеих программ был выбран вариант 1. + +Вариант первой программы: **1**. Ищет в каталоге /var/data файл с наибольшим количеством строк и перекладывает его в /var/result/data.txt. + +Вариант второй программы: **1**. Ищет набольшее число из файла /var/data/data.txt и сохраняет его вторую степень в /var/result/result.txt. + +## Структура Dockerfile + +Два Dockerfile имеют схожую структуру: +`FROM python:3.12` +`WORKDIR /app` +`COPY main.py .` +`VOLUME ["/var/data"]` +`VOLUME ["/var/result"]` +`CMD ["python", "main.py"]` + +## 3. Docker Compose +`services:` + `first:` + `build: ./worker_1/` + + `volumes:` + `- ./data:/var/data` + `- ./result_first:/var/result` + `second:` + `build: ./worker_2/` + `depends_on:` + `- first` + `volumes:` + `- ./result_first:/var/data` + `- ./result_second:/var/result` + +## 4. Запуск +Для запуска использовать команду `docker compose up --build`  +Итог работы первой программы будет в папке `result_first`, а второй - в `result_second`. + +## Ссылка на видео: https://cloud.mail.ru/public/47de/JTUYTSUM2 \ No newline at end of file diff --git a/ismailov_rovshan_lab_2/docker-compose.yml b/ismailov_rovshan_lab_2/docker-compose.yml new file mode 100644 index 0000000..8f19c73 --- /dev/null +++ b/ismailov_rovshan_lab_2/docker-compose.yml @@ -0,0 +1,14 @@ +services: + first: + build: ./worker_1/ + + volumes: + - ./data:/var/data + - ./result_first:/var/result + second: + build: ./worker_2/ + depends_on: + - first + volumes: + - ./result_first:/var/data + - ./result_second:/var/result \ No newline at end of file diff --git a/ismailov_rovshan_lab_2/worker_1/Dockerfile b/ismailov_rovshan_lab_2/worker_1/Dockerfile new file mode 100644 index 0000000..1e72042 --- /dev/null +++ b/ismailov_rovshan_lab_2/worker_1/Dockerfile @@ -0,0 +1,6 @@ +FROM python:3.12 +WORKDIR /app +COPY main.py . +VOLUME ["/var/data"] +VOLUME ["/var/result"] +CMD ["python", "main.py"] \ No newline at end of file diff --git a/ismailov_rovshan_lab_2/worker_1/main.py b/ismailov_rovshan_lab_2/worker_1/main.py new file mode 100644 index 0000000..541e333 --- /dev/null +++ b/ismailov_rovshan_lab_2/worker_1/main.py @@ -0,0 +1,68 @@ +import os +import random + +CATALOG_PATH = "/var/data" +RESULT_FILE = "/var/result/data.txt" + +def find_file_with_most_lines(directory): + file_with_most_lines = None + max_lines = 0 + + for root, _, files in os.walk(directory): + for file in files: + filepath = os.path.join(root, file) + try: + with open(filepath, 'r', encoding='utf-8') as f: + line_count = sum(1 for _ in f) + + if line_count > max_lines: + max_lines = line_count + file_with_most_lines = (filepath, line_count) + + except (OSError, UnicodeDecodeError) as e: + print(f"Ошибка при обработке файла '{filepath}': {e}") + + return file_with_most_lines + + +def copy_file(first, second): + try: + with open(second, "wb") as f_second, open(first, "rb") as f_first: + while chunk := f_first.read(4096): + f_second.write(chunk) + + print(f"Файл '{first}' успешно скопирован в '{second}'.") + + except Exception as e: + print(f"Ошибка при копировании файла '{first}': {e}") + + +def main(): + file_with_most_lines = find_file_with_most_lines(CATALOG_PATH) + + if file_with_most_lines: + first_path, _ = file_with_most_lines + second_path = RESULT_FILE + + copy_file(first_path, second_path) + + else: + print("Файлы не найдены") + +def generate_random_numbers(filename, count): + with open(filename, "w") as f: + for _ in range(count): + num = random.randint(0, 1000) + f.write(str(num) + "\n") + print(f"Числа записаны в '{filename}'.") + + +if __name__ == "__main__": + generate_random_numbers("/var/data/data1.txt", 25) + generate_random_numbers("/var/data/data2.txt", 30) + generate_random_numbers("/var/data/data3.txt", 27) + generate_random_numbers("/var/data/data4.txt", 12) + generate_random_numbers("/var/data/data5.txt", 19) + print("Файлы сгенерированы") + + main() \ No newline at end of file diff --git a/ismailov_rovshan_lab_2/worker_2/Dockerfile b/ismailov_rovshan_lab_2/worker_2/Dockerfile new file mode 100644 index 0000000..1e72042 --- /dev/null +++ b/ismailov_rovshan_lab_2/worker_2/Dockerfile @@ -0,0 +1,6 @@ +FROM python:3.12 +WORKDIR /app +COPY main.py . +VOLUME ["/var/data"] +VOLUME ["/var/result"] +CMD ["python", "main.py"] \ No newline at end of file diff --git a/ismailov_rovshan_lab_2/worker_2/main.py b/ismailov_rovshan_lab_2/worker_2/main.py new file mode 100644 index 0000000..0acd2b5 --- /dev/null +++ b/ismailov_rovshan_lab_2/worker_2/main.py @@ -0,0 +1,49 @@ +DATA_FILE = "/var/data/data.txt" +RESULT_FILE = "/var/result/result.txt" + +def find_biggest_number(data_file): + try: + with open(data_file, "r") as f: + numbers = [int(line.strip()) for line in f.readlines()] + + biggest_num = max(numbers) + return biggest_num + + except ValueError as e: + print(f"Ошибка преобразования строки: {e}") + + except Exception as e: + print(f"Ошибка чтения файла '{data_file}': {e}") + + return None + + +def square_number(num): + return num**2 + + +def write_result(result_file, result): + try: + with open(result_file, "w") as f: + f.write(str(result)) + + print(f"Результат '{result}' успешно передан в '{result_file}'.") + + except Exception as e: + print(f"Ошибка фиксации результата в файл '{result_file}': {e}") + + +def main(): + biggest_num = find_biggest_number(DATA_FILE) + + if biggest_num is not None: + result = square_number(biggest_num) + + write_result(RESULT_FILE, result) + print(result) + + else: + print("В файле нет чисел") + +if __name__ == "__main__": + main() \ No newline at end of file