Добавлен метод поискового робота для нагрузочного тестирования очереди
мелкие правки кода добавлена константа признака полной загрузки ядра системы
This commit is contained in:
1 parent
7b0dd9e581
commit
e8e62abf1b
7 files changed
+157
-110
No files matched your search
@@ -293,13 +293,6 @@
|
||||
try {
|
||||
$stmt = $this->db->query($sql);
|
||||
} catch (\Throwable $t) {
|
||||
SystemFunctions::sendAlarm('DataBase',
|
||||
'<b><u>' . date('d.m.Y H:i:s') . '</u></b>' . PHP_EOL
|
||||
. '</b><b>SQL ERROR:</b> ' . PHP_EOL
|
||||
. $this->db->errorInfo()[2] . PHP_EOL
|
||||
. '<b>QUERY:</b> ' . PHP_EOL
|
||||
. $sql
|
||||
);
|
||||
if(SystemConfig::getValue('DEBUG')) {
|
||||
throw new CoreException(
|
||||
'В SQL запросе произошла ошибка: ' . $this->db->errorInfo()[2]
|
||||
|
||||
@@ -25,6 +25,9 @@
|
||||
use Core\Helpers\Mail;
|
||||
use Core\Helpers\SystemFunctions;
|
||||
use Core\Helpers\Thumbs;
|
||||
use Core\Models\MQ;
|
||||
use PHPUnit\Util\Exception;
|
||||
use Throwable;
|
||||
|
||||
class MQTasks
|
||||
{
|
||||
@@ -496,4 +499,114 @@ DELETE from `jokes` WHERE `jokes`.id not in (SELECT id FROM t_temp);'
|
||||
return $mailObject->send();
|
||||
}
|
||||
|
||||
}
|
||||
/**
|
||||
* Запуск механизма поисковой индексации
|
||||
*
|
||||
* @param string $url Начальный URL
|
||||
*
|
||||
* @return string
|
||||
* @throws CoreException
|
||||
*/
|
||||
public static function spider(string $url): string
|
||||
{
|
||||
$DB = DB::getInstance();
|
||||
|
||||
if (empty($url)) {
|
||||
throw new Exception('Передан пустой url');
|
||||
}
|
||||
|
||||
if ($DB->getItem('spider',['url' => $url]) !== null) {
|
||||
throw new Exception('Данный url ' . $url . ' уже присутствует в базе');
|
||||
}
|
||||
$defaultSocketTimeout = ini_get('default_socket_timeout');
|
||||
ini_set('default_socket_timeout', 5);
|
||||
$data = file_get_contents($url);
|
||||
ini_set('default_socket_timeout', $defaultSocketTimeout);
|
||||
|
||||
if (!is_array($http_response_header)) {
|
||||
$http_response_header = [];
|
||||
}
|
||||
|
||||
$headers = implode("\n", $http_response_header);
|
||||
preg_match_all("/^content-type\s*:\s*(.*)$/mi", $headers, $matchesContentType);
|
||||
$contentType = trim(end($matchesContentType[1]));
|
||||
|
||||
$posTypeText = strpos($contentType, 'text/html');
|
||||
|
||||
if (empty($data)) {
|
||||
throw new Exception('Данных по url ' . $url . ' не найдено');
|
||||
}
|
||||
|
||||
if ($posTypeText === false || $posTypeText !== 0)
|
||||
{
|
||||
throw new Exception('Данный url ' . $url . ' не содержит текстовых данных (' . $contentType . ')');
|
||||
}
|
||||
|
||||
preg_match('~<body.*?>(.*?)</body>~is', $data, $matchesBody, PREG_OFFSET_CAPTURE, 0);
|
||||
|
||||
if (!empty($matchesBody)) {
|
||||
$data = $matchesBody[0][0];
|
||||
}
|
||||
|
||||
$data = preg_replace('/\s?<script[^>]*?>.*?<\/script>\s?/si', ' ', $data);
|
||||
$data = preg_replace('/\s?<style[^>]*?>.*?<\/style>\s?/si', ' ', $data);
|
||||
$data = preg_replace('/\s+/', ' ', $data);
|
||||
$dataText = preg_replace('/<[^>]+>/', '', $data);
|
||||
|
||||
try {
|
||||
$DB->addItem(
|
||||
'spider',
|
||||
[
|
||||
'url' => $url,
|
||||
'text' => $dataText,
|
||||
]
|
||||
);
|
||||
} catch (Throwable $t) {
|
||||
echo $t->getMessage();
|
||||
|
||||
}
|
||||
|
||||
preg_match_all('/href=["\']?([^"\'>]+)["\']?/m', $data, $matches, PREG_SET_ORDER, 0);
|
||||
|
||||
$counter = 0;
|
||||
$counterBreak = 0;
|
||||
foreach ($matches as $match) {
|
||||
[$href, $link, $name] = $match;
|
||||
$link = trim($link);
|
||||
|
||||
$posHttp = strpos($link, 'http://');
|
||||
$posHttps = strpos($link, 'https://');
|
||||
$posSlashes = strpos($link, '//');
|
||||
$posLocal = strpos($link, '#');
|
||||
|
||||
if ($posHttp === false && $posHttps === false && $posSlashes === false) {
|
||||
$parsedData = parse_url($url);
|
||||
$link = $parsedData['scheme'] . '://' . $parsedData['host'] . $link;
|
||||
} elseif ($posSlashes === 0) {
|
||||
$link = 'https:' . $url;
|
||||
} elseif ($posLocal === 0) {
|
||||
continue;
|
||||
} elseif ($url === '/') {
|
||||
$parsedData = parse_url($url);
|
||||
$link = $parsedData['scheme'] . '://' . $parsedData['host'] . '/';
|
||||
}
|
||||
|
||||
|
||||
|
||||
if ($DB->getItem('spider',['url' => $link]) !== null) {
|
||||
$counterBreak++;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
(new MQ())->setPriority(5)->setAttempts(1)->createTask('Core\MQTasks', 'spider', [$link]);
|
||||
} catch (Throwable $t) {
|
||||
$counterBreak++;
|
||||
continue;
|
||||
}
|
||||
$counter++;
|
||||
}
|
||||
|
||||
return 'Добавлено ' . $counter . ' заданий, пропущено ' . $counterBreak;
|
||||
}
|
||||
}
|
||||
@@ -55,7 +55,7 @@
|
||||
public const VALUE_N = 'N';
|
||||
|
||||
/** Количество задач для обработки */
|
||||
public const EXECUTION_TASKS_LIMIT = 100;
|
||||
public const EXECUTION_TASKS_LIMIT = 5;
|
||||
|
||||
/** Лимит количества запущенных воркеров */
|
||||
public const WORKERS_LIMIT = 1;
|
||||
@@ -251,16 +251,6 @@
|
||||
*/
|
||||
public function run(bool $childProcess = false): void
|
||||
{
|
||||
/*if (!$childProcess) {
|
||||
Log::logToFile(
|
||||
$this->getWorkerId() . ': Запущен новый воркер ' . $this->getCountWorkers() . '/' . self::WORKERS_LIMIT,
|
||||
self::LOG_FILE,
|
||||
[],
|
||||
LOG_INFO,
|
||||
null,
|
||||
false
|
||||
);
|
||||
}*/
|
||||
// Поиск и исправление зависших заданий
|
||||
$this->searchAndFixStuckTasks();
|
||||
|
||||
@@ -268,16 +258,6 @@
|
||||
$this->setTasksActiveStatus();
|
||||
|
||||
if ($this->hasMaxWorkers() && !$childProcess) {
|
||||
/*
|
||||
Log::logToFile(
|
||||
$this->getWorkerId() . ': Достигнуто максимальное количество воркеров. Работает ' . $this->getCountWorkers() . '/' . self::WORKERS_LIMIT,
|
||||
self::LOG_FILE,
|
||||
[],
|
||||
LOG_NOTICE,
|
||||
null,
|
||||
false
|
||||
);
|
||||
*/
|
||||
return;
|
||||
}
|
||||
$arTasks = $this->getActiveTasks();
|
||||
@@ -295,16 +275,6 @@
|
||||
$this->execute($task['id']);
|
||||
}
|
||||
} else {
|
||||
/*
|
||||
Log::logToFile(
|
||||
$this->getWorkerId() . ': Нечего выполнять - завершаем работу',
|
||||
self::LOG_FILE,
|
||||
[],
|
||||
LOG_INFO,
|
||||
null,
|
||||
false
|
||||
);
|
||||
*/
|
||||
return;
|
||||
}
|
||||
$this->runNewWorker($this->getWorkerId()); // Запускаем дочерний воркер с тем же идентификатором
|
||||
@@ -563,7 +533,6 @@
|
||||
null,
|
||||
false
|
||||
);
|
||||
//Log::logToSentry($this->getWorkerId() . ': Задания ' . $taskId . ' не найдено', 'DEBUG', ['taskId' => $taskId]);
|
||||
|
||||
return $response;
|
||||
}
|
||||
@@ -678,7 +647,6 @@
|
||||
null,
|
||||
false
|
||||
);
|
||||
//Log::logToSentry($this->getWorkerId() . ': Ошибка выполнения задания с ID ' . $taskId . ', попытка ' . $arTask['attempts'] . ' из ' . $arTask['attempts_limit'], 'DEBUG', ['response' => $t->getMessage()]);
|
||||
}
|
||||
|
||||
return $response;
|
||||
|
||||
@@ -236,7 +236,8 @@
|
||||
*/
|
||||
private function getCurrentPage(): string
|
||||
{
|
||||
return explode('?', $_SERVER['REQUEST_URI'])[0];
|
||||
$params = explode('?', $_SERVER['REQUEST_URI'] ?? '');
|
||||
return $params[0] ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user