Режим обслуживания: down/up и кнопка в панели
503 всем чужим до роутера, пока флаг стоит на диске — своим (system.manage) и списку допуска не мешает
This commit is contained in:
1 parent
84d6382c1d
commit
af4409924f
12 files changed
+380
-14
No files matched your search
@@ -25,6 +25,8 @@ final class Application
|
||||
private const COMMANDS = [
|
||||
'Установка и обслуживание' => [
|
||||
Commands\InstallCommand::class,
|
||||
Commands\DownCommand::class,
|
||||
Commands\UpCommand::class,
|
||||
Commands\MigrateCommand::class,
|
||||
Commands\MigrateStatusCommand::class,
|
||||
Commands\MigrateRollbackCommand::class,
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Console\Commands;
|
||||
|
||||
use Rsgrinko\Proton\Console\Command;
|
||||
use Rsgrinko\Proton\Support\Maintenance;
|
||||
|
||||
/**
|
||||
* включить режим обслуживания.
|
||||
*/
|
||||
final class DownCommand extends Command
|
||||
{
|
||||
public function name(): string
|
||||
{
|
||||
return 'down';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'включить режим обслуживания (503 всем, кроме system.manage и --allow)';
|
||||
}
|
||||
|
||||
public function usage(): string
|
||||
{
|
||||
return 'down [--message="Текст"] [--allow=IP,IP] [--retry=60]';
|
||||
}
|
||||
|
||||
public function run(): int
|
||||
{
|
||||
Maintenance::activate(
|
||||
(string) $this->option('message', ''),
|
||||
(string) $this->option('allow', ''),
|
||||
(int) $this->option('retry', '0')
|
||||
);
|
||||
|
||||
$this->ok('Режим обслуживания включён — свои (system.manage) работают как обычно');
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Console\Commands;
|
||||
|
||||
use Rsgrinko\Proton\Console\Command;
|
||||
use Rsgrinko\Proton\Support\Maintenance;
|
||||
|
||||
/**
|
||||
* выключить режим обслуживания.
|
||||
*/
|
||||
final class UpCommand extends Command
|
||||
{
|
||||
public function name(): string
|
||||
{
|
||||
return 'up';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'выключить режим обслуживания';
|
||||
}
|
||||
|
||||
public function run(): int
|
||||
{
|
||||
if (!Maintenance::active()) {
|
||||
$this->line('Режим обслуживания и так выключен');
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Maintenance::deactivate();
|
||||
|
||||
$this->ok('Режим обслуживания выключен');
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace Rsgrinko\Proton\Http;
|
||||
|
||||
use Rsgrinko\Proton\Access\AccessDenied;
|
||||
use Rsgrinko\Proton\Access\Permission;
|
||||
use Rsgrinko\Proton\Auth\Auth;
|
||||
use Rsgrinko\Proton\Auth\Csrf;
|
||||
use Rsgrinko\Proton\Database\Model\RecordNotFound;
|
||||
@@ -20,6 +21,7 @@ use Rsgrinko\Proton\Http\Middleware\Throttle;
|
||||
use Rsgrinko\Proton\Http\Middleware\VerifyCsrf;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\Logger;
|
||||
use Rsgrinko\Proton\Support\Maintenance;
|
||||
use Rsgrinko\Proton\Support\Metrics;
|
||||
use Rsgrinko\Proton\Support\ProtonException;
|
||||
use Rsgrinko\Proton\Support\RequestId;
|
||||
@@ -57,7 +59,9 @@ final class Kernel
|
||||
Settings::apply();
|
||||
|
||||
try {
|
||||
$response = $this->finish($this->blocked($request) ?? $this->router()->dispatch($request));
|
||||
$response = $this->finish(
|
||||
$this->maintenance($request) ?? $this->blocked($request) ?? $this->router()->dispatch($request)
|
||||
);
|
||||
} catch (AccessDenied $e) {
|
||||
$response = $this->finish($this->denied($request, $e));
|
||||
} catch (RecordNotFound $e) {
|
||||
@@ -120,6 +124,32 @@ final class Kernel
|
||||
->withHeader(RequestId::HEADER, RequestId::current());
|
||||
}
|
||||
|
||||
/**
|
||||
* Режим обслуживания разворачиваем до маршрутов и до блокировки по IP:
|
||||
* своему администратору (право system.manage) он не мешает — иначе
|
||||
* править что-то на живую под собственным же режимом обслуживания
|
||||
* пришлось бы через отдельный allow-список. Пустой ответ — режим выключен.
|
||||
*/
|
||||
private function maintenance(Request $request): ?Response
|
||||
{
|
||||
if (!Maintenance::active()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (Maintenance::allows($request->ip()) || Auth::viewer()->can(Permission::SYSTEM_MANAGE)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$payload = Maintenance::payload();
|
||||
$message = $payload['message'] !== '' ? $payload['message'] : 'Идут технические работы, зайдите чуть позже.';
|
||||
|
||||
$response = $request->wantsJson()
|
||||
? Response::error($message, 503)
|
||||
: Response::html(View::render('errors/503', ['message' => $message], 'Технические работы'), 503);
|
||||
|
||||
return $payload['retry'] > 0 ? $response->withHeader('Retry-After', (string) $payload['retry']) : $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Закрытый адрес разворачиваем до маршрутов: заблокированному нечего делать
|
||||
* ни на форме входа, ни в API. Пустой ответ означает «адрес не закрыт».
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
/**
|
||||
* Режим обслуживания: пока флаг лежит на диске, всем чужим — 503, вместо
|
||||
* того чтобы ловить приложение на середине наката миграции или деплоя.
|
||||
*
|
||||
* php bin/proton down --message="Обновляем базу" --allow=127.0.0.1 --retry=60
|
||||
* php bin/proton up
|
||||
*
|
||||
* Флаг — файл, не запись в базе: база в момент наката как раз может быть
|
||||
* недоступна или в переходном состоянии, а до файла дело есть только у диска.
|
||||
* Тем, у кого право `system.manage`, включённый режим не мешает — не нужно
|
||||
* держать отдельный список адресов ради своей же правки. Список `allow` —
|
||||
* для тех, кому нельзя увидеть панель (внешний heartbeat, вебхук).
|
||||
*/
|
||||
final class Maintenance
|
||||
{
|
||||
private static function file(): string
|
||||
{
|
||||
return (string) Config::get('paths.maintenance', APP_ROOT . '/var') . '/maintenance.json';
|
||||
}
|
||||
|
||||
/**
|
||||
* Включить. Пустой список `allow` — никого, кроме `system.manage`.
|
||||
*/
|
||||
public static function activate(string $message = '', string $allow = '', int $retry = 0): void
|
||||
{
|
||||
$file = self::file();
|
||||
|
||||
@mkdir(dirname($file), 0775, true);
|
||||
|
||||
file_put_contents($file, (string) json_encode([
|
||||
'message' => $message,
|
||||
'allow' => $allow,
|
||||
'retry' => max(0, $retry),
|
||||
'since' => time(),
|
||||
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
|
||||
}
|
||||
|
||||
public static function deactivate(): void
|
||||
{
|
||||
@unlink(self::file());
|
||||
}
|
||||
|
||||
public static function active(): bool
|
||||
{
|
||||
return is_file(self::file());
|
||||
}
|
||||
|
||||
/**
|
||||
* Разрешён ли адресу проход мимо страницы «идут работы».
|
||||
*/
|
||||
public static function allows(string $ip): bool
|
||||
{
|
||||
$allow = trim((string) (self::payload()['allow'] ?? ''));
|
||||
|
||||
return $allow !== '' && IpAllowlist::allows($allow, $ip);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{message: string, allow: string, retry: int, since: int}
|
||||
*/
|
||||
public static function payload(): array
|
||||
{
|
||||
if (!self::active()) {
|
||||
return ['message' => '', 'allow' => '', 'retry' => 0, 'since' => 0];
|
||||
}
|
||||
|
||||
$decoded = json_decode((string) file_get_contents(self::file()), true);
|
||||
|
||||
return [
|
||||
'message' => (string) ($decoded['message'] ?? ''),
|
||||
'allow' => (string) ($decoded['allow'] ?? ''),
|
||||
'retry' => (int) ($decoded['retry'] ?? 0),
|
||||
'since' => (int) ($decoded['since'] ?? 0),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* @var string $message
|
||||
*/
|
||||
|
||||
use Rsgrinko\Proton\View\View;
|
||||
?>
|
||||
<div class="card">
|
||||
<h1>Технические работы</h1>
|
||||
<p class="muted"><?= View::e($message) ?></p>
|
||||
</div>
|
||||
Reference in new issue
Block a user