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

Домашнее задание №4 - Броузерное приложение и балансировщик #1169

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
phpcs.xml
.github
.idea
86 changes: 86 additions & 0 deletions balancer/docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
version: '3'

services:
nginx:
# Если нет секции build, то система будет искать образ в репозиториях
build:
context: ./nginx
dockerfile: Dockerfile
image: balance/nginx # имя будущего образа
container_name: nginx # имя контейнера после запуска
ports:
- "80:80"
volumes:
- ./src/:/data/app.local
networks:
- app-network

php-fpm-01:
build:
context: ./fpm
dockerfile: Dockerfile
image: balance/php
container_name: php-fpm-01
volumes:
- ./src/:/data/app.local
networks:
- app-network

php-fpm-02:
build:
context: ./fpm
dockerfile: Dockerfile
image: balance/php
container_name: php-fpm-02
volumes:
- ./src/:/data/app.local
networks:
- app-network

php-fpm-03:
build:
context: ./fpm
dockerfile: Dockerfile
image: balance/php
container_name: php-fpm-03
volumes:
- ./src/:/data/app.local
networks:
- app-network

php-fpm-04:
build:
context: ./fpm
dockerfile: Dockerfile
image: balance/php
container_name: php-fpm-04
volumes:
- ./src/:/data/app.local
networks:
- app-network

memcache01:
build:
context: ./memcached
dockerfile: Dockerfile
image: balance/memcached
container_name: memcache01
ports:
- '11201:11211'
networks:
- app-network

memcache02:
build:
context: ./memcached
dockerfile: Dockerfile
image: balance/memcached
container_name: memcache02
ports:
- '11202:11211'
networks:
- app-network

networks:
app-network:
driver: bridge
61 changes: 61 additions & 0 deletions balancer/fpm/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
FROM php:8.1.22-fpm-alpine

#RUN docker-php-ext-install sockets

#RUN set -x \
# && addgroup -g 101 -S nginx \
# && adduser -u 101 -D -S -G nginx nginx

ADD https://github.com/mlocati/docker-php-extension-installer/releases/latest/download/install-php-extensions /usr/local/bin/

