-
Notifications
You must be signed in to change notification settings - Fork 0
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
base: main
Are you sure you want to change the base?
Changes from 1 commit
19ad3b5
30c8e92
7e8f5c2
0bbd5e4
f345265
2c2d70c
16dffea
0cda2b3
31472f2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
phpcs.xml | ||
.github | ||
.idea |
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 |
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 |
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" |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
FROM memcached:alpine | ||
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;"] | ||
|
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; | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
vendor/ |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
<?php | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Поправьте все замечания линтера. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Какие конкретно замечания, я их не вижу. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Откройте пулл-реквест в github на последней вкладке - где показываются изменения. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
namespace Ashishak\Balancer\code; | ||
|
||
class Validator | ||
{ | ||
public static function ValidateText(string $postVar): array{ | ||
Check failure on line 7 in balancer/src/code/Validator.php GitHub Actions / phpcs
|
||
$message = []; | ||
//Проверяем строку регуляркой, чтобы не прошла строка )( | ||
if (preg_match("/^\(.*\)/", $postVar)){ | ||
if (preg_match_all("/(\()/u", $postVar, $m)){ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Излишне усложнили. Есть более простое и эффективное решение - простой цикл в котором перебираем символа и увеличиваем счётчик на единицу если видим '(' и уменьшаем если видим ')'. Если во время итерации счётчки стал < 0, лишняя ')'. Если после цикла счётчик != 0 - то лишняя '(' или ')' There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 GitHub Actions / phpcs
Check failure on line 16 in balancer/src/code/Validator.php GitHub Actions / phpcs
Check failure on line 16 in balancer/src/code/Validator.php GitHub Actions / phpcs
|
||
//Если в процессе выполнение понимаем что строка пуста, отдаем 200 код, все ок | ||
if (empty($postVar)){ | ||
$message['code'] = 200; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Задача данного класса - провалидировать строку. Он не должен формировать HTTP ответ. Просто верните отсюда bool. There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
} | ||
|
||
} |
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": {} | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
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> |
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 'Данные записаны в сессию успешно. Перезагрузите страницу.'; | ||
} |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вот здесь не понял, будьте добры подробнее опишите
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Просто используйте в docker-compose секцию image и там укажите вот этот образ.