[+] добавлен метод и страница для парсинга логов nginx

This commit is contained in:
rsgrinko committed 2022-12-08 20:54:23 +03:00
1 parent 64c4e62ca3
commit 2ba753e625
8 files changed
+250 -113

No files matched your search

+12
View File
@@ -20,6 +20,7 @@
*/
use Core\Models\MQ;
use Core\Helpers\SystemFunctions;
require_once __DIR__ . '/../inc/bootstrap.php';
$result = null;
@@ -194,4 +195,15 @@
</div>
<?php
$result['progress'] = ob_get_clean();
ob_start();
$memory = SystemFunctions::getHostMemoryInfo();
?>
<div class="progress">
<div style="width: <?= round(($memory['free'] + $memory['swapFree']) / ($memory['total'] + $memory['swapTotal']) * 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['memory'] = ob_get_clean();
echo json_encode($result, JSON_UNESCAPED_UNICODE);
+1
View File
@@ -250,6 +250,7 @@
<li><a href="/admin/hosts.php"><i class="fa fa-home"></i> <span>Управление хостами</span></a></li>
<li><a href="/admin/threads.php"><i class="fa fa-home"></i> <span>Диспетчер очереди</span></a></li>
<li><a href="/admin/phpcmd.php"><i class="fa fa-home"></i> <span>Командная PHP строка</span></a></li>
<li><a href="/admin/nginx.php"><i class="fa fa-home"></i> <span>Логи nginx</span></a></li>
<li><a href="index.html"><i class="fa fa-home"></i> <span>Dashboard</span></a></li>
+89
View File
@@ -0,0 +1,89 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* 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';
?>
<div class="pageheader">
<div class="media">
<div class="pageicon pull-left">
<i class="fa fa-home"></i>
</div>
<div class="media-body">
<ul class="breadcrumb">
<li><a href=""><i class="glyphicon glyphicon-home"></i></a></li>
<li>Логи nginx</li>
</ul>
<h4>Логи nginx</h4>
</div>
</div><!-- media -->
</div><!-- pageheader -->
<div class="contentpanel">
<!-- table -->
<div class="row">
<div class="col-md-12r">
<div class="table-responsive">
<table class="table table-primary table-hover mb30">
<thead>
<tr>
<th>IP</th>
<th>Дата</th>
<th>Запрос</th>
<th>Код</th>
<th>Размер</th>
<th>URL</th>
<th>Браузер</th>
</tr>
</thead>
<tbody>
<?php
$nginxLogFile = $_SERVER['DOCUMENT_ROOT'].'/../../log/it-stories.ru_access';
//$nginxLogFile = $_SERVER['DOCUMENT_ROOT'].'/../../log/test.log';
Pagination::execute($_REQUEST['page'], SystemFunctions::getNginxLogData($nginxLogFile, true), PAGINATION_LIMIT);
$limit = Pagination::getLimit();
$arLogs = SystemFunctions::getNginxLogData($nginxLogFile, false, $limit, true);
foreach ($arLogs as $elLog) {
?>
<tr>
<td><?= $elLog['ip'] ?></td>
<td><?= date('Y.m.d H:i:s', strtotime($elLog['date'] . ' +3 hour')) ?></td>
<td><?= $elLog['request'] ?></td>
<td><?= $elLog['httpCode'] ?></td>
<td><?= $elLog['size'] ? SystemFunctions::convertBytes($elLog['size']) : '' ?></td>
<td><?= $elLog['url'] ?></td>
<td><?= $elLog['userAgent'] ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div><!-- table-responsive -->
<?php Pagination::show('page') ?>
</div>
</div>
<!-- end table -->
</div><!-- contentpanel -->
<?php require_once __DIR__ . '/inc/footer.php'; ?>
+15
View File
@@ -90,6 +90,20 @@
</div>
</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="memory">
<div class="preloader"></div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
@@ -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);
+3 -5
View File
@@ -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;
}
/**
@@ -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 = '/(?<ip>[0-9.]+)\s+\-\s+\-\s\[(?<date>[^\]]+)\]\s"(?<request>[^"]+)"\s(?<code>\d+)\s+(?<size>\d+)\s"(?<url>[^"]+)"\s"(?<useragent>[^"]+)"/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;
}
}
+8
View File
@@ -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);
}
}
+16 -108
View File
@@ -1,112 +1,20 @@
<?php
require_once '../core/bootstrap.php';
@ignore_user_abort(true); // игнорируем закрытие сессии клиентом
set_time_limit(3600); // лимит - час
require_once $_SERVER['DOCUMENT_ROOT'] . '/backup/inc/CBackup.class.php';
$CBackup = new CBackup('/home/rsgrinko/sites/it-stories.ru');
$CBackup->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<br>';
//echo '<pre>'.print_r($CBackup->getResult(), true).'</pre>';
$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 '<pre>' . print_r($yandexOauthToken, true) . '</pre>';
$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);