RUN apk add --no-cache --virtual .build-deps $PHPIZE_DEPS \
&& pecl install uploadprogress \
&& docker-php-ext-enable uploadprogress \
&& apk del .build-deps $PHPIZE_DEPS \
&& chmod uga+x /usr/local/bin/install-php-extensions && sync \
&& install-php-extensions bcmath \
bz2 \
calendar \
# curl \
exif \
# fileinfo \
# ftp \
gd \
gettext \
# imagick \
imap \
intl \
ldap \
# mbstring \
mcrypt \
memcache \
memcached \
# mongodb \
mysqli \
opcache \
# openssl \
# pdo \
pdo_pgsql \
pdo_mysql \
# pgsql \
redis \
soap \
# sodium \
sysvsem \
sysvshm \
xmlrpc \
xsl \
zip \
# && echo -e "\n opcache.enable=1 \n opcache.enable_cli=1 \n opcache.memory_consumption=128 \n opcache.interned_strings_buffer=8 \n opcache.max_accelerated_files=4000 \n opcache.revalidate_freq=60 \n opcache.fast_shutdown=1" >> /usr/local/etc/php/conf.d/docker-php-ext-opcache.ini \
# && echo -e "\n xdebug.remote_enable=1 \n xdebug.remote_host=localhost \n xdebug.remote_port=9000" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
# && echo -e "\n xhprof.output_dir='/var/tmp/xhprof'" >> /usr/local/etc/php/conf.d/docker-php-ext-xhprof.ini \
&& cd ~ \
&& php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" \
&& php -r "copy('https://composer.github.io/installer.sig', 'signature');" \
&& php -r "if (hash_file('SHA384', 'composer-setup.php') === trim(file_get_contents('signature'))) { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" \
&& php composer-setup.php --install-dir=/usr/local/bin --filename=composer \
&& php -r "unlink('composer-setup.php');"

COPY ./php.ini /usr/local/etc/php/conf.d/php-custom.ini

WORKDIR /data/app.local
2 changes: 2 additions & 0 deletions balancer/fpm/php.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
session.save_handler=memcache
session.save_path="tcp://memcache01:11211, tcp://memcache02:11211"
Binary file added balancer/images/Балансировщик.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions balancer/memcached/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
FROM memcached:alpine
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не нужно описывать образ с одним FROM. Просто используйте в docker-compose сам базовый образ memcached:alpine

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот здесь не понял, будьте добры подробнее опишите

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Просто используйте в docker-compose секцию image и там укажите вот этот образ.

12 changes: 12 additions & 0 deletions balancer/nginx/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
FROM nginx:latest

COPY app.local.conf /etc/nginx/conf.d/default.conf

WORKDIR /data

VOLUME /data

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

43 changes: 43 additions & 0 deletions balancer/nginx/app.local.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
upstream php-fpm-backend {
least_conn;
server php-fpm-01:9000 max_fails=3 fail_timeout=30s;
server php-fpm-02:9000 max_fails=3 fail_timeout=30s;
server php-fpm-03:9000 max_fails=3 fail_timeout=30s;
server php-fpm-04:9000 max_fails=3 fail_timeout=30s;
}

server {
# указали 80 порт для соединения
listen 80;

# указали домен для нашего приложения
server_name app.local;

# задаем корневую директорию
root /data/app.local/public;

# старторый файл
index index.php index.html;

# при обращении к статическим файлам логи не нужны, равно как и обращение к fpm
location ~* .(jpg|jpeg|gif|css|png|js|ico|html)$ {
access_log off;
expires max;
}

# помним про единую точку доступа
# все запросы заворачиваются в корневую директорию root на index.php
location / {
try_files $uri $uri/ /index.php;
}

# и наконец правило обращения к php-fpm
location ~* .php$ {
try_files $uri = 404;
fastcgi_split_path_info ^(.+.php)(/.+)$;
fastcgi_pass php-fpm-backend;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
1 change: 1 addition & 0 deletions balancer/src/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
vendor/
44 changes: 44 additions & 0 deletions balancer/src/code/Validator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

Check failure on line 1 in balancer/src/code/Validator.php

View workflow job for this annotation

GitHub Actions / phpcs

Header blocks must be separated by a single blank line
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поправьте все замечания линтера.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Какие конкретно замечания, я их не вижу.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Откройте пулл-реквест в github на последней вкладке - где показываются изменения.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Screenshot 2024-04-04 at 23 36 43

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Замечания линтера так и не поправлены.

Вы их можете посмотреть и на странице https://github.com/otusteamedu/PHP_2023/pull/1169/checks, там есть подсвеченный красным шаг пайплайна, нажмите на него и будет вывод код снифера. Так же вы можете запустить снифер локально.

declare(strict_types=1);

Check failure on line 2 in balancer/src/code/Validator.php

View workflow job for this annotation

GitHub Actions / phpcs

Header blocks must be separated by a single blank line
namespace Ashishak\Balancer\code;

class Validator
{
public static function ValidateText(string $postVar): array{

Check failure on line 7 in balancer/src/code/Validator.php

View workflow job for this annotation

GitHub Actions / phpcs

Method name &quot;Validator::ValidateText&quot; is not in camel caps format

Check failure on line 7 in balancer/src/code/Validator.php

View workflow job for this annotation

GitHub Actions / phpcs

Opening brace should be on a new line
$message = [];
//Проверяем строку регуляркой, чтобы не прошла строка )(
if (preg_match("/^\(.*\)/", $postVar)){

Check failure on line 10 in balancer/src/code/Validator.php

View workflow job for this annotation

GitHub Actions / phpcs

Expected 1 space(s) after closing parenthesis; found 0
if (preg_match_all("/(\()/u", $postVar, $m)){

Check failure on line 11 in balancer/src/code/Validator.php

View workflow job for this annotation

GitHub Actions / phpcs

Expected 1 space(s) after closing parenthesis; found 0
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Излишне усложнили. Есть более простое и эффективное решение - простой цикл в котором перебираем символа и увеличиваем счётчик на единицу если видим '(' и уменьшаем если видим ')'. Если во время итерации счётчки стал < 0, лишняя ')'. Если после цикла счётчик != 0 - то лишняя '(' или ')'

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Согласен, переписал

//количество открытых скобок
$openCount = count($m[1]);

//Удаляем по парам открытые и закрытые скобки
for ($i=1; $i<=$openCount; $i++){

Check failure on line 16 in balancer/src/code/Validator.php

View workflow job for this annotation

GitHub Actions / phpcs

Expected at least 1 space before &quot;=&quot;; 0 found

Check failure on line 16 in balancer/src/code/Validator.php

View workflow job for this annotation

GitHub Actions / phpcs

Expected at least 1 space after &quot;=&quot;; 0 found

Check failure on line 16 in balancer/src/code/Validator.php

View workflow job for this annotation

GitHub Actions / phpcs

Expected at least 1 space before &quot;&lt;=&quot;; 0 found

Check failure on line 16 in balancer/src/code/Validator.php

View workflow job for this annotation

GitHub Actions / phpcs

Expected at least 1 space after &quot;&lt;=&quot;; 0 found
//Если в процессе выполнение понимаем что строка пуста, отдаем 200 код, все ок
if (empty($postVar)){
$message['code'] = 200;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Задача данного класса - провалидировать строку. Он не должен формировать HTTP ответ. Просто верните отсюда bool.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Согласен поправил

$message['request'] = "Строка корректна!";
return $message;
} else {
$postVar = str_replace('()', '', $postVar);
}

}
//После прохождения цикла делаем контрольную проверку
if(!empty($postVar)){
$message['code'] = '400';
$message['request'] = "В строке выявлены ОШИБКИ!!!";
} else{
$message['code'] = 200;
$message['request'] = "Строка корректна!";
}
}
} else {
$message['code'] = '400';
$message['request'] = "В строке выявлены ОШИБКИ!!!";
}

return $message;
}

}
17 changes: 17 additions & 0 deletions balancer/src/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "ashishak/balancer",
"type": "project",
"autoload": {
"psr-4": {
"ashishak\\balancer\\": "src/"
}
},
"authors": [
{
"name": "Anton Shishak",
"email": "[email protected]"
}
],

"require": {}
}
18 changes: 18 additions & 0 deletions balancer/src/composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

61 changes: 61 additions & 0 deletions balancer/src/public/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php
require __DIR__ ."/../code/Validator.php";

if (isset($_POST['validator'])){
if (!empty($_POST['validator'])){
$result = \Ashishak\Balancer\code\Validator::ValidateText($_POST['validator']);
$message = '"'.$_POST['validator'].'" - '.$result['request'];
http_response_code($result['code']);
} else {
$message = 'Ошибка - строка пуста!';
http_response_code(400);
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<title>Hello, world!</title>
</head>
<body>
<div class="col-sm-12">
<div class="col-sm-5">
<h2>Валидатор скобочек</h2>
<form action="index.php" method="post">
<div class="form-group">
<input type="text" class="form-control" name="validator" id="validator" aria-describedby="emailHelp" placeholder="Введите текст">
<small id="emailHelp" class="form-text text-muted">Валидатор проверяет строку со скобочками</small>
</div>
<button type="submit" class="btn btn-primary">Проверить</button>
</form>
</div>

<div class="col-sm-5">
<h2>Результат проверки:</h2>
<div>
<?php if (!empty($message) && http_response_code() == 200) {?>
<div class="alert alert-success" role="alert">
<?php echo $message;?>
</div>
<?php } else if(!empty($message) && http_response_code() == 400) {?>
<div class="alert alert-danger" role="alert">
<?php echo $message;?>
</div>
<?php } ?>
</div>
</div>
</div>

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
16 changes: 16 additions & 0 deletions balancer/src/public/memcached.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

session_start();

echo "Контейнер nginx: {$_SERVER['HOSTNAME']}<br><br>";

echo 'ID Сессии: ' . session_id() . '<br><br>';

echo '<hr><br><br>Проверка Сессии в Memcached:<br><br>';

if ($_SESSION['var']) {
echo "Данные из сессии: " . $_SESSION['var'];
} else {
$_SESSION['var'] = 'Эти данные записали, а теперь достали из сессии';
echo 'Данные записаны в сессию успешно. Перезагрузите страницу.';
}
Loading