From 2ba753e6257374ef01ae173d2ccb4153b0e2f1b7 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Thu, 8 Dec 2022 20:54:23 +0300 Subject: [PATCH] =?UTF-8?q?[+]=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4=20=D0=B8=20=D1=81?= =?UTF-8?q?=D1=82=D1=80=D0=B0=D0=BD=D0=B8=D1=86=D0=B0=20=D0=B4=D0=BB=D1=8F?= =?UTF-8?q?=20=D0=BF=D0=B0=D1=80=D1=81=D0=B8=D0=BD=D0=B3=D0=B0=20=D0=BB?= =?UTF-8?q?=D0=BE=D0=B3=D0=BE=D0=B2=20nginx?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- admin/ajax/threads.php | 12 ++ admin/inc/header.php | 1 + admin/nginx.php | 89 +++++++++++++ admin/threads.php | 15 +++ core/lib/Core/Helpers/Pagination.class.php | 8 +- .../Core/Helpers/SystemFunctions.class.php | 106 +++++++++++++++ core/lib/Core/MQTasks.class.php | 8 ++ test2.php | 124 +++--------------- 8 files changed, 250 insertions(+), 113 deletions(-) create mode 100644 admin/nginx.php diff --git a/admin/ajax/threads.php b/admin/ajax/threads.php index 87ed374..a9ea80f 100644 --- a/admin/ajax/threads.php +++ b/admin/ajax/threads.php @@ -20,6 +20,7 @@ */ use Core\Models\MQ; + use Core\Helpers\SystemFunctions; require_once __DIR__ . '/../inc/bootstrap.php'; $result = null; @@ -194,4 +195,15 @@ +
+
+ 40% Complete (success) +
+
+ Управление хостами
  • Диспетчер очереди
  • Командная PHP строка
  • +
  • Логи nginx
  • Dashboard
  • diff --git a/admin/nginx.php b/admin/nginx.php new file mode 100644 index 0000000..af2b237 --- /dev/null +++ b/admin/nginx.php @@ -0,0 +1,89 @@ + + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + use Core\Helpers\Pagination; + use Core\Helpers\SystemFunctions; + + require_once __DIR__ . '/inc/header.php'; +?> + + +
    + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    IPДатаЗапросКодРазмерURLБраузер
    +
    + +
    +
    + +
    + \ No newline at end of file diff --git a/admin/threads.php b/admin/threads.php index ea22531..8f85243 100644 --- a/admin/threads.php +++ b/admin/threads.php @@ -90,6 +90,20 @@ +
    +
    +
    +
    +

    Использование памяти

    +

    Отношение свободной памяти к использованной

    +
    +
    +
    +
    +
    +
    +
    +
    @@ -156,6 +170,7 @@ $('#info_threads').html(data.info_threads); $('#info_threads_history').html(data.info_threads_history); $('#progress').html(data.progress); + $('#memory').html(data.memory); $('#threads_table').html(data.threads); $('#threads_history_table').html(data.threads_history); diff --git a/core/lib/Core/Helpers/Pagination.class.php b/core/lib/Core/Helpers/Pagination.class.php index 3f26411..ff3f8ed 100644 --- a/core/lib/Core/Helpers/Pagination.class.php +++ b/core/lib/Core/Helpers/Pagination.class.php @@ -52,17 +52,15 @@ */ public static function getLimit(): string { - self::$total_pages = intval((self::$total - 1) / self::$limit) + 1; - if (empty(self::$page) or self::$page < 0) { + self::$total_pages = (int)((self::$total - 1) / self::$limit) + 1; + if (empty(self::$page) || self::$page < 0) { self::$page = 1; } if (self::$page > self::$total_pages) { self::$page = self::$total_pages; } $start = self::$page * self::$limit - self::$limit; - $limit = $start . ', ' . self::$limit; - - return $limit; + return $start . ', ' . self::$limit; } /** diff --git a/core/lib/Core/Helpers/SystemFunctions.class.php b/core/lib/Core/Helpers/SystemFunctions.class.php index 6da516d..9af05bd 100644 --- a/core/lib/Core/Helpers/SystemFunctions.class.php +++ b/core/lib/Core/Helpers/SystemFunctions.class.php @@ -22,6 +22,8 @@ namespace Core\Helpers; + use Core\CoreException; + /** * Класс вспомогательных методов */ @@ -753,4 +755,108 @@ } return $count; } + + /** + * Получение данных об оперативной памяти площадки + * + * @param bool $humanView Флаг человеческого представления данных + * + * @return int[] Данные о памяти + */ + public static function getHostMemoryInfo(bool $humanView = false): array + { + $fh = fopen('/proc/meminfo', 'rb'); + $result = [ + 'total' => 0, + 'free' => 0, + 'swapTotal' => 0, + 'swapFree' => 0, + ]; + while ($line = fgets($fh)) { + if (preg_match('/^MemTotal:\s+(\d+)\skB$/', $line, $matches)) { + $result['total'] = (int)$matches[1] * 1024; + } + unset($matches); + + if (preg_match('/^MemFree:\s+(\d+)\skB$/', $line, $matches)) { + $result['free'] = (int)$matches[1] * 1024; + } + unset($matches); + + if (preg_match('/^SwapFree:\s+(\d+)\skB$/', $line, $matches)) { + $result['swapTotal'] = (int)$matches[1] * 1024; + } + unset($matches); + + if (preg_match('/^SwapFree:\s+(\d+)\skB$/', $line, $matches)) { + $result['swapFree'] = (int)$matches[1] * 1024; + } + unset($matches); + } + fclose($fh); + + if ($humanView) { + $result = array_map(static function ($el) { + return self::convertBytes($el); + }, $result); + } + return $result; + } + + /** + * Парсинг логов nginx + * + * @param string $logPath Путь до файла логов + * @param bool $isOnlyCount Только получение количества + * @param string|null $limit Ограничение выборки "0, 10" + * @param bool $isReverse Реверсировать выборку + * + * @return array|int + * @throws CoreException + */ + public static function getNginxLogData(string $logPath, bool $isOnlyCount = false, ?string $limit = null, bool $isReverse = false) + { + if (!file_exists($logPath)) { + throw new CoreException('Файл логов не найден', CoreException::ERROR_FILE_NOT_FOUND); + } + $arLogs = file($logPath); + $logCount = count($arLogs); + if ($isOnlyCount) { + return $logCount; + } + if ($isReverse) { + $arLogs = array_reverse($arLogs); + } + $arLimit = [0, $logCount]; + if ($limit !== null) { + $arLimit['start'] = (int)explode(',', $limit)[0]; + $arLimit['stop'] = $arLimit['start'] + (int)explode(',', $limit)[1]; + } + $regExp = '/(?[0-9.]+)\s+\-\s+\-\s\[(?[^\]]+)\]\s"(?[^"]+)"\s(?\d+)\s+(?\d+)\s"(?[^"]+)"\s"(?[^"]+)"/m'; + $arResult = []; + $result = null; + $counter = 0; + foreach ($arLogs as $logEvent) { + $counter++; + if ($limit !== null && ($counter - 1) < $arLimit['start']) { + continue; + } + preg_match_all($regExp, $logEvent, $result, PREG_SET_ORDER, 0); + $result = array_shift($result); + $arResult[] = [ + 'ip' => $result['ip'], + 'date' => $result['date'], + 'request' => $result['request'], + 'httpCode' => $result['code'], + 'size' => $result['size'], + 'url' => $result['url'], + 'userAgent' => $result['useragent'], + ]; + $result = null; + if ($limit !== null && ($counter + 1) > $arLimit['stop']) { + break; + } + } + return $arResult; + } } diff --git a/core/lib/Core/MQTasks.class.php b/core/lib/Core/MQTasks.class.php index 242be65..367cf30 100644 --- a/core/lib/Core/MQTasks.class.php +++ b/core/lib/Core/MQTasks.class.php @@ -440,5 +440,13 @@ DELETE from `jokes` WHERE `jokes`.id not in (SELECT id FROM t_temp);' return $result; } + public function saveSiteScreen(string $url = 'it-stories.ru') + { + $image = file_get_contents('https://screen.2ip.ru/?url=' . $url); + if (empty($image)) { + throw new CoreException('Не удалось получить содержимое'); + } + return file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/uploads/screens/' . $url . ' .png', $image); + } } \ No newline at end of file diff --git a/test2.php b/test2.php index fc3bd81..39450a1 100644 --- a/test2.php +++ b/test2.php @@ -1,112 +1,20 @@ setOutputFolder($_SERVER['DOCUMENT_ROOT'] . '/backup/backups'); - $CBackup->setIgnoreDirs(['backups', 'no_bkp']); - $CBackup->useBackupDB(true); - $CBackup->setDB('localhost', 'rsgrinko_wp', '2670135', 'rsgrinko_wp'); - $CBackup->setTTL(17); - $CBackup->deleteOldBackups(); - - $res = $CBackup->create(); - if (!$res) { - echo 'Fail. Error: ' . $CBackup->getLastError(); - die(); - } - - echo 'Backup was created
    '; - //echo '
    '.print_r($CBackup->getResult(), true).'
    '; - - $arResult = $CBackup->getResult(); - - $emailBody = 'Скрипт создания бекапа закончил свою работу.' . PHP_EOL . 'Задание: it-stories.ru' . PHP_EOL . 'Файловый бекап (' - . $arResult['create']['files']['time'] . '):' . PHP_EOL . $arResult['create']['files']['path'] . PHP_EOL . PHP_EOL - . 'Бекап базы (' . $arResult['create']['db']['time'] . '):' . PHP_EOL . $arResult['create']['db']['path'] . PHP_EOL . PHP_EOL - . 'Обработка старых бекапов (' . $arResult['remove']['time'] . ')' . PHP_EOL . implode(PHP_EOL, $arResult['remove']['files']); - $arMailFields = [ - 'MESSAGE' => nl2br($emailBody), - 'TITLE' => 'Бекап завершен', + $array = [ + 'login' => 'Nominal', + 'password' => 'j2medit' ]; - $mail = new Mail(); - $mail->dump = false; - $mail->dumpPath = '.'; - $mail->from('backup@cron.it-stories.ru', 'Система резервного копирования'); - $mail->to('rsgrinko@yandex.ru, rsgrinko@gmail.com', 'Роман Гринько'); - $mail->subject = 'Отчет о создании бекапа'; - $mail->assignTemplateVars($arMailFields); - $mail->template = 'scom'; - $mail->templateDir = $_SERVER['DOCUMENT_ROOT'] . '/core/mail_templates'; - $mail->send(); - - - /** @var DB $DB */ - $DB = new DB('localhost', 'rsgrinko_wp', '2670135', 'rsgrinko_wp'); - $yandexOauthToken = $DB->query('SELECT * FROM its_yandex')[0]['accessToken']; - if (empty($yandexOauthToken)) { - $emailBody = 'Токен авторизации не определен'; - $arMailFields = [ - 'MESSAGE' => nl2br($emailBody), - 'TITLE' => 'Ошибка бекапа на Яндекс.Диск', - ]; - $mail = new Mail(); - $mail->dump = false; - $mail->dumpPath = '.'; - $mail->from('backup@cron.it-stories.ru', 'Система резервного копирования'); - $mail->to('rsgrinko@yandex.ru, rsgrinko@gmail.com', 'Роман Гринько'); - $mail->subject = 'Отчет о создании бекапа'; - $mail->assignTemplateVars($arMailFields); - $mail->template = 'scom'; - $mail->templateDir = $_SERVER['DOCUMENT_ROOT'] . '/core/mail_templates'; - $mail->send(); - } - echo '
    ' . print_r($yandexOauthToken, true) . '
    '; - - $yandexDir = '/its_backup'; - - $disk = new Arhitector\Yandex\Disk($yandexOauthToken); - $resourceFiles = $disk->getResource($yandexDir . '/' . basename($arResult['create']['files']['path'])); - $resourceDB = $disk->getResource($yandexDir . '/' . basename($arResult['create']['db']['path'])); - - $yandexFilePath = $yandexDBPath = ''; - - $yandexStartTime = microtime(true); - if (!$resourceFiles->has()) { - $resourceFiles->upload($arResult['create']['files']['path']); - $yandexFilePath = $resourceFiles->toArray()['path']; - } - - if (!$resourceDB->has()) { - $resourceDB->upload($arResult['create']['db']['path']); - $yandexDBPath = $resourceDB->toArray()['path']; - } - - - $emailBody = 'Бекап на Яндекс.Диск выполнен' . PHP_EOL . 'Время выполнения: ' . round(microtime(true) - $yandexStartTime, 4) . ' cek.' - . PHP_EOL . 'Расположения бекапов: ' . PHP_EOL . implode(PHP_EOL, [$yandexFilePath, $yandexDBPath]); - $arMailFields = [ - 'MESSAGE' => nl2br($emailBody), - 'TITLE' => 'Бекап на Яндекс.Диск выполнен', - ]; - $mail = new Mail(); - $mail->dump = false; - $mail->dumpPath = '.'; - $mail->from('backup@cron.it-stories.ru', 'Система резервного копирования'); - $mail->to('rsgrinko@yandex.ru, rsgrinko@gmail.com', 'Роман Гринько'); - $mail->subject = 'Отчет о создании бекапа'; - $mail->assignTemplateVars($arMailFields); - $mail->template = 'scom'; - $mail->templateDir = $_SERVER['DOCUMENT_ROOT'] . '/core/mail_templates'; - $mail->send(); - - @unlink($arResult['create']['files']['path']); - @unlink($arResult['create']['db']['path']); - + $cookieFile = $_SERVER['DOCUMENT_ROOT'] . '/uploads/cookie.txt'; + $ch = curl_init('https://visavi.net/login'); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array, '', '&')); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); + curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); + curl_setopt($ch, CURLOPT_HEADER, false); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); + $html = curl_exec($ch); + curl_close($ch); + unset($html);