доработки диспетчера очереди, теперь мы используем запуски потоков нового воркера для предотвращения зависания коннекта к базе, также расширен класс респонса задания

This commit is contained in:
rsgrinko committed 2022-10-26 16:16:34 +03:00
1 parent 0ad5080edc
commit 1dfd2ebeef
6 files changed
+265 -78

No files matched your search

+2
View File
@@ -96,6 +96,7 @@
<th>ID задания</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>
@@ -121,6 +122,7 @@
<td><?= $task['task_id']; ?></td> <td><?= $task['task_id']; ?></td>
<td><?= $task['execution_time']; ?></td> <td><?= $task['execution_time']; ?></td>
<td><?= $task['attempts']; ?></td> <td><?= $task['attempts']; ?></td>
<td><?= $task['attempts_limit']; ?></td>
<td><?= $task['class']; ?></td> <td><?= $task['class']; ?></td>
<td><?= $task['method']; ?></td> <td><?= $task['method']; ?></td>
<td><?= $task['params']; ?></td> <td><?= $task['params']; ?></td>
+1 -1
View File
@@ -191,7 +191,7 @@
} }
} }
if($i < 1 ) { if($i < 1 ) {
throw new CoreException('Новых шуток не найдено'); throw new CoreException('Новых данных не найдено');
} }
return ['method' => __FUNCTION__, 'status' => 'OK', 'message' => 'Добавлено ' . $i . ' шуток из ' . count($arJokes)]; return ['method' => __FUNCTION__, 'status' => 'OK', 'message' => 'Добавлено ' . $i . ' шуток из ' . count($arJokes)];
+102 -41
View File
@@ -30,77 +30,77 @@
/** /**
* Таблица заданий * Таблица заданий
*/ */
const TABLE = 'threads'; public const TABLE = 'threads';
/** /**
* Таблица истории заданий * Таблица истории заданий
*/ */
const TABLE_HISTORY = 'threads_history'; public const TABLE_HISTORY = 'threads_history';
/** /**
* Формат даты и времени * Формат даты и времени
*/ */
const DATETIME_FORMAT = 'Y-m-d H:i:s'; public const DATETIME_FORMAT = 'Y-m-d H:i:s';
/** /**
* Имя файла логов * Имя файла логов
*/ */
const LOG_FILE = 'MQ.log'; public const LOG_FILE = 'MQ.log';
/** /**
* Статус успешно выполненного задания * Статус успешно выполненного задания
*/ */
const STATUS_OK = 'OK'; public const STATUS_OK = 'OK';
/** /**
* Статус неудачно выполненного задания * Статус неудачно выполненного задания
*/ */
const STATUS_ERROR = 'ERROR'; public const STATUS_ERROR = 'ERROR';
/** /**
* Статус занято * Статус занято
*/ */
const STATUS_BUSY = 'BUSY'; public const STATUS_BUSY = 'BUSY';
/** /**
* Значение ДА * Значение ДА
*/ */
const VALUE_Y = 'Y'; public const VALUE_Y = 'Y';
/** /**
* Значение НЕТ * Значение НЕТ
*/ */
const VALUE_N = 'N'; public const VALUE_N = 'N';
/** /**
* Количество задач для обработки * Количество задач для обработки
*/ */
const EXECUTION_TASKS_LIMIT = 100; public const EXECUTION_TASKS_LIMIT = 100;
/** /**
* Лимит количества запущенных воркеров * Лимит количества запущенных воркеров
*/ */
const WORKERS_LIMIT = 2; public const WORKERS_LIMIT = 2;
/** /**
* @var DB|null $DB Объект базы * @var object|DB|null $DB Объект базы
*/ */
private $DB = null; private $DB = null;
/** /**
* Приоритет по умолчанию * Приоритет по умолчанию
*/ */
const DEFAULT_PRIORITY = 5; public const DEFAULT_PRIORITY = 5;
/** /**
* Попыток выполнения по умолчанию * Попыток выполнения по умолчанию
*/ */
const DEFAULT_ATTEMPTS = 1; public const DEFAULT_ATTEMPTS = 1;
/** /**
* Время, после которого задача считается повисшей (5 минут) * Время, после которого задача считается повисшей (5 минут)
*/ */
const STUCK_TIME = 60 * 10; public const STUCK_TIME = 60 * 10;
/** /**
* @var null $priority Приоритет задания * @var null $priority Приоритет задания
@@ -115,12 +115,12 @@
/** /**
* @var bool $useCheckDuplicates Флаг проверки задания на дубликат * @var bool $useCheckDuplicates Флаг проверки задания на дубликат
*/ */
private $useCheckDuplicates = true; public $useCheckDuplicates = true;
/** /**
* @var null $attempts Количество попыток выполнения задания * @var null $attempts Количество попыток выполнения задания
*/ */
private $attempts = self::DEFAULT_ATTEMPTS; protected $attempts = self::DEFAULT_ATTEMPTS;
/** /**
* @var null $workerId Идентификатор воркера * @var null $workerId Идентификатор воркера
@@ -130,10 +130,10 @@
/** /**
* Конструктор * Конструктор
*/ */
public function __construct() public function __construct(?string $workerId = null)
{ {
$this->DB = DB::getInstance(); $this->DB = DB::getInstance();
$this->workerId = 'MQ_' . uniqid(); $this->workerId = $workerId ?: explode('.', uniqid('MQ_', true))[0];
} }
/** /**
@@ -203,9 +203,9 @@
/** /**
* Преобразование из JSON строки в данные * Преобразование из JSON строки в данные
* *
* @param string $json Данные * @param string|null $json Данные
* *
* @return string * @return array
*/ */
private function convertFromJson(?string $json): array private function convertFromJson(?string $json): array
{ {
@@ -216,9 +216,10 @@
} }
/** /**
* Выборка активных невыполненных заданий из очереди * Выборка количества активных невыполненных заданий из очереди
* *
* @return int * @return int Количество заданий
* @throws CoreException
*/ */
private function getActiveTasksCount(): int private function getActiveTasksCount(): int
{ {
@@ -273,7 +274,7 @@
$this->getWorkerId() . ': Взято в работу заданий ' . count($arTaskIds), $this->getWorkerId() . ': Взято в работу заданий ' . count($arTaskIds),
self::LOG_FILE, self::LOG_FILE,
['added' => count($arTaskIds), 'before' => $countTasks], ['added' => count($arTaskIds), 'before' => $countTasks],
LOG_DEBUG, LOG_INFO,
null, null,
false false
); );
@@ -286,7 +287,8 @@
/** /**
* Запуск диспетчера очереди * Запуск диспетчера очереди
* *
* @return void * @param bool $childProcess Флаг дочернего процесса
*
* @throws CoreException * @throws CoreException
*/ */
public function run(bool $childProcess = false): void public function run(bool $childProcess = false): void
@@ -296,7 +298,7 @@
$this->getWorkerId() . ': Запущен новый воркер ' . $this->getCountWorkers() . '/' . self::WORKERS_LIMIT, $this->getWorkerId() . ': Запущен новый воркер ' . $this->getCountWorkers() . '/' . self::WORKERS_LIMIT,
self::LOG_FILE, self::LOG_FILE,
[], [],
LOG_DEBUG, LOG_INFO,
null, null,
false false
); );
@@ -313,7 +315,7 @@
$this->getWorkerId() . ': Достигнуто максимальное количество воркеров. Работает ' . $this->getCountWorkers() . '/' . self::WORKERS_LIMIT, $this->getWorkerId() . ': Достигнуто максимальное количество воркеров. Работает ' . $this->getCountWorkers() . '/' . self::WORKERS_LIMIT,
self::LOG_FILE, self::LOG_FILE,
[], [],
LOG_DEBUG, LOG_NOTICE,
null, null,
false false
); );
@@ -328,7 +330,7 @@
$this->getWorkerId() . ': Запущено выполнение заданий из очереди', $this->getWorkerId() . ': Запущено выполнение заданий из очереди',
self::LOG_FILE, self::LOG_FILE,
['count' => count($arTasks)], ['count' => count($arTasks)],
LOG_DEBUG, LOG_INFO,
null, null,
false false
); );
@@ -342,14 +344,15 @@
$this->getWorkerId() . ': Нечего выполнять - завершаем работу', $this->getWorkerId() . ': Нечего выполнять - завершаем работу',
self::LOG_FILE, self::LOG_FILE,
[], [],
LOG_DEBUG, LOG_INFO,
null, null,
false false
); );
} }
return; return;
} }
//$this->run(true); $this->runNewWorker($this->getWorkerId()); // Запускаем дочерний воркер с тем же идентификатором
//$this->run(true); // Продолжаем выполнение заданий текущим воркером
} }
/** /**
@@ -454,9 +457,14 @@
$this->priority = null; $this->priority = null;
$response = new MQResponse(); $response = new MQResponse();
$response->setTaskId(0)->setStatus(self::STATUS_OK)->setParams(self::convertFromJson($params))->setParamsJson($params)->setResponse( $response->setTaskId(0)
$count . ' tasks were created' ->setStatus(self::STATUS_OK)
); ->setParams($this->convertFromJson($params))
->setParamsJson($params)
->setExecutionTime(0)
->setAttempts(0)
->setAttemptsLimit($this->attempts)
->setResponse($count . ' tasks were created');
return $response; return $response;
} }
@@ -519,9 +527,16 @@
} }
$response = new MQResponse(); $response = new MQResponse();
$response->setTaskId($taskId)->setStatus(self::STATUS_OK)->setParams(self::convertFromJson($params))->setParamsJson($params)->setResponse( $response->setTaskId($taskId)
'Task ' . $taskId . ' created' ->setStatus(self::STATUS_OK)
); ->setClass($class)
->setMethod($method)
->setParams($this->convertFromJson($params))
->setParamsJson($params)
->setExecutionTime(0)
->setAttempts(0)
->setAttemptsLimit($this->runNow ? 1 : $this->attempts)
->setResponse('Task ' . $taskId . ' created');
return $response; return $response;
@@ -578,7 +593,7 @@
$this->getWorkerId() . ': Задание ' . $taskId . ' взято в работу', $this->getWorkerId() . ': Задание ' . $taskId . ' взято в работу',
self::LOG_FILE, self::LOG_FILE,
['taskId' => $taskId], ['taskId' => $taskId],
LOG_DEBUG, LOG_INFO,
null, null,
false false
); );
@@ -605,7 +620,7 @@
return $response; return $response;
} }
$response->setParamsJson($arTask['params']); $response->setParamsJson($arTask['params'])->setClass($arTask['class'])->setMethod($arTask['method']);
$arTask['params'] = $this->convertFromJson($arTask['params']); $arTask['params'] = $this->convertFromJson($arTask['params']);
$response->setParams($arTask['params']); $response->setParams($arTask['params']);
@@ -618,7 +633,7 @@
$this->getWorkerId() . ': Задание ' . $taskId . ' уже выполняется другим воркером', $this->getWorkerId() . ': Задание ' . $taskId . ' уже выполняется другим воркером',
self::LOG_FILE, self::LOG_FILE,
['taskId' => $taskId], ['taskId' => $taskId],
LOG_DEBUG, LOG_INFO,
null, null,
false false
); );
@@ -672,7 +687,11 @@
'response' => addslashes($this->convertToJson($result)), 'response' => addslashes($this->convertToJson($result)),
] ]
); );
$response->setStatus(self::STATUS_OK)->setExecutionTime($endTime)->setResponse($this->convertToJson($result)); $response->setStatus(self::STATUS_OK)
->setExecutionTime($endTime)
->setResponse($this->convertToJson($result))
->setAttempts($arTask['attempts'])
->setAttemptsLimit($arTask['attempts_limit']);
$this->saveTaskToHistory($taskId); $this->saveTaskToHistory($taskId);
if (USE_LOG) { if (USE_LOG) {
@@ -680,7 +699,7 @@
$this->getWorkerId() . ': Выполнено задание с ID ' . $taskId . ', попытка ' . $arTask['attempts'] . ' из ' . $arTask['attempts_limit'], $this->getWorkerId() . ': Выполнено задание с ID ' . $taskId . ', попытка ' . $arTask['attempts'] . ' из ' . $arTask['attempts_limit'],
self::LOG_FILE, self::LOG_FILE,
['response' => $this->convertToJson($result)], ['response' => $this->convertToJson($result)],
LOG_DEBUG, LOG_INFO,
null, null,
false false
); );
@@ -739,6 +758,7 @@
'task_id' => $arTask['id'], 'task_id' => $arTask['id'],
'execution_time' => $arTask['execution_time'], 'execution_time' => $arTask['execution_time'],
'attempts' => $arTask['attempts'], 'attempts' => $arTask['attempts'],
'attempts_limit' => $arTask['attempts_limit'],
'date_created' => $arTask['date_created'], 'date_created' => $arTask['date_created'],
'date_updated' => $arTask['date_updated'], 'date_updated' => $arTask['date_updated'],
'class' => addslashes($arTask['class']), 'class' => addslashes($arTask['class']),
@@ -826,6 +846,16 @@
return (int)exec('ps -awx | grep \'threadsWorker.php\' | grep -v \'grep\' | wc -l'); return (int)exec('ps -awx | grep \'threadsWorker.php\' | grep -v \'grep\' | wc -l');
} }
/**
* Запуск нового воркера
*
* @return void
*/
public function runNewWorker(?string $workerId = null)
{
exec('(php -f ' . $_SERVER['DOCUMENT_ROOT'] . '/core/runtime/threadsWorker.php "children" "' . $workerId . '" & ) >> /dev/null 2>&1');
}
/** /**
* Принудительная остановка всех запущенных воркеров * Принудительная остановка всех запущенных воркеров
* *
@@ -902,4 +932,35 @@
} }
} }
} }
/**
* Получение объекта задания
*
* @param int $taskId Идентификатор задания
*
* @return MQResponse
*/
public function getTaskResponse(int $taskId): MQResponse
{
$res = $this->DB->query('SELECT * FROM ' . self::TABLE . ' WHERE id="' . $taskId . '"')[0];
if (empty($res)) {
$res = $this->DB->query('SELECT * FROM ' . self::TABLE_HISTORY . ' WHERE task_id="' . $taskId . '"')[0];
}
if (empty($res)) {
throw new CoreException('Задание с ID ' . $taskId . ' не найдено');
}
//print_r($res);die();
$response = new MQResponse();
$response->setTaskId($taskId)
->setStatus($res['status'])
->setClass($res['class'])
->setMethod($res['method'])
->setParams($this->convertFromJson($res['params']))
->setParamsJson($res['params'])
->setExecutionTime($res['execution_time'])
->setAttempts($res['attempts'])
->setAttemptsLimit($res['attempts_limit'])
->setResponse($res['response']);
return $response;
}
} }
+114 -2
View File
@@ -65,6 +65,26 @@
*/ */
private $executionTime = null; private $executionTime = null;
/**
* @var string|null $class Класс
*/
private $class = null;
/**
* @var string|null $method Метод
*/
private $method = null;
/**
* @var int|null $attempts Количество попыток
*/
private $attempts = null;
/**
* @var int|null $attempts Лимит количество попыток
*/
private $attemptsLimit = null;
/** /**
* @var string|null $response Результат выполнения задания * @var string|null $response Результат выполнения задания
*/ */
@@ -124,6 +144,98 @@
return $this; return $this;
} }
/**
* Получение класса задания
*
* @return ?string
*/
public function getClass(): ?string
{
return $this->class;
}
/**
* Установка класса задания
*
* @param string|null $class Время выполнения
*
* @return $this
*/
public function setClass(?string $class = null): self
{
$this->class = $class;
return $this;
}
/**
* Получение метода задания
*
* @return ?string
*/
public function getMethod(): ?string
{
return $this->method;
}
/**
* Установка метода задания
*
* @param string|null $method Время выполнения
*
* @return $this
*/
public function setMethod(?string $method = null): self
{
$this->method = $method;
return $this;
}
/**
* Получение количества попыток
*
* @return int|null Количество попыток
*/
public function getAttempts(): ?int
{
return $this->attempts;
}
/**
* Установка количества попыток
*
* @param int|null $attempts Количество попыток
*
* @return $this
*/
public function setAttempts(?int $attempts = null): self
{
$this->attempts = $attempts;
return $this;
}
/**
* Получение лимита количества попыток
*
* @return int|null Количество попыток
*/
public function getAttemptsLimit(): ?int
{
return $this->attemptsLimit;
}
/**
* Установка лимита количества попыток
*
* @param int|null $attempts Количество попыток
*
* @return $this
*/
public function setAttemptsLimit(?int $attempts = null): self
{
$this->attemptsLimit = $attempts;
return $this;
}
/** /**
* Получение статуса задания * Получение статуса задания
* *
@@ -167,11 +279,11 @@
/** /**
* Установка текстового кода ответа внешней службы * Установка текстового кода ответа внешней службы
* *
* @param string $status Текстовый код ответа * @param string|null $status Текстовый код ответа
* *
* @return $this * @return $this
*/ */
public function setStatus(string $status): self public function setStatus(?string $status): self
{ {
$status = strtoupper($status); $status = strtoupper($status);
$this->status = $status; $this->status = $status;
+3 -2
View File
@@ -29,9 +29,10 @@
use Core\Helpers\SystemFunctions; use Core\Helpers\SystemFunctions;
use Core\Models\MQ; use Core\Models\MQ;
$isChildrenThread = isset($argv[1]) && $argv[1] === 'children';
$workerId = isset($argv[2]) && !empty($argv[2]) ? $argv[2] : null;
try { try {
(new MQ())->run(); (new MQ($workerId))->run($isChildrenThread);
} catch (Throwable $t) { } catch (Throwable $t) {
SystemFunctions::sendTelegram( SystemFunctions::sendTelegram(
'ThreadsWorker: Произошла ошибка' . PHP_EOL . $t->getMessage() . PHP_EOL . 'File: ' . $t->getFile() . PHP_EOL . 'Line: ' . $t->getLine() 'ThreadsWorker: Произошла ошибка' . PHP_EOL . $t->getMessage() . PHP_EOL . 'File: ' . $t->getFile() . PHP_EOL . 'Line: ' . $t->getLine()
+43 -32
View File
@@ -1,40 +1,51 @@
<?php <?php
function sendRequest(string $method, array $request = []): array $timer1 = $timer2 = 0;
{
$ch = curl_init('https://api.telegram.org/bot1667667369:AAGv5Y1mLTndb1JEzwjzQ1yeelox2NRamR0/' . $method);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$res = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$res = json_decode($res, true);
if (empty($res) || $res['ok'] !== true) {
die($res['description'] . ' | ' . $res['error_code']);
}
return $res;
}
//sendRequest('deleteWebhook'); $varTrue = true;
$arUpdates = sendRequest('getUpdates?offset='); $varFalse = false;
$result = $arUpdates['result'];
if(isset($result['update_id'])) { $count = 100000000;
$result[] = $result;
}
$update_id = '';
/**********************/
$res = []; $start = microtime(true);
foreach ($result as $element) { // Проверка эталона
if(isset($element['message']['from']['id']) && !empty($element['message']['from']['id'])) { for ($i = 0; $i < $count; $i++) {
$res[] = sendRequest( if ($varTrue) {
'sendMessage', // пустота
['chat_id' => $element['message']['from']['id'], 'parse_mode' => 'html', 'text' => 'Ответ бота']
);
} }
} }
$end = microtime(true);
$deltaOne = $end - $start;
print_r($result); /**********************/
$start = microtime(true);
// Проверка инверсии
for ($i = 0; $i < $count; $i++) {
if (!$varFalse) {
// пустота
}
}
$end = microtime(true);
$deltaTwo = $end - $start;
/**********************/
$start = microtime(true);
// Проверка сравнением в булевым
for ($i = 0; $i < $count; $i++) {
if ($varFalse === false) {
// пустота
}
}
$end = microtime(true);
$deltaThree = $end - $start;
/**********************/
?>
<b>Тестирование условий с количеством выполнения <?= $count ?></b><br>
<table border="1px">
<tr style="font-weight: bold"><td>Тестирование</td><td>Время</td></tr>
<tr><td>Эталон</td><td><?= $deltaOne ?></td></tr>
<tr><td>Инверсия</td><td><?= $deltaTwo ?></td></tr>
<tr><td>Сравнение с bool</td><td><?= $deltaThree ?></td></tr>
</table>