аякс диспетчера очереди, класс для шифрования

This commit is contained in:
rsgrinko committed 2022-07-14 00:17:12 +03:00
1 parent 2aab779005
commit 9d7349867e
12 files changed
+507 -158

No files matched your search

Generated
+1 -1
View File
@@ -34,7 +34,7 @@
<path value="$PROJECT_DIR$/vendor/ralouphie/getallheaders" />
</include_path>
</component>
<component name="PhpProjectSharedConfiguration" php_language_level="8.0">
<component name="PhpProjectSharedConfiguration" php_language_level="7.4">
<option name="suggestChangeDefaultLanguageLevel" value="false" />
</component>
</project>
+175
View File
@@ -0,0 +1,175 @@
<?php
use Core\Models\MQ;
require_once __DIR__ . '/../inc/bootstrap.php';
$result = null;
$MQ = new MQ();
ob_start();
?>
<table class="table table-primary mb30">
<thead>
<tr>
<th></th>
<th>ID</th>
<th>Активен</th>
<th>Выполняется</th>
<th>Приоритет</th>
<th>Время выполнения</th>
<th>Попытки</th>
<th>Лимит попыток</th>
<th>Класс</th>
<th>Метод</th>
<th>Параметры</th>
<th>Статус</th>
<th>Результат</th>
<th>Создан</th>
<th>Обновлен</th>
</tr>
</thead>
<tbody>
<?php
$arTasks = $MQ->getTasks(10, 'priority', 'asc');
foreach ($arTasks as $task) {
?>
<tr class="<?php
if ($task['active'] === MQ::VALUE_Y && $task['in_progress'] === MQ::VALUE_Y && $task['status'] === 'ERROR') {
echo 'alert-warning';
} elseif ($task['active'] === MQ::VALUE_N && $task['status'] === 'ERROR') {
echo 'alert-danger';
} elseif ($task['in_progress'] === MQ::VALUE_Y) {
echo 'alert-success';
} elseif ($task['in_progress'] === MQ::VALUE_N && $task['status'] === 'ERROR') {
echo 'alert-danger';
} elseif ($task['active'] === MQ::VALUE_Y && $task['in_progress'] === MQ::VALUE_N) {
echo 'alert-info';
}
?>">
<td><?= $task['in_progress'] === MQ::VALUE_Y ? '<span class="badge badge-success">RUN</span>' : ''; ?></td>
<td><?= $task['id']; ?></td>
<td><?= $task['active'] === MQ::VALUE_Y ? 'Да' : 'Нет'; ?></td>
<td><?= $task['in_progress'] === MQ::VALUE_Y ? 'Да' : 'Нет'; ?></td>
<td><?= $task['priority']; ?></td>
<td><?= $task['execution_time']; ?></td>
<td><?= $task['attempts']; ?></td>
<td><?= $task['attempts_limit']; ?></td>
<td><?= $task['class']; ?></td>
<td><?= $task['method']; ?></td>
<td><?= $task['params']; ?></td>
<td><?= $task['status']; ?></td>
<td><?= $task['response']; ?></td>
<td><?= $task['date_created']; ?></td>
<td><?= $task['date_updated']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
$result['threads'] = ob_get_clean();
ob_start();
?>
<table class="table table-primary mb30">
<thead>
<tr>
<th>ID</th>
<th>ID задания</th>
<th>Время выполнения</th>
<th>Попыток</th>
<th>Класс</th>
<th>Метод</th>
<th>Параметры</th>
<th>Статус</th>
<th>Результат</th>
<th>Создан</th>
<th>Обновлен</th>
</tr>
</thead>
<tbody>
<?php
$arTasks = $MQ->getTasksHistory(10, 'id', 'desc');
foreach($arTasks as $task) {
?>
<tr class="<?php
if($task['status'] === MQ::STATUS_OK) {
echo 'alert-success';
} elseif($task['status'] === MQ::STATUS_ERROR) {
echo 'alert-danger';
}
?>">
<td><?=$task['id'];?></td>
<td><?=$task['task_id'];?></td>
<td><?=$task['execution_time'];?></td>
<td><?=$task['attempts'];?></td>
<td><?=$task['class'];?></td>
<td><?=$task['method'];?></td>
<td><?=$task['params'];?></td>
<td><?=$task['status'];?></td>
<td><?=$task['response'];?></td>
<td><?=$task['date_created'];?></td>
<td><?=$task['date_updated'];?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
$result['threads_history'] = ob_get_clean();
ob_start();
?>
<table class="table">
<thead>
<tr>
<th>Всего</th>
<th>Воркеров</th>
<th>Активных</th>
<th>Выполняются</th>
<th>С ошибкой</th>
</tr>
</thead>
<tbody>
<tr>
<td><?=$MQ->getCountTasks();?></td>
<td><?=$MQ->getCountWorkers() . ' / ' . MQ::WORKERS_LIMIT;?></td>
<td><?=$MQ->getCountTasks(['active' => 'Y']);?></td>
<td><?=$MQ->getCountTasks(['active' => 'Y', 'in_progress' => 'Y']);?></td>
<td><?=$MQ->getCountTasks(['in_progress' => 'N', 'status' => MQ::STATUS_ERROR]);?></td>
</tr>
</tbody>
</table>
<?php
$result['info_threads'] = ob_get_clean();
ob_start();
?>
<table class="table">
<thead>
<tr>
<th>Всего</th>
<th>Успешных</th>
<th>Неудачных</th>
</tr>
</thead>
<tbody>
<tr>
<td><?=$MQ->getCountTasksHistory();?></td>
<td><?=$MQ->getCountTasksHistory(['status' => MQ::STATUS_OK]);?></td>
<td><?=$MQ->getCountTasksHistory(['status' => MQ::STATUS_ERROR]);?></td>
</tr>
</tbody>
</table>
<?php
$result['info_threads_history'] = ob_get_clean();
ob_start();
?>
<div class="progress">
<div style="width: <?=round(($MQ->getCountWorkers() / MQ::WORKERS_LIMIT)*100, 2);?>%" aria-valuemax="100" aria-valuemin="0" aria-valuenow="40" role="progressbar" class="progress-bar progress-bar-warning">
<span class="sr-only">40% Complete (success)</span>
</div>
</div>
<?php
$result['progress'] = ob_get_clean();
echo json_encode($result, JSON_UNESCAPED_UNICODE);
+9
View File
@@ -24,12 +24,21 @@
<title>Delta - CPanel</title>
<link href="//<?=$_SERVER['SERVER_NAME']; ?>/admin/styles/css/style.default.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="//<?=$_SERVER['SERVER_NAME']; ?>/admin/styles/js/html5shiv.js"></script>
<script src="//<?=$_SERVER['SERVER_NAME']; ?>/admin/styles/js/respond.min.js"></script>
<![endif]-->
<style>
.preloader {
text-align: center;
background: url(//<?=$_SERVER['SERVER_NAME']; ?>/uploads/preloader.gif) no-repeat center;
width: 100%;
height: 70px;
}
</style>
</head>
<body>
+50 -150
View File
@@ -29,29 +29,8 @@
<h4 class="panel-title">Задания в очереди</h4>
<p>Задания, ожидающие выполнения и задания, выполнение которых завершилось ошибкой</p>
</div><!-- panel-heading -->
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>Всего</th>
<th>Воркеров</th>
<th>Активных</th>
<th>Выполняются</th>
<th>С ошибкой</th>
</tr>
</thead>
<tbody>
<tr>
<td><?=$MQ->getCountTasks();?></td>
<td><?=$MQ->getCountWorkers() . ' / ' . MQ::WORKERS_LIMIT;?></td>
<td><?=$MQ->getCountTasks(['active' => 'Y']);?></td>
<td><?=$MQ->getCountTasks(['active' => 'Y', 'in_progress' => 'Y']);?></td>
<td><?=$MQ->getCountTasks(['in_progress' => 'N', 'status' => MQ::STATUS_ERROR]);?></td>
</tr>
</tbody>
</table>
<div class="panel-body" id="info_threads">
<div class="preloader"></div>
</div>
</div><!-- panel -->
@@ -64,26 +43,8 @@
<h4 class="panel-title">Завершенные задания</h4>
<p>Задания, которые были успешно выполнены</p>
</div><!-- panel-heading -->
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>Всего</th>
<th>Успешных</th>
<th>Неудачных</th>
</tr>
</thead>
<tbody>
<tr>
<td><?=$MQ->getCountTasksHistory();?></td>
<td><?=$MQ->getCountTasksHistory(['status' => MQ::STATUS_OK]);?></td>
<td><?=$MQ->getCountTasksHistory(['status' => MQ::STATUS_ERROR]);?></td>
</tr>
</tbody>
</table>
<div class="panel-body" id="info_threads_history">
<div class="preloader"></div>
</div>
</div><!-- panel -->
@@ -93,7 +54,19 @@
</div>
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h4 class="panel-title">Текущая нагрузка на диспетчер очереди</h4>
<p>Чем больше количество активных воркеров - тем больше нагрузка</p>
</div><!-- panel-heading -->
<div class="panel-body" id="progress">
<div class="preloader"></div>
</div>
</div>
</div>
</div>
<!-- table -->
@@ -105,66 +78,8 @@
<p>Список текущих заданий очереди</p>
</div><!-- panel-heading -->
<div class="table-responsive">
<table class="table table-primary mb30">
<thead>
<tr>
<th></th>
<th>ID</th>
<th>Активен</th>
<th>Выполняется</th>
<th>Приоритет</th>
<th>Время выполнения</th>
<th>Попытки</th>
<th>Лимит попыток</th>
<th>Класс</th>
<th>Метод</th>
<th>Параметры</th>
<th>Статус</th>
<th>Результат</th>
<th>Создан</th>
<th>Обновлен</th>
</tr>
</thead>
<tbody>
<?php
$arTasks = $MQ->getTasks(10, 'priority', 'asc');
foreach($arTasks as $task) {
?>
<tr class="<?php
if($task['active'] === MQ::VALUE_Y && $task['in_progress'] === MQ::VALUE_Y&& $task['status'] === 'ERROR') {
echo 'alert-warning';
} elseif($task['active'] === MQ::VALUE_N && $task['status'] === 'ERROR') {
echo 'alert-danger';
} elseif($task['in_progress'] === MQ::VALUE_Y) {
echo 'alert-success';
} elseif($task['in_progress'] === MQ::VALUE_N && $task['status'] === 'ERROR') {
echo 'alert-danger';
} elseif($task['active'] === MQ::VALUE_Y && $task['in_progress'] === MQ::VALUE_N) {
echo 'alert-info';
}
?>">
<td><?=$task['in_progress'] === MQ::VALUE_Y ? '<span class="badge badge-success">RUN</span>' : '';?></td>
<td><?=$task['id'];?></td>
<td><?=$task['active'] === MQ::VALUE_Y ? 'Да' : 'Нет';?></td>
<td><?=$task['in_progress'] === MQ::VALUE_Y ? 'Да' : 'Нет';?></td>
<td><?=$task['priority'];?></td>
<td><?=$task['execution_time'];?></td>
<td><?=$task['attempts'];?></td>
<td><?=$task['attempts_limit'];?></td>
<td><?=$task['class'];?></td>
<td><?=$task['method'];?></td>
<td><?=$task['params'];?></td>
<td><?=$task['status'];?></td>
<td><?=$task['response'];?></td>
<td><?=$task['date_created'];?></td>
<td><?=$task['date_updated'];?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<div class="table-responsive" id="threads_table">
<div class="preloader"></div>
</div><!-- table-responsive -->
</div>
@@ -183,52 +98,8 @@
<p>Список заверщившихся заданий</p>
</div><!-- panel-heading -->
<div class="table-responsive">
<table class="table table-primary mb30">
<thead>
<tr>
<th>ID</th>
<th>ID задания</th>
<th>Время выполнения</th>
<th>Попыток</th>
<th>Класс</th>
<th>Метод</th>
<th>Параметры</th>
<th>Статус</th>
<th>Результат</th>
<th>Создан</th>
<th>Обновлен</th>
</tr>
</thead>
<tbody>
<?php
$arTasks = $MQ->getTasksHistory(10, 'id', 'desc');
foreach($arTasks as $task) {
?>
<tr class="<?php
if($task['status'] === MQ::STATUS_OK) {
echo 'alert-success';
} elseif($task['status'] === MQ::STATUS_ERROR) {
echo 'alert-danger';
}
?>">
<td><?=$task['id'];?></td>
<td><?=$task['task_id'];?></td>
<td><?=$task['execution_time'];?></td>
<td><?=$task['attempts'];?></td>
<td><?=$task['class'];?></td>
<td><?=$task['method'];?></td>
<td><?=$task['params'];?></td>
<td><?=$task['status'];?></td>
<td><?=$task['response'];?></td>
<td><?=$task['date_created'];?></td>
<td><?=$task['date_updated'];?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<div class="table-responsive" id="threads_history_table">
<div class="preloader"></div>
</div><!-- table-responsive -->
</div>
@@ -236,4 +107,33 @@
<!-- end table -->
</div><!-- contentpanel -->
<script>
var isPaused = false;
function update()
{
isPaused = true;
$.ajax({
url: 'ajax/threads.php',
cache: false,
success: function(data){
data = JSON.parse(data);
$('#info_threads').html(data.info_threads);
$('#info_threads_history').html(data.info_threads_history);
$('#progress').html(data.progress);
$('#threads_table').html(data.threads);
$('#threads_history_table').html(data.threads_history);
isPaused = false;
}
});
}
$(document).ready(function(){
update();
setInterval(function () {
if(!isPaused){
update();
}
},500);
});
</script>
<?php require_once __DIR__ . '/inc/footer.php'; ?>
+4 -1
View File
@@ -17,6 +17,9 @@
"require": {
"twig/twig": "^3.0",
"sentry/sdk": "^3.2",
"ext-iconv": "*"
"ext-iconv": "*",
"ext-curl": "*",
"ext-json": "*",
"ext-openssl": "*"
}
}
+5 -1
View File
@@ -20,8 +20,12 @@
if((time() - (int)$cronMyslo) > 600) {
$runMyslo = true;
Cache::set($cacheId, time());
sendTelegram('cron_myslo if if set (' . $cronMyslo . ')');
}
} else {
$runMyslo = true;
sendTelegram('cron_myslo global else (' . $cronMyslo . ')');
Cache::set($cacheId, time());
}
if($runMyslo === true) {
@@ -2,6 +2,161 @@
namespace Core\ExternalServices;
use Core\CoreException;
class Request
{
private $httpStatus = null;
private $httpCode = null;
private $maxRedirects = 2;
private $requestHeaders = [];
/**
* @var false|string
*/
private $responseBody = null;
private $responseHeader = null;
private $timeout = 5;
/**
* @return string|null
*/
public function getResponseBody(): ?string
{
return $this->responseBody;
}
/**
* @return null
*/
public function getResponseHeader()
{
return $this->responseHeader;
}
private $usertAgent = null;
private $requestType = null;
private $url = null;
private $params = [];
private $referer = '';
private $usePostMethod = false;
public function __construct()
{
}
public function setUrl(?string $url): self
{
$this->url = $url;
return $this;
}
public function post(): self
{
$this->usePostMethod = true;
return $this;
}
public function get(): self
{
$this->usePostMethod = true;
return $this;
}
public function setParams(?array $params = null): self
{
$this->params = $params ?: [];
return $this;
}
public function setHeaders(?array $arHeaders = null): self
{
$this->requestHeaders = $arHeaders ?: [];
return $this;
}
public function setTimeout(int $timeout): self
{
$this->timeout = $timeout;
return $this;
}
public function setMaxRedirects(int $redirects): self
{
$this->maxRedirects = $redirects;
return $this;
}
public function setReferer(?string $referer = null): self
{
$this->referer = $referer ?: '';
return $this;
}
public function setUserAgent(?string $userAgent = null): self
{
$this->userAgent = $userAgent ?: '';
return $this;
}
public function getCode(): ?int
{
return $this->httpCode;
}
public function send()
{
$res = $this->sendRequest();
return $res;
}
/**
* @throws CoreException
*/
private function sendRequest(): ?string
{
if (empty($this->url)) {
throw new CoreException('Адрес запроса не задан');
}
if ($this->usePostMethod === true) {
$ch = curl_init($this->url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
} else {
$ch = curl_init($this->url . '?' . http_build_query($this->params));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_REFERER, $this->referer);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($ch, CURLOPT_MAXREDIRS, $this->maxRedirects);
curl_setopt($ch, CURLOPT_USERAGENT, $this->usertAgent);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->requestHeaders);
curl_setopt($ch, CURLOPT_HEADER, 1);
$res = curl_exec($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$this->responseHeader = substr($res, 0, $headerSize);
$this->responseBody = substr($res, $headerSize);
$this->httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $res;
}
}
+99
View File
@@ -0,0 +1,99 @@
<?php
namespace Core\Helpers;
class Crypto
{
/**
* @var string|null $key Ключ шифрования
*/
private $key = null;
/**
* @var string $method Метод шифрования
*/
private $method = 'AES-192-CBC';
/**
* @var string $algorithm Алгоритм
*/
private $algorithm = 'sha256';
/**
* Конструктор
*/
public function __construct()
{
}
/**
* Деструктор
*/
public function __destruct()
{
unset($this->key);
unset($this->method);
}
/**
* Генерация ключа шифрования
*
* @return string Ключ
*/
public static function generateKey(): string
{
return bin2hex(openssl_random_pseudo_bytes(40));
}
/**
* @param string $key
*
* @return Crypto
*/
public function setKey(string $key): self
{
$this->key = $key;
return $this;
}
/**
* Шифрование данных
*
* @param string $string Строка
*
* @return string
*/
public function encode(string $string): string
{
$ivlen = openssl_cipher_iv_length($this->method);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($string, $this->method, $this->key, OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac($this->algorithm, $ciphertext_raw, $this->key, true);
$ciphertext = base64_encode($iv . $hmac . $ciphertext_raw);
return $ciphertext;
}
/**
* Расшифровка данных
*
* @param string $string Зашифрованная строка
*
* @return string|null
*/
public function decode(string $string): ?string
{
$c = base64_decode($string);
$ivlen = openssl_cipher_iv_length($this->method);
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len = 32);
$ciphertext_raw = substr($c, $ivlen + $sha2len);
$plaintext = openssl_decrypt($ciphertext_raw, $this->method, $this->key, OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac($this->algorithm, $ciphertext_raw, $this->key, true);
if (hash_equals($hmac, $calcmac)) {
return $plaintext;
}
return null;
}
}
+4 -2
View File
@@ -259,6 +259,8 @@ DELETE from `jokes` WHERE `jokes`.id not in (SELECT id FROM t_temp);'
if($oldLink !== $link) {
sendTelegram('OLD (' .strlen($oldLink).'): ' . $oldLink . PHP_EOL . 'NEW (' .strlen($link).'): ' . $link);
sendTelegram('Обнаружен новый пост');
$full = file_get_contents($link);
preg_match_all('/<div class="h3 lid"><p>(.*?)<\/p><\/div>/us', $full, $lidArticle);
@@ -286,10 +288,10 @@ DELETE from `jokes` WHERE `jokes`.id not in (SELECT id FROM t_temp);'
$post .= PHP_EOL . '<a href="' . $link . '">Подробнее</a>';
$telegram = new \Core\ExternalServices\TelegramSender(TELEGRAM_BOT_TOKEN);
$telegram->setChat(TELEGRAM_NOTIFICATION_CHANNEL);
$telegram->setChat('-1001789206618');
$res = $telegram->sendPhoto($tmpFile, $post);
@unlink($tmpFile);
Cache::set($cacheId, $link);
Cache::set($cacheId, trim($link));
return $res;
} else {
return 'Обновление не требуется';
+1 -1
View File
@@ -160,7 +160,7 @@
*/
public static function test2(...$params): string
{
sleep(rand(10, 60));
sleep(rand(1, 5));
$result = rand(0, 100);
if (($result % 2) == 0) {
throw new CoreException('Сервер обмена временно недоступен');
+4 -2
View File
@@ -2,5 +2,7 @@
$_SERVER['DOCUMENT_ROOT'] = '/home/rsgrinko/sites/dev.it-stories.ru';
require_once $_SERVER['DOCUMENT_ROOT'] . '/core/bootstrap.php';
use Core\MQTasks;
echo MQTasks::sendJokeToTelegram();
print_r($_REQUEST);
print_r($_SERVER);
/*use Core\MQTasks;
echo MQTasks::sendJokeToTelegram();*/
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB