This commit is contained in:
2026-07-08 11:58:04 +08:00
parent 614e943845
commit acc966c3df
3 changed files with 301 additions and 356 deletions
+25 -95
View File
@@ -11,14 +11,18 @@ use Kiri\Server\Events\OnWorkerStart;
use Kiri\Server\Processes\AbstractProcess; use Kiri\Server\Processes\AbstractProcess;
use Kiri\Server\Processes\OnProcessInterface; use Kiri\Server\Processes\OnProcessInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Swoole\Coroutine;
use Swoole\Event; use Swoole\Event;
use Swoole\Process; use Swoole\Process;
use Swoole\Timer;
use const SIGKILL; use const SIGKILL;
use const SIGTERM; use const SIGTERM;
use const SIGUSR1; use const SIGUSR1;
class FileWatcher extends AbstractProcess implements OnProcessInterface class FileWatcher extends AbstractProcess implements OnProcessInterface
{ {
use ReloadWorkers;
protected mixed $pipe; protected mixed $pipe;
#[Container(LoggerInterface::class)] #[Container(LoggerInterface::class)]
@@ -39,21 +43,21 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
private bool $running = false; private bool $running = false;
private bool $scanning = false; private bool $scanning = false;
private $inotifyFd = null; private mixed $inotifyFd = null;
private array $inotifyWatchMap = []; private array $inotifyWatchMap = [];
private $fswatchProcess = null; private mixed $fswatchProcess = null;
private array $fswatchPipes = []; private array $fswatchPipes = [];
private int $pollInterval = 2; private int $pollInterval = 2;
private array $fileSnapshot = []; private array $fileSnapshot = [];
private $pollTimer = null; private int $pollTimer = -1;
private $debounceTimer = null; private int $debounceTimer = -1;
private int $debounceMs = 200; private int $debounceMs = 200;
private int $minReloadIntervalMs = 1000; private int $minReloadIntervalMs = 1000;
private int $lastReloadAtMs = 0; private int $lastReloadAtMs = 0;
private const STRATEGY_INOTIFY = 'inotify'; private const string STRATEGY_INOTIFY = 'inotify';
private const STRATEGY_FSWATCH = 'fswatch'; private const string STRATEGY_FSWATCH = 'fswatch';
private const STRATEGY_POLL = 'poll'; private const string STRATEGY_POLL = 'poll';
public function __construct() public function __construct()
{ {
@@ -136,7 +140,7 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
public function process(Process|null $process): void public function process(Process|null $process): void
{ {
if (class_exists('\\Swoole\\Coroutine')) { if (class_exists('\\Swoole\\Coroutine')) {
\Swoole\Coroutine::set(['enable_deadlock_check' => false]); Coroutine::set(['enable_deadlock_check' => false]);
} }
if ($this->running) { if ($this->running) {
@@ -180,13 +184,13 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
$this->stopFswatchProcess(); $this->stopFswatchProcess();
if ($this->pollTimer) { if ($this->pollTimer) {
\Swoole\Timer::clear($this->pollTimer); Timer::clear($this->pollTimer);
$this->pollTimer = null; $this->pollTimer = -1;
} }
if ($this->debounceTimer) { if ($this->debounceTimer) {
\Swoole\Timer::clear($this->debounceTimer); Timer::clear($this->debounceTimer);
$this->debounceTimer = null; $this->debounceTimer = -1;
} }
@Event::exit(); @Event::exit();
@@ -229,6 +233,7 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
} }
$this->fswatchProcess = null; $this->fswatchProcess = null;
} }
private function isExcluded(string $path): bool private function isExcluded(string $path): bool
{ {
foreach ($this->excludePatterns as $pattern) { foreach ($this->excludePatterns as $pattern) {
@@ -252,23 +257,25 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
private function triggerCallback(array $changedFiles): void private function triggerCallback(array $changedFiles): void
{ {
$changedFiles = array_values(array_unique(array_filter($changedFiles, function ($file) { $changedFiles = array_filter($changedFiles, function ($file) {
return !$this->isExcluded($file) && $this->hasValidExtension($file); return !$this->isExcluded($file) && $this->hasValidExtension($file);
}))); })
|> array_unique(...)
|> array_values(...);
if (empty($changedFiles)) { if (empty($changedFiles)) {
return; return;
} }
if ($this->debounceTimer) { if ($this->debounceTimer) {
\Swoole\Timer::clear($this->debounceTimer); Timer::clear($this->debounceTimer);
} }
$now = intdiv(hrtime(true), 1000000); $now = intdiv(hrtime(true), 1000000);
$elapsed = $this->lastReloadAtMs > 0 ? $now - $this->lastReloadAtMs : $this->minReloadIntervalMs; $elapsed = $this->lastReloadAtMs > 0 ? $now - $this->lastReloadAtMs : $this->minReloadIntervalMs;
$delay = max($this->debounceMs, $this->minReloadIntervalMs - $elapsed); $delay = max($this->debounceMs, $this->minReloadIntervalMs - $elapsed);
$this->debounceTimer = \Swoole\Timer::after($delay, function () use ($changedFiles) { $this->debounceTimer = Timer::after($delay, function () use ($changedFiles) {
$this->debounceTimer = null; $this->debounceTimer = null;
$this->reload($changedFiles); $this->reload($changedFiles);
}); });
@@ -300,58 +307,6 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
} }
} }
private function reloadWorkers(): bool
{
$pid = $this->getMasterPid();
if ($pid === null) {
return false;
}
return Process::kill($pid, SIGUSR1);
}
private function getMasterPid(): ?int
{
$processes = $this->listProcesses();
$candidates = [];
$pidFile = function_exists('storage') ? storage('.swoole.pid') : '';
if (is_file($pidFile)) {
$candidates[] = (int)trim((string)file_get_contents($pidFile));
}
foreach ($processes as $process) {
if ($this->isMasterProcessCommand($process['command'])) {
$candidates[] = (int)$process['pid'];
}
}
foreach (array_values(array_unique(array_filter($candidates))) as $pid) {
if ($this->isProcessAlive($pid) && $this->isMasterPid($pid, $processes)) {
return $pid;
}
}
return null;
}
/**
* @param int $pid
* @param array $processes
* @return bool
*/
private function isMasterPid(int $pid, array $processes): bool
{
foreach ($processes as $process) {
if ((int)$process['pid'] === $pid) {
return $this->isMasterProcessCommand($process['command']) && $this->isSameAppProcess($pid);
}
}
return false;
}
private function isMasterProcessCommand(string $command): bool private function isMasterProcessCommand(string $command): bool
{ {
$prefix = '[' . config('site.id', 'system-service') . '].Master['; $prefix = '[' . config('site.id', 'system-service') . '].Master[';
@@ -374,37 +329,12 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
return rtrim(str_replace('\\', '/', $real), '/'); return rtrim(str_replace('\\', '/', $real), '/');
} }
private function listProcesses(): array
{
$lines = [];
exec('ps -eo pid=,ppid=,args=', $lines);
$processes = [];
foreach ($lines as $line) {
$line = trim($line);
if ($line === '') {
continue;
}
$parts = preg_split('/\s+/', $line, 3);
if (count($parts) < 3) {
continue;
}
$processes[] = [
'pid' => (int)$parts[0],
'ppid' => (int)$parts[1],
'command' => $parts[2],
];
}
return $processes;
}
private function isProcessAlive(int $pid): bool private function isProcessAlive(int $pid): bool
{ {
return $pid > 1 && @Process::kill($pid, 0); return $pid > 1 && @Process::kill($pid, 0);
} }
private function startInotify(): void private function startInotify(): void
{ {
$this->inotifyFd = inotify_init(); $this->inotifyFd = inotify_init();
@@ -531,7 +461,7 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
$this->buildFileSnapshot(); $this->buildFileSnapshot();
$intervalMs = $this->pollInterval * 1000; $intervalMs = $this->pollInterval * 1000;
$this->pollTimer = \Swoole\Timer::tick($intervalMs, function () { $this->pollTimer = Timer::tick($intervalMs, function () {
if (!$this->running || $this->scanning) { if (!$this->running || $this->scanning) {
return; return;
} }
+3 -75
View File
@@ -15,6 +15,8 @@ use Kiri\Server\Processes\AbstractProcess;
class HotReload extends AbstractProcess class HotReload extends AbstractProcess
{ {
use ReloadWorkers;
/** /**
* @var mixed * @var mixed
@@ -134,55 +136,6 @@ class HotReload extends AbstractProcess
} }
/**
* @return void
*/
private function reloadWorkers(): bool
{
$pid = $this->getMasterPid();
if ($pid === null) {
return false;
}
return Process::kill($pid, SIGUSR1);
}
private function getMasterPid(): ?int
{
$processes = $this->listProcesses();
$candidates = [];
$pidFile = function_exists('storage') ? storage('.swoole.pid') : '';
if (is_file($pidFile)) {
$candidates[] = (int)trim((string)file_get_contents($pidFile));
}
foreach ($processes as $process) {
if ($this->isMasterProcessCommand($process['command'])) {
$candidates[] = (int)$process['pid'];
}
}
foreach (array_values(array_unique(array_filter($candidates))) as $pid) {
if ($this->isProcessAlive($pid) && $this->isMasterPid($pid, $processes)) {
return $pid;
}
}
return null;
}
private function isMasterPid(int $pid, array $processes): bool
{
foreach ($processes as $process) {
if ((int)$process['pid'] === $pid) {
return $this->isMasterProcessCommand($process['command']) && $this->isSameAppProcess($pid);
}
}
return false;
}
private function isMasterProcessCommand(string $command): bool private function isMasterProcessCommand(string $command): bool
{ {
$prefix = '[' . config('site.id', 'system-service') . '].Master['; $prefix = '[' . config('site.id', 'system-service') . '].Master[';
@@ -205,37 +158,12 @@ class HotReload extends AbstractProcess
return rtrim(str_replace('\\', '/', $real), '/'); return rtrim(str_replace('\\', '/', $real), '/');
} }
private function listProcesses(): array
{
$lines = [];
exec('ps -eo pid=,ppid=,args=', $lines);
$processes = [];
foreach ($lines as $line) {
$line = trim($line);
if ($line === '') {
continue;
}
$parts = preg_split('/\s+/', $line, 3);
if (count($parts) < 3) {
continue;
}
$processes[] = [
'pid' => (int)$parts[0],
'ppid' => (int)$parts[1],
'command' => $parts[2],
];
}
return $processes;
}
private function isProcessAlive(int $pid): bool private function isProcessAlive(int $pid): bool
{ {
return $pid > 1 && @Process::kill($pid, 0); return $pid > 1 && @Process::kill($pid, 0);
} }
protected function addListen(): void protected function addListen(): void
{ {
foreach (config('servers.reload.listen') as $value) { foreach (config('servers.reload.listen') as $value) {
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace Kiri\Server\Abstracts;
use Swoole\Process;
trait ReloadWorkers
{
/**
* @return void
*/
private function reloadWorkers(): bool
{
$pid = $this->getMasterPid();
if ($pid === null) {
return false;
}
return Process::kill($pid, SIGUSR1);
}
private function getMasterPid(): ?int
{
$processes = $this->listProcesses();
$candidates = [];
$pidFile = function_exists('storage') ? storage('.swoole.pid') : '';
if (is_file($pidFile)) {
$candidates[] = (int)trim((string)file_get_contents($pidFile));
}
foreach ($processes as $process) {
if ($this->isMasterProcessCommand($process['command'])) {
$candidates[] = (int)$process['pid'];
}
}
foreach ($candidates
|> array_filter(...)
|> array_unique(...)
|> array_values(...) as $pid) {
if ($this->isProcessAlive($pid) && $this->isMasterPid($pid, $processes)) {
return $pid;
}
}
return null;
}
private function isMasterPid(int $pid, array $processes): bool
{
foreach ($processes as $process) {
if ((int)$process['pid'] === $pid) {
return $this->isMasterProcessCommand($process['command']) && $this->isSameAppProcess($pid);
}
}
return false;
}
private function listProcesses(): array
{
$lines = [];
exec('ps -eo pid=,ppid=,args=', $lines);
$processes = [];
foreach ($lines as $line) {
$line = trim($line);
if ($line === '') {
continue;
}
$parts = preg_split('/\s+/', $line, 3);
if (count($parts) < 3) {
continue;
}
$processes[] = [
'pid' => (int)$parts[0],
'ppid' => (int)$parts[1],
'command' => $parts[2],
];
}
return $processes;
}
}