Compare commits

..

16 Commits

Author SHA1 Message Date
as2252258 d3ca24c4c5 Build hot reload artifacts before worker restart 2026-07-10 17:13:20 +08:00
as2252258 ca68418e0d eee 2026-07-10 15:57:44 +08:00
as2252258 3fe9ab06c3 Invalidate changed PHP files before worker reload 2026-07-08 14:34:38 +08:00
as2252258 a61e83ff6a Fix FileWatcher timer sentinel handling 2026-07-08 13:49:46 +08:00
as2252258 55d50b7bff Handle SIGINT after Swoole server start 2026-07-08 12:13:48 +08:00
as2252258 f6219a5c5d Avoid creating Swoole event loop for SIGINT 2026-07-08 12:04:04 +08:00
as2252258 acc966c3df eee 2026-07-08 11:58:04 +08:00
as2252258 614e943845 Fix server SIGINT handling under Swoole 2026-07-08 11:50:02 +08:00
as2252258 27ffa05515 eee 2026-07-08 11:39:27 +08:00
as2252258 1f443958e8 eee 2026-07-08 10:46:00 +08:00
as2252258 77e9333651 eee 2026-07-08 10:45:21 +08:00
as2252258 56ebbd2a2e eee 2026-07-08 10:08:10 +08:00
as2252258 7f36bb0d53 eee 2026-07-08 09:42:56 +08:00
as2252258 0adfe14a1f eee 2026-07-07 22:59:28 +08:00
as2252258 3ca39d2205 eee 2026-07-03 14:25:26 +08:00
as2252258 908c8719d3 eee 2026-06-24 20:17:54 +08:00
12 changed files with 961 additions and 237 deletions
+12 -5
View File
@@ -9,7 +9,6 @@ use Kiri\Exception\NotFindClassException;
use Kiri\Server\Config as SConfig;
use Kiri\Server\Constant;
use Kiri\Server\Events\OnServerBeforeStart;
use Kiri\Server\Events\OnShutdown;
use Kiri\Server\Handler\OnServer;
use Kiri\Server\Processes\TraitProcess;
use Kiri\Server\ServerInterface;
@@ -32,6 +31,8 @@ class AsyncServer extends Component implements ServerInterface
*/
private ?Server $server = null;
private bool $shuttingDown = false;
/**
* @param array $service
@@ -61,14 +62,20 @@ class AsyncServer extends Component implements ServerInterface
*/
public function shutdown(): bool
{
$this->server->shutdown();
if ($this->shuttingDown) {
return true;
}
$this->shuttingDown = true;
$this->dispatch->dispatch(new OnShutdown);
$this->terminateProcesses();
if ($this->server !== null) {
$this->server->shutdown();
}
return true;
}
/**
* @param array $service
* @param int $daemon
@@ -112,7 +119,7 @@ class AsyncServer extends Component implements ServerInterface
$settings[Constant::OPTION_DAEMONIZE] = (bool)$daemon;
$settings[Constant::OPTION_ENABLE_REUSE_PORT] = true;
$settings[Constant::OPTION_PID_FILE] = storage('.swoole.pid');
if (!isset($settings[Constant::OPTION_PID_FILE])) {
if (!isset($settings[Constant::OPTION_LOG_FILE])) {
$settings[Constant::OPTION_LOG_FILE] = storage('system.log');
}
return $settings;
+213 -40
View File
@@ -7,16 +7,23 @@ use Kiri\Di\Inject\Container;
use Kiri\Error\StdoutLogger;
use Kiri\Events\EventProvider;
use Kiri\Router\Router;
use Kiri\Router\RouteArtifactState;
use Kiri\Server\Events\OnWorkerStart;
use Kiri\Server\Processes\AbstractProcess;
use Kiri\Server\Processes\OnProcessInterface;
use Kiri\Server\ServerInterface;
use Psr\Log\LoggerInterface;
use Swoole\Coroutine;
use Swoole\Event;
use Swoole\Process;
use Swoole\Timer;
use const SIGKILL;
use const SIGTERM;
use const SIGUSR1;
class FileWatcher extends AbstractProcess implements OnProcessInterface
{
use ReloadWorkers;
protected mixed $pipe;
#[Container(LoggerInterface::class)]
@@ -35,20 +42,23 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
private array $extensions = ['php'];
private string $strategy;
private bool $running = false;
private bool $scanning = false;
private $inotifyFd = null;
private mixed $inotifyFd = null;
private array $inotifyWatchMap = [];
private $fswatchProcess = null;
private mixed $fswatchProcess = null;
private array $fswatchPipes = [];
private int $pollInterval = 2;
private array $fileSnapshot = [];
private $pollTimer = null;
private $debounceTimer = null;
private int $pollTimer = -1;
private int $debounceTimer = -1;
private int $debounceMs = 200;
private int $minReloadIntervalMs = 1000;
private int $lastReloadAtMs = 0;
private const STRATEGY_INOTIFY = 'inotify';
private const STRATEGY_FSWATCH = 'fswatch';
private const STRATEGY_POLL = 'poll';
private const string STRATEGY_INOTIFY = 'inotify';
private const string STRATEGY_FSWATCH = 'fswatch';
private const string STRATEGY_POLL = 'poll';
public function __construct()
{
@@ -58,6 +68,8 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
di(EventProvider::class)->on(OnWorkerStart::class, [di(Router::class), 'scan_build_route']);
$this->debounceMs = (int)config('servers.reload.debounce_ms', $this->debounceMs);
$this->minReloadIntervalMs = (int)config('servers.reload.min_interval_ms', $this->minReloadIntervalMs);
$this->strategy = $this->detectBestStrategy();
}
@@ -128,6 +140,10 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
public function process(Process|null $process): void
{
if (class_exists('\\Swoole\\Coroutine')) {
Coroutine::set(['enable_deadlock_check' => false]);
}
if ($this->running) {
return;
}
@@ -159,34 +175,66 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
$this->inotifyFd = null;
}
if (isset($this->fswatchPipes[1]) && is_resource($this->fswatchPipes[1])) {
@Event::del($this->fswatchPipes[1]);
@fclose($this->fswatchPipes[1]);
foreach ($this->fswatchPipes as $pipe) {
if (is_resource($pipe)) {
@Event::del($pipe);
@fclose($pipe);
}
}
$this->fswatchPipes = [];
$this->stopFswatchProcess();
if ($this->pollTimer > 0) {
Timer::clear($this->pollTimer);
$this->pollTimer = -1;
}
if (isset($this->fswatchPipes[2]) && is_resource($this->fswatchPipes[2])) {
@fclose($this->fswatchPipes[2]);
}
if ($this->fswatchProcess && is_resource($this->fswatchProcess)) {
@proc_terminate($this->fswatchProcess);
@proc_close($this->fswatchProcess);
$this->fswatchProcess = null;
}
if ($this->pollTimer) {
\Swoole\Timer::clear($this->pollTimer);
$this->pollTimer = null;
}
if ($this->debounceTimer) {
\Swoole\Timer::clear($this->debounceTimer);
$this->debounceTimer = null;
if ($this->debounceTimer > 0) {
Timer::clear($this->debounceTimer);
$this->debounceTimer = -1;
}
@Event::exit();
}
private function stopFswatchProcess(): void
{
if (!$this->fswatchProcess || !is_resource($this->fswatchProcess)) {
$this->fswatchProcess = null;
return;
}
$status = @proc_get_status($this->fswatchProcess);
if (($status['running'] ?? false) === true) {
@proc_terminate($this->fswatchProcess, SIGTERM);
for ($i = 0; $i < 10; $i++) {
usleep(100000);
$status = @proc_get_status($this->fswatchProcess);
if (($status['running'] ?? false) !== true) {
break;
}
}
}
$status = @proc_get_status($this->fswatchProcess);
if (($status['running'] ?? false) === true) {
@proc_terminate($this->fswatchProcess, SIGKILL);
for ($i = 0; $i < 5; $i++) {
usleep(100000);
$status = @proc_get_status($this->fswatchProcess);
if (($status['running'] ?? false) !== true) {
break;
}
}
}
$status = @proc_get_status($this->fswatchProcess);
if (($status['running'] ?? false) !== true) {
@proc_close($this->fswatchProcess);
}
$this->fswatchProcess = null;
}
private function isExcluded(string $path): bool
{
foreach ($this->excludePatterns as $pattern) {
@@ -210,20 +258,26 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
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);
})));
})
|> array_unique(...)
|> array_values(...);
if (empty($changedFiles)) {
return;
}
if ($this->debounceTimer) {
\Swoole\Timer::clear($this->debounceTimer);
if ($this->debounceTimer > 0) {
Timer::clear($this->debounceTimer);
}
$this->debounceTimer = \Swoole\Timer::after($this->debounceMs, function () use ($changedFiles) {
$this->debounceTimer = null;
$now = intdiv(hrtime(true), 1000000);
$elapsed = $this->lastReloadAtMs > 0 ? $now - $this->lastReloadAtMs : $this->minReloadIntervalMs;
$delay = max($this->debounceMs, $this->minReloadIntervalMs - $elapsed);
$this->debounceTimer = Timer::after($delay, function () use ($changedFiles) {
$this->debounceTimer = -1;
$this->reload($changedFiles);
});
}
@@ -237,23 +291,122 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
$this->reloading = true;
try {
$this->lastReloadAtMs = intdiv(hrtime(true), 1000000);
$this->invalidateChangedFiles($changedFiles);
$preview = implode(', ', array_slice($changedFiles, 0, 3));
if (count($changedFiles) > 3) {
$preview .= ' ...';
}
di(HotReloadState::class)->store($changedFiles);
di(StdoutLogger::class)->println('detected file changes, reloading server: ' . $preview);
di(StdoutLogger::class)->println('detected file changes, building hot reload artifacts: ' . $preview);
$server = di(ServerInterface::class);
if (method_exists($server, 'reload')) {
$server->reload();
if (!$this->buildChangedFiles($changedFiles)) {
di(StdoutLogger::class)->println('hot reload build failed, keep old workers running');
return;
}
if (!$this->reloadWorkers()) {
di(StdoutLogger::class)->println('reload server failed: master pid not found or signal failed');
}
} finally {
$this->reloading = false;
}
}
private function buildChangedFiles(array $changedFiles): bool
{
$entry = $this->detectConsoleEntry();
if ($entry === null) {
di(StdoutLogger::class)->println('hot reload build failed: entry script not found');
return false;
}
$artifactType = defined('ROUTER_TYPE_HTTP') ? ROUTER_TYPE_HTTP : 'http';
$artifactState = di(RouteArtifactState::class);
$artifactState->clearBuild($artifactType);
$php = PHP_BINARY ?: 'php';
$command = escapeshellarg($php) . ' ' . escapeshellarg($entry) . ' sw:file-build';
$output = [];
$returnCode = 0;
exec($command . ' 2>&1', $output, $returnCode);
foreach ($output as $line) {
if ($line !== '') {
di(StdoutLogger::class)->println('[file-build] ' . $line);
}
}
if ($returnCode !== 0) {
return false;
}
return $artifactState->coversChangedFiles($artifactType, $changedFiles);
}
private function detectConsoleEntry(): ?string
{
$candidates = [
$_SERVER['SCRIPT_FILENAME'] ?? '',
defined('APP_PATH') ? APP_PATH . 'kiri.php' : '',
defined('APP_PATH') ? APP_PATH . 'bin/kiri' : '',
defined('APP_PATH') ? APP_PATH . 'artisan' : '',
];
foreach ($candidates as $candidate) {
if (is_string($candidate) && $candidate !== '' && is_file($candidate)) {
return $candidate;
}
}
return null;
}
private function invalidateChangedFiles(array $changedFiles): void
{
if (!function_exists('opcache_invalidate')) {
return;
}
foreach ($changedFiles as $file) {
if (!is_string($file) || !str_ends_with($file, '.php')) {
continue;
}
$path = realpath($file) ?: $file;
if (is_file($path)) {
@opcache_invalidate($path, true);
}
}
}
private function isMasterProcessCommand(string $command): bool
{
$prefix = '[' . config('site.id', 'system-service') . '].Master[';
return str_contains($command, $prefix);
}
private function isSameAppProcess(int $pid): bool
{
$cwd = @readlink('/proc/' . $pid . '/cwd');
if ($cwd === false || $cwd === '') {
return false;
}
return $this->normalizePath($cwd) === $this->normalizePath(APP_PATH);
}
private function normalizePath(string $path): string
{
$real = realpath($path) ?: $path;
return rtrim(str_replace('\\', '/', $real), '/');
}
private function isProcessAlive(int $pid): bool
{
return $pid > 1 && @Process::kill($pid, 0);
}
private function startInotify(): void
{
$this->inotifyFd = inotify_init();
@@ -264,6 +417,10 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
}
Event::add($this->inotifyFd, function ($fd) {
if (!$this->running) {
return;
}
$events = inotify_read($fd);
if ($events === false) {
return;
@@ -353,6 +510,10 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
stream_set_blocking($this->fswatchPipes[1], false);
Event::add($this->fswatchPipes[1], function ($pipe) {
if (!$this->running) {
return;
}
$data = fread($pipe, 8192);
if ($data === false || $data === '') {
return;
@@ -372,14 +533,26 @@ class FileWatcher extends AbstractProcess implements OnProcessInterface
$this->buildFileSnapshot();
$intervalMs = $this->pollInterval * 1000;
$this->pollTimer = \Swoole\Timer::tick($intervalMs, function () {
$this->pollTimer = Timer::tick($intervalMs, function () {
if (!$this->running || $this->scanning) {
return;
}
$this->scanning = true;
try {
$newSnapshot = [];
$changedFiles = $this->compareSnapshots($newSnapshot);
if (!$this->running) {
return;
}
if (!empty($changedFiles)) {
$this->triggerCallback($changedFiles);
}
$this->fileSnapshot = $newSnapshot;
} finally {
$this->scanning = false;
}
});
}
+44 -6
View File
@@ -7,7 +7,6 @@ use Kiri\Error\StdoutLogger;
use Kiri\Events\EventProvider;
use Kiri\Router\Router;
use Kiri\Server\Events\OnWorkerStart;
use Kiri\Server\ServerInterface;
use Psr\Log\LoggerInterface;
use Swoole\Event;
use Swoole\Process;
@@ -16,6 +15,8 @@ use Kiri\Server\Processes\AbstractProcess;
class HotReload extends AbstractProcess
{
use ReloadWorkers;
/**
* @var mixed
@@ -77,10 +78,20 @@ class HotReload extends AbstractProcess
*/
public function onSigterm(): void
{
// TODO: Implement onSigterm() method.
$this->stop();
}
public function stop(): void
{
parent::stop();
if (isset($this->pipe) && is_resource($this->pipe)) {
@Event::del($this->pipe);
@fclose($this->pipe);
}
@Event::exit();
}
/**
* @param ?Process $process
*/
@@ -116,16 +127,43 @@ class HotReload extends AbstractProcess
di(StdoutLogger::class)->println('reloading server[' . \config('site.id', 'system-service') . '], please waite.');
$this->clear();
di(ServerInterface::class)->reload();
if (!$this->reloadWorkers()) {
di(StdoutLogger::class)->println('reload server failed: master pid not found or signal failed');
}
$this->addListen();
$this->reloading = false;
}
/**
* @return void
*/
private function isMasterProcessCommand(string $command): bool
{
$prefix = '[' . config('site.id', 'system-service') . '].Master[';
return str_contains($command, $prefix);
}
private function isSameAppProcess(int $pid): bool
{
$cwd = @readlink('/proc/' . $pid . '/cwd');
if ($cwd === false || $cwd === '') {
return false;
}
return $this->normalizePath($cwd) === $this->normalizePath(APP_PATH);
}
private function normalizePath(string $path): string
{
$real = realpath($path) ?: $path;
return rtrim(str_replace('\\', '/', $real), '/');
}
private function isProcessAlive(int $pid): bool
{
return $pid > 1 && @Process::kill($pid, 0);
}
protected function addListen(): void
{
foreach (config('servers.reload.listen') as $value) {
+115
View File
@@ -0,0 +1,115 @@
<?php
namespace Kiri\Server\Abstracts;
use Swoole\Process;
trait ReloadWorkers
{
private static ?int $cachedMasterPid = null;
/**
* @return void
*/
private function reloadWorkers(): bool
{
$pid = $this->getMasterPid();
if ($pid === null) {
return false;
}
return Process::kill($pid, SIGUSR1);
}
private function getMasterPid(): ?int
{
if (self::$cachedMasterPid !== null && $this->isCachedMasterPid(self::$cachedMasterPid)) {
return self::$cachedMasterPid;
}
self::$cachedMasterPid = null;
$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)) {
self::$cachedMasterPid = $pid;
return $pid;
}
}
return null;
}
private function isCachedMasterPid(int $pid): bool
{
if (!$this->isProcessAlive($pid)) {
return false;
}
$command = $this->readProcessCommand($pid);
return $command !== '' && $this->isMasterProcessCommand($command) && $this->isSameAppProcess($pid);
}
private function readProcessCommand(int $pid): string
{
$cmdline = @file_get_contents('/proc/' . $pid . '/cmdline');
if (is_string($cmdline) && $cmdline !== '') {
return trim(str_replace("\0", ' ', $cmdline));
}
return '';
}
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;
}
}
+87
View File
@@ -42,7 +42,17 @@ trait TraitServer
*/
public function onSigint($no, array $signInfo): void
{
static $handling = false;
if ($handling) {
return;
}
$handling = true;
try {
if (!$this->shouldHandleSigint()) {
return;
}
Kiri::getLogger()->alert('Pid ' . getmypid() . ' get signo ' . $no);
$this->shutdown();
} catch (\Throwable $exception) {
@@ -51,6 +61,80 @@ trait TraitServer
}
private function shouldHandleSigint(): bool
{
$currentPid = getmypid();
if ($this->isMasterProcess($currentPid)) {
return true;
}
$masterPid = $this->getVerifiedPidFileMasterPid();
return $masterPid !== null && $masterPid === $currentPid;
}
private function getVerifiedPidFileMasterPid(): ?int
{
$pidFile = function_exists('storage') ? storage('.swoole.pid') : '';
if (!is_file($pidFile)) {
return null;
}
$pid = (int)trim((string)file_get_contents($pidFile));
if ($pid <= 1 || !$this->isProcessAlive($pid) || !$this->isSameAppProcess($pid) || !$this->isMasterProcess($pid)) {
return null;
}
return $pid;
}
private function isMasterProcess(int $pid): bool
{
$command = $this->getProcessCommand($pid);
if ($command === '') {
return false;
}
$prefix = '[' . config('site.id', 'system-service') . '].Master[';
return str_contains($command, $prefix);
}
private function getProcessCommand(int $pid): string
{
$command = @file_get_contents('/proc/' . $pid . '/cmdline');
if (!is_string($command) || $command === '') {
return '';
}
return str_replace("\0", ' ', $command);
}
private function isSameAppProcess(int $pid): bool
{
$cwd = @readlink('/proc/' . $pid . '/cwd');
if ($cwd === false || $cwd === '') {
return false;
}
return $this->normalizePath($cwd) === $this->normalizePath(APP_PATH);
}
private function normalizePath(string $path): string
{
$real = realpath($path) ?: $path;
return rtrim(str_replace('\\', '/', $real), '/');
}
private function isProcessAlive(int $pid): bool
{
return $pid > 1 && @Process::kill($pid, 0);
}
/**
* @param $signal
* @param $callback
@@ -58,6 +142,9 @@ trait TraitServer
*/
private function onPcntlSignal($signal, $callback): void
{
if (function_exists('pcntl_async_signals')) {
pcntl_async_signals(true);
}
\pcntl_signal($signal, $callback);
}
+72
View File
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace Kiri\Server;
use Kiri\Di\HotReloadState;
use Kiri\Router\RouteArtifactState;
use Kiri\Router\Router;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
class FileBuildCommand extends Command
{
protected function configure(): void
{
$this->setName('sw:file-build')
->setDescription('build hot reload artifacts for changed files');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
defined('ROUTER_TYPE_HTTP') or define('ROUTER_TYPE_HTTP', 'http');
putenv('KIRI_FILE_BUILD=1');
$changedFiles = di(HotReloadState::class)->peek();
$startedAt = microtime(true);
try {
$syntaxError = $this->lintChangedFiles($changedFiles);
if ($syntaxError !== null) {
$output->writeln('<error>file build failed: ' . $syntaxError . '</error>');
return Command::FAILURE;
}
di(Router::class)->scan_build_route();
di(HotReloadState::class)->store($changedFiles);
di(RouteArtifactState::class)->markBuild(ROUTER_TYPE_HTTP, $changedFiles);
$elapsed = round((microtime(true) - $startedAt) * 1000, 2);
$output->writeln(sprintf('file build complete: %d changed files, %sms', count($changedFiles), $elapsed));
return Command::SUCCESS;
} catch (Throwable $throwable) {
if (class_exists('Kiri')) {
\Kiri::getLogger()->json_log($throwable);
}
$output->writeln('<error>file build failed: ' . $throwable->getMessage() . '</error>');
return Command::FAILURE;
} finally {
putenv('KIRI_FILE_BUILD');
}
}
private function lintChangedFiles(array $changedFiles): ?string
{
foreach ($changedFiles as $file) {
if (!is_string($file) || !str_ends_with($file, '.php') || !is_file($file)) {
continue;
}
$output = [];
$returnCode = 0;
exec(escapeshellarg(PHP_BINARY ?: 'php') . ' -l ' . escapeshellarg($file) . ' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
return implode("\n", $output);
}
}
return null;
}
}
+5
View File
@@ -11,6 +11,8 @@ use Kiri\Server\Events\OnBeforeShutdown;
use Kiri\Server\Events\OnShutdown;
use Kiri\Server\Events\OnStart;
use Swoole\Server as SServer;
use Swoole\Process;
use const SIGINT;
/**
@@ -35,6 +37,9 @@ class OnServer extends Server
public function onStart(SServer $server): void
{
Kiri::setProcessName(sprintf('Master[%d]', $server->master_pid));
Process::signal(SIGINT, static function () use ($server): void {
$server->shutdown();
});
event(new OnStart($server));
}
+20 -7
View File
@@ -6,6 +6,7 @@ namespace Kiri\Server\Processes;
use Swoole\Coroutine;
use Swoole\Process;
use const SIGHUP;
use const SIGINT;
use const SIGTERM;
/**
@@ -16,6 +17,8 @@ abstract class AbstractProcess implements OnProcessInterface
private bool $stop = false;
private bool $stopping = false;
public Process $process;
@@ -131,9 +134,11 @@ abstract class AbstractProcess implements OnProcessInterface
$array['deadlock_check_disable_trace'] = false;
$array['exit_condition'] = [$this, 'exit_condition'];
Coroutine::set($array);
$process::signal(SIGINT, static function (): void {});
Coroutine::create(fn() => $this->coroutineWaitSignal());
} else {
$process::signal(SIGTERM | SIGINT | SIGUSR1, [$this, 'pointWaitSignal']);
$process::signal(SIGTERM, [$this, 'pointWaitSignal']);
$process::signal(SIGINT, static function (): void {});
}
return $this;
}
@@ -151,9 +156,7 @@ abstract class AbstractProcess implements OnProcessInterface
*/
public function pointWaitSignal($signal): void
{
$this->stop = true;
$this->onSigterm();
$this->requestStop();
}
@@ -162,10 +165,20 @@ abstract class AbstractProcess implements OnProcessInterface
*/
public function coroutineWaitSignal(): void
{
$value = Coroutine::waitSignal(SIGTERM);
if ($value) {
$this->stop = true;
Coroutine::waitSignal(SIGTERM);
$this->requestStop();
}
private function requestStop(): void
{
if ($this->stopping) {
return;
}
$this->stopping = true;
$this->stop = true;
$this->onSigterm();
}
+37
View File
@@ -5,6 +5,8 @@ namespace Kiri\Server\Processes;
use Exception;
use Kiri;
use Swoole\Process;
use const SIGKILL;
use const SIGTERM;
trait TraitProcess
{
@@ -66,4 +68,39 @@ trait TraitProcess
{
return $this->_process;
}
/**
* @return void
*/
private function terminateProcesses(): void
{
$pids = [];
foreach ($this->_process as $process) {
$pid = (int)($process->pid ?? 0);
if ($pid > 1 && $pid !== getmypid()) {
$pids[] = $pid;
}
}
$pids = array_values(array_unique($pids));
foreach ($pids as $pid) {
if (@Process::kill($pid, 0)) {
@Process::kill($pid, SIGTERM);
}
}
for ($i = 0; $i < 10; $i++) {
$alive = array_values(array_filter($pids, static fn(int $pid): bool => @Process::kill($pid, 0)));
if ($alive === []) {
return;
}
usleep(100000);
}
foreach ($pids as $pid) {
if (@Process::kill($pid, 0)) {
@Process::kill($pid, SIGKILL);
}
}
}
}
+6 -2
View File
@@ -133,9 +133,13 @@ class ServerCommand extends Command
protected function start(InputInterface $input): int
{
$this->asyncServer->addProcess(config('process', []));
if (\config('servers.reload.hot', false) === true) {
$hotReload = \config('servers.reload.hot', false) === true;
if ($hotReload) {
$this->asyncServer->addProcess([FileWatcher::class]);
} else {
}
if (!$hotReload) {
// 非热更模式可在 Master 进程预扫描,Worker 通过 fork 继承扫描结果。
// 热更模式必须让新 Worker 自己加载业务类,避免继承旧类定义后无法重新声明。
di(Router::class)->scan_build_route();
}
$this->asyncServer->initCoreServers(config('servers.server', []), (int)$input->getOption('daemon'));
+2
View File
@@ -21,8 +21,10 @@ class ServerProviders extends Providers
public function onImport(): void
{
$server = $this->container->get(ServerCommand::class);
$builder = $this->container->get(FileBuildCommand::class);
$console = $this->container->get(Application::class);
$console->addCommand($server);
$console->addCommand($builder);
}
}
+176 -5
View File
@@ -31,9 +31,13 @@ class State extends Component
*/
public function isRunner(): bool
{
if ($this->getPidFilePid() !== null || $this->getNamedServerPids() !== []) {
return true;
}
$ports = $this->sortService($this->servers);
foreach ($ports as $config) {
if (checkPortIsAlready($config['port'])) {
if (checkPortIsAlready($config->port)) {
return true;
}
}
@@ -47,13 +51,180 @@ class State extends Component
*/
public function exit($port): void
{
if (!($pid = checkPortIsAlready($port))) {
$pids = $this->collectStopPids((int)$port);
if ($pids === []) {
return;
}
while (checkPortIsAlready($port)) {
Process::kill($pid, 0) && Process::kill($pid, SIGTERM);
usleep(300);
$this->terminatePids($pids, SIGTERM, 30);
$remaining = array_values(array_filter($pids, [$this, 'isProcessAlive']));
if ($remaining !== []) {
$this->terminatePids($remaining, SIGKILL, 10);
}
if (!checkPortIsAlready((int)$port)) {
@unlink(storage('.swoole.pid'));
}
}
private function collectStopPids(int $port): array
{
$pids = [];
$pidFilePid = $this->getPidFilePid();
if ($pidFilePid !== null) {
$pids[] = $pidFilePid;
$pids = array_merge($pids, $this->getDescendantPids($pidFilePid));
}
$pids = array_merge($pids, $this->getNamedServerPids());
$portPid = checkPortIsAlready($port);
if ($portPid !== false) {
$pids[] = (int)$portPid;
$pids = array_merge($pids, $this->getDescendantPids((int)$portPid));
}
$currentPid = getmypid();
$pids = array_values(array_unique(array_filter(array_map('intval', $pids), function (int $pid) use ($currentPid) {
return $pid > 1 && $pid !== $currentPid;
})));
rsort($pids);
return $pids;
}
private function terminatePids(array $pids, int $signal, int $rounds): void
{
for ($i = 0; $i < $rounds; $i++) {
$alive = false;
foreach ($pids as $pid) {
if (!$this->isProcessAlive($pid)) {
continue;
}
$alive = true;
@Process::kill($pid, $signal);
}
if (!$alive) {
return;
}
usleep(100000);
}
}
private function getPidFilePid(): ?int
{
$pidFile = storage('.swoole.pid');
if (!is_file($pidFile)) {
return null;
}
$pid = (int)trim((string)file_get_contents($pidFile));
if ($pid <= 1 || !$this->isProcessAlive($pid) || !$this->isSameAppProcess($pid)) {
return null;
}
return $pid;
}
private function getDescendantPids(int $parentPid): array
{
$processes = $this->listProcesses();
$children = [];
foreach ($processes as $process) {
$children[(int)$process['ppid']][] = (int)$process['pid'];
}
$result = [];
$stack = [$parentPid];
while ($stack !== []) {
$pid = array_pop($stack);
foreach ($children[$pid] ?? [] as $childPid) {
$result[] = $childPid;
$stack[] = $childPid;
}
}
return $result;
}
private function getNamedServerPids(): array
{
$siteId = '[' . config('site.id', 'system-service') . ']';
$pids = [];
foreach ($this->listProcesses() as $process) {
$command = $process['command'];
if (!str_contains($command, $siteId)) {
continue;
}
if (!preg_match('/\\]\\..+\\[[0-9]+\\]/', $command)) {
continue;
}
if (!$this->isSameAppProcess((int)$process['pid'])) {
continue;
}
$pids[] = (int)$process['pid'];
}
return $pids;
}
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 isSameAppProcess(int $pid): bool
{
$cwd = @readlink('/proc/' . $pid . '/cwd');
if ($cwd === false || $cwd === '') {
return false;
}
return $this->normalizePath($cwd) === $this->normalizePath(APP_PATH);
}
private function normalizePath(string $path): string
{
$real = realpath($path) ?: $path;
return rtrim(str_replace('\\', '/', $real), '/');
}
private function isProcessAlive(int $pid): bool
{
return $pid > 1 && @Process::kill($pid, 0);
}
}