Compare commits
38 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3fe9ab06c3 | |||
| a61e83ff6a | |||
| 55d50b7bff | |||
| f6219a5c5d | |||
| acc966c3df | |||
| 614e943845 | |||
| 27ffa05515 | |||
| 1f443958e8 | |||
| 77e9333651 | |||
| 56ebbd2a2e | |||
| 7f36bb0d53 | |||
| 0adfe14a1f | |||
| 3ca39d2205 | |||
| 908c8719d3 | |||
| 69b845d924 | |||
| d9c8344a29 | |||
| ced9f89ebe | |||
| ee487649fa | |||
| 0cdb100180 | |||
| a9f1afb866 | |||
| 853a9661bc | |||
| 2d4951b0dd | |||
| e819fe9ba4 | |||
| 9e1e16dca9 | |||
| 77cf882f2e | |||
| eeb925b5b9 | |||
| 59042c0110 | |||
| 7c459cc9bc | |||
| 968cdbd11a | |||
| 37b59c8536 | |||
| 9376a73628 | |||
| eebaf63999 | |||
| e399837dad | |||
| 7b8a43f94f | |||
| c0f8133926 | |||
| f533d3262b | |||
| c767a1745a | |||
| 251e05dbf7 |
+150
-141
@@ -9,7 +9,6 @@ use Kiri\Exception\NotFindClassException;
|
|||||||
use Kiri\Server\Config as SConfig;
|
use Kiri\Server\Config as SConfig;
|
||||||
use Kiri\Server\Constant;
|
use Kiri\Server\Constant;
|
||||||
use Kiri\Server\Events\OnServerBeforeStart;
|
use Kiri\Server\Events\OnServerBeforeStart;
|
||||||
use Kiri\Server\Events\OnShutdown;
|
|
||||||
use Kiri\Server\Handler\OnServer;
|
use Kiri\Server\Handler\OnServer;
|
||||||
use Kiri\Server\Processes\TraitProcess;
|
use Kiri\Server\Processes\TraitProcess;
|
||||||
use Kiri\Server\ServerInterface;
|
use Kiri\Server\ServerInterface;
|
||||||
@@ -23,164 +22,174 @@ use Swoole\Server;
|
|||||||
class AsyncServer extends Component implements ServerInterface
|
class AsyncServer extends Component implements ServerInterface
|
||||||
{
|
{
|
||||||
|
|
||||||
use TraitServer;
|
use TraitServer;
|
||||||
use TraitProcess;
|
use TraitProcess;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @var Server|null
|
* @var Server|null
|
||||||
*/
|
*/
|
||||||
private ?Server $server = null;
|
private ?Server $server = null;
|
||||||
|
|
||||||
|
private bool $shuttingDown = false;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array $service
|
* @param array $service
|
||||||
* @param int $daemon
|
* @param int $daemon
|
||||||
* @return void
|
* @return void
|
||||||
* @throws
|
* @throws
|
||||||
*/
|
*/
|
||||||
public function initCoreServers(array $service, int $daemon = 0): void
|
public function initCoreServers(array $service, int $daemon = 0): void
|
||||||
{
|
{
|
||||||
$service = $this->createBaseServer($this->genConfigService($service), $daemon);
|
$service = $this->createBaseServer($this->genConfigService($service), $daemon);
|
||||||
if (isset($this->server->setting[Constant::OPTION_TASK_WORKER_NUM])) {
|
if (isset($this->server->setting[Constant::OPTION_TASK_WORKER_NUM])) {
|
||||||
$this->container->get(Task::class)->initTaskWorker($this->server);
|
$this->container->get(Task::class)->initTaskWorker($this->server);
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($this->_process as $process) $this->server->addProcess($process);
|
foreach ($this->_process as $process)
|
||||||
foreach ($service as $value) $this->addListener($value);
|
$this->server->addProcess($process);
|
||||||
|
foreach ($service as $value)
|
||||||
|
$this->addListener($value);
|
||||||
|
|
||||||
$this->provider->on(OnServerBeforeStart::class, [$this, 'onSignal']);
|
$this->provider->on(OnServerBeforeStart::class, [$this, 'onSignal']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return bool
|
* @return bool
|
||||||
* @throws
|
* @throws
|
||||||
*/
|
*/
|
||||||
public function shutdown(): bool
|
public function shutdown(): bool
|
||||||
{
|
{
|
||||||
$this->server->shutdown();
|
if ($this->shuttingDown) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
$this->shuttingDown = true;
|
||||||
|
|
||||||
$this->dispatch->dispatch(new OnShutdown());
|
$this->terminateProcesses();
|
||||||
|
|
||||||
return true;
|
if ($this->server !== null) {
|
||||||
}
|
$this->server->shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $service
|
||||||
|
* @param int $daemon
|
||||||
|
* @return array
|
||||||
|
* @throws ContainerExceptionInterface
|
||||||
|
* @throws NotFindClassException
|
||||||
|
* @throws NotFoundExceptionInterface
|
||||||
|
*/
|
||||||
|
private function createBaseServer(array $service, int $daemon = 0): array
|
||||||
|
{
|
||||||
|
$config = array_pop($service);
|
||||||
|
|
||||||
|
$match = $this->getServerClass($config->type);
|
||||||
|
if (is_null($match)) {
|
||||||
|
throw new NotFindClassException('Unknown server type ' . $config->type);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->container->get(StdoutLogger::class)->println('Listen address ' . $config->type . ' ' . $config->host . '::' . $config->port);
|
||||||
|
|
||||||
|
$this->server = new $match($config->host, $config->port, $config->mode, $config->socket);
|
||||||
|
$this->server->set($this->systemConfig($config, $daemon));
|
||||||
|
if (!isset($config->events[Constant::SHUTDOWN])) {
|
||||||
|
$config->events[Constant::SHUTDOWN] = [OnServer::class, 'onShutdown'];
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->event($this->server, array_merge(\config('servers.server.events', []), $config->events));
|
||||||
|
$this->container->bind(ServerInterface::class, $this->server);
|
||||||
|
return $service;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array $service
|
* @param SConfig $config
|
||||||
* @param int $daemon
|
* @param int $daemon
|
||||||
* @return array
|
* @return array
|
||||||
* @throws ContainerExceptionInterface
|
* @throws
|
||||||
* @throws NotFindClassException
|
*/
|
||||||
* @throws NotFoundExceptionInterface
|
protected function systemConfig(SConfig $config, int $daemon): array
|
||||||
*/
|
{
|
||||||
private function createBaseServer(array $service, int $daemon = 0): array
|
$settings = array_merge(\config('servers.server.settings', []), $config->settings);
|
||||||
{
|
$settings[Constant::OPTION_DAEMONIZE] = (bool)$daemon;
|
||||||
$config = array_pop($service);
|
$settings[Constant::OPTION_ENABLE_REUSE_PORT] = true;
|
||||||
|
$settings[Constant::OPTION_PID_FILE] = storage('.swoole.pid');
|
||||||
$match = $this->getServerClass($config->type);
|
if (!isset($settings[Constant::OPTION_LOG_FILE])) {
|
||||||
if (is_null($match)) {
|
$settings[Constant::OPTION_LOG_FILE] = storage('system.log');
|
||||||
throw new NotFindClassException('Unknown server type ' . $config->type);
|
}
|
||||||
}
|
return $settings;
|
||||||
|
}
|
||||||
$this->container->get(StdoutLogger::class)->println('Listen address ' . $config->host . '::' . $config->port);
|
|
||||||
|
|
||||||
$this->server = new $match($config->host, $config->port, $config->mode, $config->socket);
|
|
||||||
$this->server->set($this->systemConfig($config, $daemon));
|
|
||||||
if (!isset($config->events[Constant::SHUTDOWN])) {
|
|
||||||
$config->events[Constant::SHUTDOWN] = [OnServer::class, 'onShutdown'];
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->event($this->server, array_merge(\config('server.events', []), $config->events));
|
|
||||||
$this->container->bind(ServerInterface::class, $this->server);
|
|
||||||
return $service;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param SConfig $config
|
* @param SConfig $config
|
||||||
* @param int $daemon
|
* @return void
|
||||||
* @return array
|
* @throws
|
||||||
* @throws
|
*/
|
||||||
*/
|
public function addListener(SConfig $config): void
|
||||||
protected function systemConfig(SConfig $config, int $daemon): array
|
{
|
||||||
{
|
$port = $this->server->addlistener($config->host, $config->port, $config->socket);
|
||||||
$settings = array_merge(\config('server.settings', []), $config->settings);
|
if ($port === false) {
|
||||||
$settings[Constant::OPTION_DAEMONIZE] = (bool)$daemon;
|
throw new Exception('Listen port fail.' . swoole_last_error());
|
||||||
$settings[Constant::OPTION_ENABLE_REUSE_PORT] = true;
|
}
|
||||||
$settings[Constant::OPTION_PID_FILE] = storage('.swoole.pid');
|
$port->set($this->resetSettings($config->type, $config->settings));
|
||||||
if (!isset($settings[Constant::OPTION_PID_FILE])) {
|
$this->event($port, $config->getEvents());
|
||||||
$settings[Constant::OPTION_LOG_FILE] = storage('system.log');
|
|
||||||
}
|
$this->container->get(StdoutLogger::class)->println('Listen address ' . $config->type . ' ' . $config->host . '::' . $config->port);
|
||||||
return $settings;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param SConfig $config
|
* @param string $type
|
||||||
* @return void
|
* @param array $settings
|
||||||
* @throws
|
* @return array
|
||||||
*/
|
* @throws
|
||||||
public function addListener(SConfig $config): void
|
*/
|
||||||
{
|
private function resetSettings(string $type, array $settings): array
|
||||||
$port = $this->server->addlistener($config->host, $config->port, $config->socket);
|
{
|
||||||
if ($port === false) {
|
if ($type == Constant::SERVER_TYPE_HTTP && !isset($settings['open_http_protocol'])) {
|
||||||
throw new Exception('Listen port fail.' . swoole_last_error());
|
$settings['open_http_protocol'] = true;
|
||||||
}
|
if (in_array($this->server->setting['dispatch_mode'], [2, 4])) {
|
||||||
$port->set($this->resetSettings($config->type, $config->settings));
|
$settings['open_http2_protocol'] = true;
|
||||||
$this->event($port, $config->getEvents());
|
}
|
||||||
|
}
|
||||||
$this->container->get(StdoutLogger::class)->println('Listen address ' . $config->host . '::' . $config->port);
|
if ($type == Constant::SERVER_TYPE_WEBSOCKET && !isset($settings['open_websocket_protocol'])) {
|
||||||
}
|
$settings['open_websocket_protocol'] = true;
|
||||||
|
}
|
||||||
|
return $settings;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param string $type
|
* @param Server\Port|Server $base
|
||||||
* @param array $settings
|
* @param array $events
|
||||||
* @return array
|
* @return void
|
||||||
* @throws
|
* @throws
|
||||||
*/
|
*/
|
||||||
private function resetSettings(string $type, array $settings): array
|
private function event(Server\Port|Server $base, array $events): void
|
||||||
{
|
{
|
||||||
if ($type == Constant::SERVER_TYPE_HTTP && !isset($settings['open_http_protocol'])) {
|
$container = $this->container;
|
||||||
$settings['open_http_protocol'] = true;
|
foreach ($events as $name => $event) {
|
||||||
if (in_array($this->server->setting['dispatch_mode'], [2, 4])) {
|
if (is_array($event) && is_string($event[0])) {
|
||||||
$settings['open_http2_protocol'] = true;
|
$event[0] = $container->get($event[0]);
|
||||||
}
|
}
|
||||||
}
|
$base->on($name, $event);
|
||||||
if ($type == Constant::SERVER_TYPE_WEBSOCKET && !isset($settings['open_websocket_protocol'])) {
|
}
|
||||||
$settings['open_websocket_protocol'] = true;
|
}
|
||||||
}
|
|
||||||
return $settings;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param Server\Port|Server $base
|
* @return void
|
||||||
* @param array $events
|
* @throws
|
||||||
* @return void
|
*/
|
||||||
* @throws
|
public function start(): void
|
||||||
*/
|
{
|
||||||
private function event(Server\Port|Server $base, array $events): void
|
$this->dispatch->dispatch(new OnServerBeforeStart);
|
||||||
{
|
$this->server->start();
|
||||||
$container = $this->container;
|
}
|
||||||
foreach ($events as $name => $event) {
|
|
||||||
if (is_array($event) && is_string($event[0])) {
|
|
||||||
$event[0] = $container->get($event[0]);
|
|
||||||
}
|
|
||||||
$base->on($name, $event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return void
|
|
||||||
* @throws
|
|
||||||
*/
|
|
||||||
public function start(): void
|
|
||||||
{
|
|
||||||
$this->dispatch->dispatch(new OnServerBeforeStart());
|
|
||||||
$this->server->start();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,565 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Kiri\Server\Abstracts;
|
||||||
|
|
||||||
|
use Kiri\Di\HotReloadState;
|
||||||
|
use Kiri\Di\Inject\Container;
|
||||||
|
use Kiri\Error\StdoutLogger;
|
||||||
|
use Kiri\Events\EventProvider;
|
||||||
|
use Kiri\Router\Router;
|
||||||
|
use Kiri\Server\Events\OnWorkerStart;
|
||||||
|
use Kiri\Server\Processes\AbstractProcess;
|
||||||
|
use Kiri\Server\Processes\OnProcessInterface;
|
||||||
|
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)]
|
||||||
|
public StdoutLogger|LoggerInterface $logger;
|
||||||
|
|
||||||
|
protected bool $enable_coroutine = false;
|
||||||
|
|
||||||
|
protected array $watches = [];
|
||||||
|
|
||||||
|
protected bool $enable_queue = false;
|
||||||
|
|
||||||
|
protected bool $reloading = false;
|
||||||
|
|
||||||
|
private array $watchPaths = [];
|
||||||
|
private array $excludePatterns = [];
|
||||||
|
private array $extensions = ['php'];
|
||||||
|
private string $strategy;
|
||||||
|
private bool $running = false;
|
||||||
|
private bool $scanning = false;
|
||||||
|
|
||||||
|
private mixed $inotifyFd = null;
|
||||||
|
private array $inotifyWatchMap = [];
|
||||||
|
private mixed $fswatchProcess = null;
|
||||||
|
private array $fswatchPipes = [];
|
||||||
|
private int $pollInterval = 2;
|
||||||
|
private array $fileSnapshot = [];
|
||||||
|
private int $pollTimer = -1;
|
||||||
|
private int $debounceTimer = -1;
|
||||||
|
private int $debounceMs = 200;
|
||||||
|
private int $minReloadIntervalMs = 1000;
|
||||||
|
private int $lastReloadAtMs = 0;
|
||||||
|
|
||||||
|
private const string STRATEGY_INOTIFY = 'inotify';
|
||||||
|
private const string STRATEGY_FSWATCH = 'fswatch';
|
||||||
|
private const string STRATEGY_POLL = 'poll';
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->watchPaths = config('servers.reload.listen', []);
|
||||||
|
$this->excludePatterns = config('servers.reload.scan.skip_patterns', []);
|
||||||
|
$this->extensions = config('servers.reload.scan.extensions', ['php']);
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getName(): string
|
||||||
|
{
|
||||||
|
return 'hotReload';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function onSigterm(): void
|
||||||
|
{
|
||||||
|
$this->stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function detectBestStrategy(): string
|
||||||
|
{
|
||||||
|
$forced = config('servers.reload.scan.strategy', 'auto');
|
||||||
|
if (in_array($forced, [self::STRATEGY_INOTIFY, self::STRATEGY_FSWATCH, self::STRATEGY_POLL], true)) {
|
||||||
|
return $forced;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->isMountedWindowsPath()) {
|
||||||
|
return $this->isFswatchAvailable() ? self::STRATEGY_FSWATCH : self::STRATEGY_POLL;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (extension_loaded('inotify')) {
|
||||||
|
return self::STRATEGY_INOTIFY;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->isFswatchAvailable()) {
|
||||||
|
return self::STRATEGY_FSWATCH;
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::STRATEGY_POLL;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function isMountedWindowsPath(): bool
|
||||||
|
{
|
||||||
|
foreach ($this->watchPaths as $path) {
|
||||||
|
$real = realpath($path) ?: (string)$path;
|
||||||
|
$real = str_replace('\\', '/', $real);
|
||||||
|
if (str_starts_with($real, '/mnt/')) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function isFswatchAvailable(): bool
|
||||||
|
{
|
||||||
|
$output = [];
|
||||||
|
$returnVar = 0;
|
||||||
|
exec('which fswatch 2>/dev/null', $output, $returnVar);
|
||||||
|
return $returnVar === 0 && !empty($output[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setDebounce(int $milliseconds): self
|
||||||
|
{
|
||||||
|
$this->debounceMs = $milliseconds;
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setPollInterval(int $seconds): self
|
||||||
|
{
|
||||||
|
$this->pollInterval = $seconds;
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function process(Process|null $process): void
|
||||||
|
{
|
||||||
|
if (class_exists('\\Swoole\\Coroutine')) {
|
||||||
|
Coroutine::set(['enable_deadlock_check' => false]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->running) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->running = true;
|
||||||
|
|
||||||
|
switch ($this->strategy) {
|
||||||
|
case self::STRATEGY_INOTIFY:
|
||||||
|
$this->startInotify();
|
||||||
|
break;
|
||||||
|
case self::STRATEGY_FSWATCH:
|
||||||
|
$this->startFswatch();
|
||||||
|
break;
|
||||||
|
case self::STRATEGY_POLL:
|
||||||
|
$this->startPolling();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
Event::wait();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function stop(): void
|
||||||
|
{
|
||||||
|
$this->running = false;
|
||||||
|
|
||||||
|
if ($this->inotifyFd && is_resource($this->inotifyFd)) {
|
||||||
|
@Event::del($this->inotifyFd);
|
||||||
|
@fclose($this->inotifyFd);
|
||||||
|
$this->inotifyFd = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 ($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) {
|
||||||
|
if (strpos($path, $pattern) !== false) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function hasValidExtension(string $path): bool
|
||||||
|
{
|
||||||
|
if (empty($this->extensions)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$ext = pathinfo($path, PATHINFO_EXTENSION);
|
||||||
|
return in_array($ext, $this->extensions, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function triggerCallback(array $changedFiles): void
|
||||||
|
{
|
||||||
|
$changedFiles = array_filter($changedFiles, function ($file) {
|
||||||
|
return !$this->isExcluded($file) && $this->hasValidExtension($file);
|
||||||
|
})
|
||||||
|
|> array_unique(...)
|
||||||
|
|> array_values(...);
|
||||||
|
|
||||||
|
if (empty($changedFiles)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->debounceTimer > 0) {
|
||||||
|
Timer::clear($this->debounceTimer);
|
||||||
|
}
|
||||||
|
|
||||||
|
$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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function reload(array $changedFiles): void
|
||||||
|
{
|
||||||
|
if ($this->reloading) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$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);
|
||||||
|
|
||||||
|
if (!$this->reloadWorkers()) {
|
||||||
|
di(StdoutLogger::class)->println('reload server failed: master pid not found or signal failed');
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
$this->reloading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
stream_set_blocking($this->inotifyFd, false);
|
||||||
|
|
||||||
|
foreach ($this->watchPaths as $path) {
|
||||||
|
$this->addInotifyWatchRecursive($path);
|
||||||
|
}
|
||||||
|
|
||||||
|
Event::add($this->inotifyFd, function ($fd) {
|
||||||
|
if (!$this->running) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$events = inotify_read($fd);
|
||||||
|
if ($events === false) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$changedFiles = [];
|
||||||
|
foreach ($events as $event) {
|
||||||
|
$wd = $event['wd'];
|
||||||
|
$dir = $this->inotifyWatchMap[$wd] ?? '';
|
||||||
|
$name = $event['name'] ?? '';
|
||||||
|
$filePath = $name === '' ? $dir : $dir . '/' . $name;
|
||||||
|
|
||||||
|
if (($event['mask'] & IN_CREATE) && $filePath !== '' && is_dir($filePath) && !$this->isExcluded($filePath)) {
|
||||||
|
$this->addInotifyWatchRecursive($filePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($filePath !== '') {
|
||||||
|
$changedFiles[] = $filePath;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->triggerCallback($changedFiles);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function addInotifyWatchRecursive(string $path): void
|
||||||
|
{
|
||||||
|
if ($this->isExcluded($path)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_file($path)) {
|
||||||
|
if ($this->hasValidExtension($path)) {
|
||||||
|
$wd = inotify_add_watch($this->inotifyFd, $path, IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
|
||||||
|
$this->inotifyWatchMap[$wd] = dirname($path);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!is_dir($path)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$wd = inotify_add_watch($this->inotifyFd, $path, IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
|
||||||
|
$this->inotifyWatchMap[$wd] = $path;
|
||||||
|
|
||||||
|
$items = scandir($path);
|
||||||
|
foreach ($items as $item) {
|
||||||
|
if ($item === '.' || $item === '..') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$full = $path . '/' . $item;
|
||||||
|
if (is_dir($full)) {
|
||||||
|
$this->addInotifyWatchRecursive($full);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function startFswatch(): void
|
||||||
|
{
|
||||||
|
$descriptorspec = [
|
||||||
|
0 => ['pipe', 'r'],
|
||||||
|
1 => ['pipe', 'w'],
|
||||||
|
2 => ['pipe', 'w'],
|
||||||
|
];
|
||||||
|
|
||||||
|
$excludeArgs = [];
|
||||||
|
foreach ($this->excludePatterns as $pattern) {
|
||||||
|
$excludeArgs[] = '--exclude';
|
||||||
|
$excludeArgs[] = '.*' . preg_quote($pattern, '/') . '.*';
|
||||||
|
}
|
||||||
|
|
||||||
|
$filterArgs = [];
|
||||||
|
foreach ($this->extensions as $ext) {
|
||||||
|
$filterArgs[] = '--include';
|
||||||
|
$filterArgs[] = '\.' . $ext . '$';
|
||||||
|
}
|
||||||
|
|
||||||
|
$cmd = 'fswatch -0 -r ' . implode(' ', array_merge($excludeArgs, $filterArgs)) . ' ' . implode(' ', array_map('escapeshellarg', $this->watchPaths));
|
||||||
|
|
||||||
|
$this->fswatchProcess = proc_open($cmd, $descriptorspec, $this->fswatchPipes);
|
||||||
|
if (!is_resource($this->fswatchProcess)) {
|
||||||
|
throw new \RuntimeException('Failed to start fswatch process');
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
$files = explode("\0", trim($data, "\0"));
|
||||||
|
$changedFiles = array_values(array_filter($files, function ($file) {
|
||||||
|
return $file !== '';
|
||||||
|
}));
|
||||||
|
|
||||||
|
$this->triggerCallback($changedFiles);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function startPolling(): void
|
||||||
|
{
|
||||||
|
$this->buildFileSnapshot();
|
||||||
|
|
||||||
|
$intervalMs = $this->pollInterval * 1000;
|
||||||
|
$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;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function buildFileSnapshot(): void
|
||||||
|
{
|
||||||
|
$this->fileSnapshot = [];
|
||||||
|
foreach ($this->watchPaths as $path) {
|
||||||
|
$this->scanDirectory($path, $this->fileSnapshot);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function scanDirectory(string $path, array &$snapshot): void
|
||||||
|
{
|
||||||
|
if ($this->isExcluded($path)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_file($path)) {
|
||||||
|
if ($this->hasValidExtension($path)) {
|
||||||
|
$snapshot[$path] = filemtime($path);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!is_dir($path)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$items = scandir($path);
|
||||||
|
foreach ($items as $item) {
|
||||||
|
if ($item === '.' || $item === '..') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$full = $path . '/' . $item;
|
||||||
|
$this->scanDirectory($full, $snapshot);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function compareSnapshots(array &$newSnapshot): array
|
||||||
|
{
|
||||||
|
$changed = [];
|
||||||
|
|
||||||
|
foreach ($this->watchPaths as $path) {
|
||||||
|
$this->scanDirectory($path, $newSnapshot);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($newSnapshot as $file => $mtime) {
|
||||||
|
if (!isset($this->fileSnapshot[$file])) {
|
||||||
|
$changed[] = $file;
|
||||||
|
} elseif ($this->fileSnapshot[$file] !== $mtime) {
|
||||||
|
$changed[] = $file;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($this->fileSnapshot as $file => $mtime) {
|
||||||
|
if (!isset($newSnapshot[$file])) {
|
||||||
|
$changed[] = $file;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $changed;
|
||||||
|
}
|
||||||
|
}
|
||||||
+166
-128
@@ -7,7 +7,6 @@ use Kiri\Error\StdoutLogger;
|
|||||||
use Kiri\Events\EventProvider;
|
use Kiri\Events\EventProvider;
|
||||||
use Kiri\Router\Router;
|
use Kiri\Router\Router;
|
||||||
use Kiri\Server\Events\OnWorkerStart;
|
use Kiri\Server\Events\OnWorkerStart;
|
||||||
use Kiri\Server\ServerInterface;
|
|
||||||
use Psr\Log\LoggerInterface;
|
use Psr\Log\LoggerInterface;
|
||||||
use Swoole\Event;
|
use Swoole\Event;
|
||||||
use Swoole\Process;
|
use Swoole\Process;
|
||||||
@@ -16,156 +15,195 @@ use Kiri\Server\Processes\AbstractProcess;
|
|||||||
class HotReload extends AbstractProcess
|
class HotReload extends AbstractProcess
|
||||||
{
|
{
|
||||||
|
|
||||||
|
use ReloadWorkers;
|
||||||
/**
|
|
||||||
* @var mixed
|
|
||||||
*/
|
|
||||||
protected mixed $pipe;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @var LoggerInterface|StdoutLogger
|
* @var mixed
|
||||||
*/
|
*/
|
||||||
#[Container(LoggerInterface::class)]
|
protected mixed $pipe;
|
||||||
public StdoutLogger|LoggerInterface $logger;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @var bool
|
* @var LoggerInterface|StdoutLogger
|
||||||
*/
|
*/
|
||||||
protected bool $enable_coroutine = false;
|
#[Container(LoggerInterface::class)]
|
||||||
|
public StdoutLogger|LoggerInterface $logger;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @var array
|
* @var bool
|
||||||
*/
|
*/
|
||||||
protected array $watches = [];
|
protected bool $enable_coroutine = false;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @var bool
|
* @var array
|
||||||
*/
|
*/
|
||||||
protected bool $enable_queue = false;
|
protected array $watches = [];
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @var bool
|
* @var bool
|
||||||
*/
|
*/
|
||||||
protected bool $reloading = false;
|
protected bool $enable_queue = false;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @throws \Exception
|
* @var bool
|
||||||
*/
|
*/
|
||||||
public function __construct()
|
protected bool $reloading = false;
|
||||||
{
|
|
||||||
di(EventProvider::class)->on(OnWorkerStart::class, [di(Router::class), 'scan_build_route']);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return string
|
* @throws \Exception
|
||||||
*/
|
*/
|
||||||
public function getName(): string
|
public function __construct()
|
||||||
{
|
{
|
||||||
return 'hotReload';
|
di(EventProvider::class)->on(OnWorkerStart::class, [di(Router::class), 'scan_build_route']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return void
|
* @return string
|
||||||
*/
|
*/
|
||||||
public function onSigterm(): void
|
public function getName(): string
|
||||||
{
|
{
|
||||||
// TODO: Implement onSigterm() method.
|
return 'hotReload';
|
||||||
$this->stop();
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param ?Process $process
|
|
||||||
*/
|
|
||||||
public function process(Process|null $process): void
|
|
||||||
{
|
|
||||||
$this->pipe = inotify_init();
|
|
||||||
$this->addListen();
|
|
||||||
Event::add($this->pipe, function () use ($process) {
|
|
||||||
$read = inotify_read($this->pipe);
|
|
||||||
if (count($read) > 0) {
|
|
||||||
$this->reload();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Event::cycle(function (): void {
|
|
||||||
if ($this->isStop()) {
|
|
||||||
Event::exit();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Event::wait();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function reload(): void
|
public function onSigterm(): void
|
||||||
{
|
{
|
||||||
if ($this->reloading) {
|
$this->stop();
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
$this->reloading = true;
|
|
||||||
|
|
||||||
di(StdoutLogger::class)->println('reloading server[' . \config('id', 'system-service') . '], please waite.');
|
|
||||||
|
|
||||||
$this->clear();
|
|
||||||
di(ServerInterface::class)->reload();
|
|
||||||
$this->addListen();
|
|
||||||
|
|
||||||
$this->reloading = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
public function stop(): void
|
||||||
* @return void
|
{
|
||||||
*/
|
parent::stop();
|
||||||
protected function addListen(): void
|
if (isset($this->pipe) && is_resource($this->pipe)) {
|
||||||
{
|
@Event::del($this->pipe);
|
||||||
foreach (config('reload.listen') as $value) {
|
@fclose($this->pipe);
|
||||||
$this->readDirectory($value);
|
}
|
||||||
}
|
@Event::exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param ?Process $process
|
||||||
|
*/
|
||||||
|
public function process(Process|null $process): void
|
||||||
|
{
|
||||||
|
$this->pipe = inotify_init();
|
||||||
|
$this->addListen();
|
||||||
|
Event::add($this->pipe, function () use ($process) {
|
||||||
|
$read = inotify_read($this->pipe);
|
||||||
|
if (count($read) > 0) {
|
||||||
|
$this->reload();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Event::cycle(function (): void {
|
||||||
|
if ($this->isStop()) {
|
||||||
|
Event::exit();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Event::wait();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
protected function clear(): void
|
public function reload(): void
|
||||||
{
|
{
|
||||||
$this->watches = [];
|
if ($this->reloading) {
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
$this->reloading = true;
|
||||||
|
|
||||||
/**
|
di(StdoutLogger::class)->println('reloading server[' . \config('site.id', 'system-service') . '], please waite.');
|
||||||
* @param string $directory
|
|
||||||
* @return void
|
$this->clear();
|
||||||
*/
|
if (!$this->reloadWorkers()) {
|
||||||
public function readFile(string $directory): void
|
di(StdoutLogger::class)->println('reload server failed: master pid not found or signal failed');
|
||||||
{
|
}
|
||||||
if (str_ends_with($directory, '.php') === true) {
|
$this->addListen();
|
||||||
inotify_add_watch($this->pipe, $directory, IN_MODIFY | IN_MOVE | IN_CREATE | IN_DELETE);
|
|
||||||
}
|
$this->reloading = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
private function isMasterProcessCommand(string $command): bool
|
||||||
* @param string $directory
|
{
|
||||||
* @return void
|
$prefix = '[' . config('site.id', 'system-service') . '].Master[';
|
||||||
*/
|
return str_contains($command, $prefix);
|
||||||
public function readDirectory(string $directory): void
|
}
|
||||||
{
|
|
||||||
foreach (glob($directory . '/*') as $data) {
|
private function isSameAppProcess(int $pid): bool
|
||||||
if (is_dir($data)) {
|
{
|
||||||
$this->readDirectory($data);
|
$cwd = @readlink('/proc/' . $pid . '/cwd');
|
||||||
} else {
|
if ($cwd === false || $cwd === '') {
|
||||||
$this->readFile($data);
|
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) {
|
||||||
|
$this->readDirectory($value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function clear(): void
|
||||||
|
{
|
||||||
|
$this->watches = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $directory
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function readFile(string $directory): void
|
||||||
|
{
|
||||||
|
if (str_ends_with($directory, '.php') === true) {
|
||||||
|
inotify_add_watch($this->pipe, $directory, IN_MODIFY | IN_MOVE | IN_CREATE | IN_DELETE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $directory
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function readDirectory(string $directory): void
|
||||||
|
{
|
||||||
|
foreach (glob($directory . '/*') as $data) {
|
||||||
|
if (is_dir($data)) {
|
||||||
|
$this->readDirectory($data);
|
||||||
|
} else {
|
||||||
|
$this->readFile($data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+19
-7
@@ -4,6 +4,8 @@
|
|||||||
namespace Kiri\Server\Abstracts;
|
namespace Kiri\Server\Abstracts;
|
||||||
|
|
||||||
|
|
||||||
|
use Kiri\Error\StdoutLogger;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class Server
|
* Class Server
|
||||||
* @package Server\Abstracts
|
* @package Server\Abstracts
|
||||||
@@ -11,12 +13,22 @@ namespace Kiri\Server\Abstracts;
|
|||||||
abstract class Server
|
abstract class Server
|
||||||
{
|
{
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Server constructor.
|
* Server constructor.
|
||||||
* @throws
|
* @throws
|
||||||
*/
|
*/
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return StdoutLogger
|
||||||
|
*/
|
||||||
|
protected function getLogger(): StdoutLogger
|
||||||
|
{
|
||||||
|
return \Kiri::getLogger();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ trait TraitServer
|
|||||||
*/
|
*/
|
||||||
public function onSignal(): void
|
public function onSignal(): void
|
||||||
{
|
{
|
||||||
$signal = \config('signal', []);
|
$signal = \config('servers.signal', []);
|
||||||
$this->onPcntlSignal(SIGINT, [$this, 'onSigint']);
|
$this->onPcntlSignal(SIGINT, [$this, 'onSigint']);
|
||||||
foreach ($signal as $sig => $value) {
|
foreach ($signal as $sig => $value) {
|
||||||
if (is_array($value) && is_string($value[0])) {
|
if (is_array($value) && is_string($value[0])) {
|
||||||
@@ -42,15 +42,99 @@ trait TraitServer
|
|||||||
*/
|
*/
|
||||||
public function onSigint($no, array $signInfo): void
|
public function onSigint($no, array $signInfo): void
|
||||||
{
|
{
|
||||||
|
static $handling = false;
|
||||||
|
if ($handling) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$handling = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
if (!$this->shouldHandleSigint()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
Kiri::getLogger()->alert('Pid ' . getmypid() . ' get signo ' . $no);
|
Kiri::getLogger()->alert('Pid ' . getmypid() . ' get signo ' . $no);
|
||||||
$this->shutdown();
|
$this->shutdown();
|
||||||
} catch (\Throwable $exception) {
|
} catch (\Throwable $exception) {
|
||||||
error($exception);
|
\Kiri::getLogger()->json_log($exception);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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 $signal
|
||||||
* @param $callback
|
* @param $callback
|
||||||
@@ -58,6 +142,9 @@ trait TraitServer
|
|||||||
*/
|
*/
|
||||||
private function onPcntlSignal($signal, $callback): void
|
private function onPcntlSignal($signal, $callback): void
|
||||||
{
|
{
|
||||||
|
if (function_exists('pcntl_async_signals')) {
|
||||||
|
pcntl_async_signals(true);
|
||||||
|
}
|
||||||
\pcntl_signal($signal, $callback);
|
\pcntl_signal($signal, $callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,7 +189,7 @@ trait TraitServer
|
|||||||
if ($port['type'] == Constant::SERVER_TYPE_WEBSOCKET) {
|
if ($port['type'] == Constant::SERVER_TYPE_WEBSOCKET) {
|
||||||
array_unshift($array, $config);
|
array_unshift($array, $config);
|
||||||
} else if ($port['type'] == Constant::SERVER_TYPE_HTTP) {
|
} else if ($port['type'] == Constant::SERVER_TYPE_HTTP) {
|
||||||
if (!empty($array) && $array[0]['type'] == Constant::SERVER_TYPE_WEBSOCKET) {
|
if (!empty($array) && $array[0]->type == Constant::SERVER_TYPE_WEBSOCKET) {
|
||||||
$array[] = $config;
|
$array[] = $config;
|
||||||
} else {
|
} else {
|
||||||
array_unshift($array, $config);
|
array_unshift($array, $config);
|
||||||
|
|||||||
@@ -13,10 +13,11 @@ interface OnCloseInterface
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param Server $server
|
* @param Server $server
|
||||||
* @param int $fd
|
* @param int $fd
|
||||||
|
* @param int $reactorId
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function onClose(Server $server, int $fd): void;
|
public function onClose(Server $server, int $fd, int $reactorId): void;
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,9 +10,10 @@ interface OnConnectInterface
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param Server $server
|
* @param Server $server
|
||||||
* @param int $fd
|
* @param int $fd
|
||||||
|
* @param int $reactorId
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function onConnect(Server $server, int $fd): void;
|
public function onConnect(Server $server, int $fd, int $reactorId): void;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace Kiri\Server\Contract;
|
namespace Kiri\Server\Contract;
|
||||||
|
|
||||||
use Swoole\WebSocket\Server;
|
use Swoole\{WebSocket\Server};
|
||||||
|
|
||||||
interface OnDisconnectInterface
|
interface OnDisconnectInterface
|
||||||
{
|
{
|
||||||
@@ -10,7 +10,7 @@ interface OnDisconnectInterface
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param Server $server
|
* @param Server $server
|
||||||
* @param int $fd
|
* @param int $fd
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function onDisconnect(Server $server, int $fd): void;
|
public function onDisconnect(Server $server, int $fd): void;
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace Kiri\Server\Contract;
|
namespace Kiri\Server\Contract;
|
||||||
|
|
||||||
use Swoole\Server;
|
use Swoole\WebSocket\Server;
|
||||||
use Swoole\WebSocket\Frame;
|
use Swoole\WebSocket\Frame;
|
||||||
|
|
||||||
interface OnMessageInterface
|
interface OnMessageInterface
|
||||||
@@ -11,7 +11,7 @@ interface OnMessageInterface
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param Server $server
|
* @param Server $server
|
||||||
* @param Frame $frame
|
* @param Frame $frame
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function onMessage(Server $server, Frame $frame): void;
|
public function onMessage(Server $server, Frame $frame): void;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
namespace Kiri\Server\Contract;
|
namespace Kiri\Server\Contract;
|
||||||
|
|
||||||
use Swoole\Http\Request;
|
use Swoole\Http\Request;
|
||||||
use Swoole\Http\Server;
|
use Swoole\WebSocket\Server;
|
||||||
|
|
||||||
interface OnOpenInterface
|
interface OnOpenInterface
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
namespace Kiri\Server\Contract;
|
namespace Kiri\Server\Contract;
|
||||||
|
|
||||||
|
|
||||||
|
use Swoole\Server;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Interface OnPipeMessageInterface
|
* Interface OnPipeMessageInterface
|
||||||
* @package Server\Contract
|
* @package Server\Contract
|
||||||
@@ -12,9 +14,12 @@ interface OnPipeMessageInterface
|
|||||||
{
|
{
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
* @param Server $server
|
||||||
|
* @param int $src_worker_id
|
||||||
|
* @param mixed $message
|
||||||
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function process(): void;
|
public function onPipeMessage(Server $server, int $src_worker_id, mixed $message): void;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Kiri\Server\Handler;
|
|
||||||
|
|
||||||
use Kiri;
|
|
||||||
use Kiri\Server\Abstracts\Server;
|
|
||||||
use Kiri\Server\Contract\OnPipeMessageInterface;
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
class OnPipeMessage extends Server
|
|
||||||
{
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param \Swoole\Server $server
|
|
||||||
* @param int $src_worker_id
|
|
||||||
* @param mixed $message
|
|
||||||
* @throws
|
|
||||||
*/
|
|
||||||
public function onPipeMessage(\Swoole\Server $server, int $src_worker_id, mixed $message): void
|
|
||||||
{
|
|
||||||
try {
|
|
||||||
if (is_string($message)) {
|
|
||||||
$message = unserialize($message);
|
|
||||||
}
|
|
||||||
if (!is_object($message) || !($message instanceof OnPipeMessageInterface)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
call_user_func([$message, 'process'], $server, $src_worker_id);
|
|
||||||
} catch (\Throwable $throwable) {
|
|
||||||
Kiri::getLogger()->error(throwable($throwable));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -11,6 +11,8 @@ use Kiri\Server\Events\OnBeforeShutdown;
|
|||||||
use Kiri\Server\Events\OnShutdown;
|
use Kiri\Server\Events\OnShutdown;
|
||||||
use Kiri\Server\Events\OnStart;
|
use Kiri\Server\Events\OnStart;
|
||||||
use Swoole\Server as SServer;
|
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
|
public function onStart(SServer $server): void
|
||||||
{
|
{
|
||||||
Kiri::setProcessName(sprintf('Master[%d]', $server->master_pid));
|
Kiri::setProcessName(sprintf('Master[%d]', $server->master_pid));
|
||||||
|
Process::signal(SIGINT, static function () use ($server): void {
|
||||||
|
$server->shutdown();
|
||||||
|
});
|
||||||
|
|
||||||
event(new OnStart($server));
|
event(new OnStart($server));
|
||||||
}
|
}
|
||||||
|
|||||||
+115
-111
@@ -30,135 +30,139 @@ class OnServerWorker extends Kiri\Server\Abstracts\Server
|
|||||||
{
|
{
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @var EventDispatch
|
* @var EventDispatch
|
||||||
*/
|
*/
|
||||||
#[Container(EventDispatch::class)]
|
#[Container(EventDispatch::class)]
|
||||||
public EventDispatch $dispatch;
|
public EventDispatch $dispatch;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function init(): void
|
public function init(): void
|
||||||
{
|
{
|
||||||
on(OnBeforeWorkerStart::class, [$this, 'onWorkerNameAlias']);
|
on(OnBeforeWorkerStart::class, [$this, 'onWorkerNameAlias']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param OnBeforeWorkerStart $workerStart
|
* @param OnBeforeWorkerStart $workerStart
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function onWorkerNameAlias(OnBeforeWorkerStart $workerStart): void
|
public function onWorkerNameAlias(OnBeforeWorkerStart $workerStart): void
|
||||||
{
|
{
|
||||||
set_env('environmental_workerId', $workerStart->workerId);
|
if ($workerStart->workerId < $workerStart->server->setting['worker_num']) {
|
||||||
if ($workerStart->workerId < $workerStart->server->setting['worker_num']) {
|
$this->processName($workerStart->server, 'Worker');
|
||||||
$this->processName($workerStart->server, 'Worker');
|
set_env('environmental', Kiri::WORKER);
|
||||||
set_env('environmental', Kiri::WORKER);
|
} else {
|
||||||
} else {
|
$this->processName($workerStart->server, 'Tasker');
|
||||||
$this->processName($workerStart->server, 'Tasker');
|
set_env('environmental', Kiri::TASK);
|
||||||
set_env('environmental', Kiri::TASK);
|
}
|
||||||
}
|
set_env('environmental_worker_id', $workerStart->workerId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param Server $server
|
* @param Server $server
|
||||||
* @param int $workerId
|
* @param int $workerId
|
||||||
* @return void
|
* @return void
|
||||||
* @throws
|
* @throws
|
||||||
*/
|
*/
|
||||||
public function onWorkerStart(Server $server, int $workerId): void
|
public function onWorkerStart(Server $server, int $workerId): void
|
||||||
{
|
{
|
||||||
$this->dispatch->dispatch(new OnBeforeWorkerStart($server, $workerId));
|
try {
|
||||||
if ($workerId < $server->setting['worker_num']) {
|
$this->dispatch->dispatch(new OnBeforeWorkerStart($server, $workerId));
|
||||||
CoordinatorManager::utility(Coordinator::WORKER_START)->waite();
|
if ($workerId < $server->setting['worker_num']) {
|
||||||
|
CoordinatorManager::utility(Coordinator::WORKER_START)->wait();
|
||||||
|
|
||||||
$this->dispatch->dispatch(new OnWorkerStart($server, $workerId));
|
$this->dispatch->dispatch(new OnWorkerStart($server, $workerId));
|
||||||
} else {
|
} else {
|
||||||
$this->dispatch->dispatch(new OnTaskerStart($server, $workerId));
|
$this->dispatch->dispatch(new OnTaskerStart($server, $workerId));
|
||||||
}
|
}
|
||||||
$this->dispatch->dispatch(new OnAfterWorkerStart($server, $workerId));
|
} catch (Throwable $exception) {
|
||||||
}
|
\Kiri::getLogger()->json_log($exception);
|
||||||
|
} finally {
|
||||||
|
$this->dispatch->dispatch(new OnAfterWorkerStart($server, $workerId));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param Server $server
|
* @param Server $server
|
||||||
* @param string $prefix
|
* @param string $prefix
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
protected function processName(Server $server, string $prefix): void
|
protected function processName(Server $server, string $prefix): void
|
||||||
{
|
{
|
||||||
Kiri::setProcessName(sprintf($prefix . '[%d]', $server->worker_pid));
|
Kiri::setProcessName(sprintf($prefix . '[%d]', $server->worker_pid));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param Server $server
|
* @param Server $server
|
||||||
* @param int $workerId
|
* @param int $workerId
|
||||||
* @throws
|
* @throws
|
||||||
*/
|
*/
|
||||||
public function onWorkerStop(Server $server, int $workerId): void
|
public function onWorkerStop(Server $server, int $workerId): void
|
||||||
{
|
{
|
||||||
event(new OnWorkerStop($server, $workerId));
|
event(new OnWorkerStop($server, $workerId));
|
||||||
Timer::clearAll();
|
Timer::clearAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param Server $server
|
* @param Server $server
|
||||||
* @param int $workerId
|
* @param int $workerId
|
||||||
* @throws
|
* @throws
|
||||||
*/
|
*/
|
||||||
public function onWorkerExit(Server $server, int $workerId): void
|
public function onWorkerExit(Server $server, int $workerId): void
|
||||||
{
|
{
|
||||||
event(new OnWorkerExit($server, $workerId));
|
event(new OnWorkerExit($server, $workerId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param Server $server
|
* @param Server $server
|
||||||
* @param int $worker_id
|
* @param int $worker_id
|
||||||
* @param int $worker_pid
|
* @param int $worker_pid
|
||||||
* @param int $exit_code
|
* @param int $exit_code
|
||||||
* @param int $signal
|
* @param int $signal
|
||||||
* @throws
|
* @throws
|
||||||
*/
|
*/
|
||||||
public function onWorkerError(Server $server, int $worker_id, int $worker_pid, int $exit_code, int $signal): void
|
public function onWorkerError(Server $server, int $worker_id, int $worker_pid, int $exit_code, int $signal): void
|
||||||
{
|
{
|
||||||
event(new OnWorkerError($server, $worker_id, $worker_pid, $exit_code, $signal));
|
event(new OnWorkerError($server, $worker_id, $worker_pid, $exit_code, $signal));
|
||||||
|
|
||||||
debug_print_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
|
debug_print_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
|
||||||
|
|
||||||
/** @var RequestInterface $context */
|
/** @var RequestInterface $context */
|
||||||
$context = Kiri\Di\Context::get(RequestInterface::class);
|
$context = Kiri\Di\Context::get(RequestInterface::class);
|
||||||
if (is_null($context)) {
|
if (is_null($context)) {
|
||||||
$message = sprintf('Worker#%d::%d error stop. signal %d, exit_code %d, msg %s', $worker_id, $worker_pid, $signal, $exit_code, swoole_strerror(swoole_last_error(), $signal));
|
$message = sprintf('Worker#%d::%d error stop. signal %d, exit_code %d, msg %s', $worker_id, $worker_pid, $signal, $exit_code, swoole_strerror(swoole_last_error(), $signal));
|
||||||
} else {
|
} else {
|
||||||
$message = sprintf('Worker#%d::%d error stop. signal %d, exit_code %d, msg %s, method: %s, path: %s, query: %s', $worker_id, $worker_pid, $signal, $exit_code, swoole_strerror(swoole_last_error(), $signal),
|
$message = sprintf('Worker#%d::%d error stop. signal %d, exit_code %d, msg %s, method: %s, path: %s, query: %s', $worker_id, $worker_pid, $signal, $exit_code, swoole_strerror(swoole_last_error(), $signal),
|
||||||
$context->getMethod(), $context->getUri()->getPath(), $context->getUri()->getQuery());
|
$context->getMethod(), $context->getUri()->getPath(), $context->getUri()->getQuery());
|
||||||
}
|
}
|
||||||
error($message . PHP_EOL);
|
$this->getLogger()->println($message);
|
||||||
|
$this->system_mail($message);
|
||||||
$this->system_mail($message);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param $messageContent
|
* @param $messageContent
|
||||||
* @throws
|
* @throws
|
||||||
*/
|
*/
|
||||||
protected function system_mail($messageContent): void
|
protected function system_mail($messageContent): void
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
$email = config('email', ['enable' => false]);
|
$email = config('email', ['enable' => false]);
|
||||||
if (!empty($email) && ($email['enable'] ?? false)) {
|
if (!empty($email) && ($email['enable'] ?? false)) {
|
||||||
Help::sendEmail($email, 'Service Error', $messageContent);
|
Help::sendEmail($email, 'Service Error', $messageContent);
|
||||||
}
|
}
|
||||||
} catch (Throwable $e) {
|
} catch (Throwable $e) {
|
||||||
error($e, ['email']);
|
\Kiri::getLogger()->json_log($e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ namespace Kiri\Server\Processes;
|
|||||||
use Swoole\Coroutine;
|
use Swoole\Coroutine;
|
||||||
use Swoole\Process;
|
use Swoole\Process;
|
||||||
use const SIGHUP;
|
use const SIGHUP;
|
||||||
|
use const SIGINT;
|
||||||
use const SIGTERM;
|
use const SIGTERM;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -16,6 +17,8 @@ abstract class AbstractProcess implements OnProcessInterface
|
|||||||
|
|
||||||
private bool $stop = false;
|
private bool $stop = false;
|
||||||
|
|
||||||
|
private bool $stopping = false;
|
||||||
|
|
||||||
|
|
||||||
public Process $process;
|
public Process $process;
|
||||||
|
|
||||||
@@ -131,9 +134,11 @@ abstract class AbstractProcess implements OnProcessInterface
|
|||||||
$array['deadlock_check_disable_trace'] = false;
|
$array['deadlock_check_disable_trace'] = false;
|
||||||
$array['exit_condition'] = [$this, 'exit_condition'];
|
$array['exit_condition'] = [$this, 'exit_condition'];
|
||||||
Coroutine::set($array);
|
Coroutine::set($array);
|
||||||
|
$process::signal(SIGINT, static function (): void {});
|
||||||
Coroutine::create(fn() => $this->coroutineWaitSignal());
|
Coroutine::create(fn() => $this->coroutineWaitSignal());
|
||||||
} else {
|
} else {
|
||||||
pcntl_signal(SIGTERM | SIGINT | SIGUSR1, [$this, 'pointWaitSignal']);
|
$process::signal(SIGTERM, [$this, 'pointWaitSignal']);
|
||||||
|
$process::signal(SIGINT, static function (): void {});
|
||||||
}
|
}
|
||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
@@ -151,9 +156,7 @@ abstract class AbstractProcess implements OnProcessInterface
|
|||||||
*/
|
*/
|
||||||
public function pointWaitSignal($signal): void
|
public function pointWaitSignal($signal): void
|
||||||
{
|
{
|
||||||
$this->stop = true;
|
$this->requestStop();
|
||||||
|
|
||||||
$this->onSigterm();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -162,10 +165,20 @@ abstract class AbstractProcess implements OnProcessInterface
|
|||||||
*/
|
*/
|
||||||
public function coroutineWaitSignal(): void
|
public function coroutineWaitSignal(): void
|
||||||
{
|
{
|
||||||
$value = Coroutine::waitSignal(SIGTERM);
|
Coroutine::waitSignal(SIGTERM);
|
||||||
if ($value) {
|
$this->requestStop();
|
||||||
$this->stop = true;
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
private function requestStop(): void
|
||||||
|
{
|
||||||
|
if ($this->stopping) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$this->stopping = true;
|
||||||
|
$this->stop = true;
|
||||||
$this->onSigterm();
|
$this->onSigterm();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ namespace Kiri\Server\Processes;
|
|||||||
use Exception;
|
use Exception;
|
||||||
use Kiri;
|
use Kiri;
|
||||||
use Swoole\Process;
|
use Swoole\Process;
|
||||||
|
use const SIGKILL;
|
||||||
|
use const SIGTERM;
|
||||||
|
|
||||||
trait TraitProcess
|
trait TraitProcess
|
||||||
{
|
{
|
||||||
@@ -40,7 +42,7 @@ trait TraitProcess
|
|||||||
private function genProcess(AbstractProcess $name): Process
|
private function genProcess(AbstractProcess $name): Process
|
||||||
{
|
{
|
||||||
return new Process(function (Process $process) use ($name) {
|
return new Process(function (Process $process) use ($name) {
|
||||||
$process->name('[' . \config('id', 'system-service') . '].' . $name->getName() . '[' . $process->pid . ']');
|
$process->name('[' . \config('site.id', 'system-service') . '].' . $name->getName() . '[' . $process->pid . ']');
|
||||||
$name->onShutdown($process)->process($process);
|
$name->onShutdown($process)->process($process);
|
||||||
},
|
},
|
||||||
$name->getRedirectStdinAndStdout(),
|
$name->getRedirectStdinAndStdout(),
|
||||||
@@ -66,4 +68,39 @@ trait TraitProcess
|
|||||||
{
|
{
|
||||||
return $this->_process;
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+12
-17
@@ -6,6 +6,7 @@ namespace Kiri\Server;
|
|||||||
|
|
||||||
use Exception;
|
use Exception;
|
||||||
use Kiri;
|
use Kiri;
|
||||||
|
use Kiri\Server\Abstracts\FileWatcher;
|
||||||
use Kiri\Server\Events\OnWorkerStart;
|
use Kiri\Server\Events\OnWorkerStart;
|
||||||
use Kiri\Events\EventProvider;
|
use Kiri\Events\EventProvider;
|
||||||
use Kiri\Events\EventDispatch;
|
use Kiri\Events\EventDispatch;
|
||||||
@@ -33,6 +34,7 @@ class ServerCommand extends Command
|
|||||||
{
|
{
|
||||||
|
|
||||||
|
|
||||||
|
#[Container(State::class)]
|
||||||
public State $state;
|
public State $state;
|
||||||
|
|
||||||
|
|
||||||
@@ -64,17 +66,6 @@ class ServerCommand extends Command
|
|||||||
public EventProvider $eventProvider;
|
public EventProvider $eventProvider;
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param string|null $name
|
|
||||||
* @throws Exception
|
|
||||||
*/
|
|
||||||
public function __construct(string $name = null)
|
|
||||||
{
|
|
||||||
parent::__construct($name);
|
|
||||||
$this->state = Kiri::getDi()->get(State::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
@@ -124,7 +115,7 @@ class ServerCommand extends Command
|
|||||||
*/
|
*/
|
||||||
protected function stop(): int
|
protected function stop(): int
|
||||||
{
|
{
|
||||||
$configs = config('server', []);
|
$configs = config('servers.server', []);
|
||||||
$instances = $this->asyncServer->sortService($configs['ports'] ?? []);
|
$instances = $this->asyncServer->sortService($configs['ports'] ?? []);
|
||||||
foreach ($instances as $config) {
|
foreach ($instances as $config) {
|
||||||
$this->state->exit($config->port);
|
$this->state->exit($config->port);
|
||||||
@@ -141,13 +132,17 @@ class ServerCommand extends Command
|
|||||||
*/
|
*/
|
||||||
protected function start(InputInterface $input): int
|
protected function start(InputInterface $input): int
|
||||||
{
|
{
|
||||||
$this->asyncServer->addProcess(config('processes', []));
|
$this->asyncServer->addProcess(config('process', []));
|
||||||
if (\config('reload.hot', false) === true) {
|
$hotReload = \config('servers.reload.hot', false) === true;
|
||||||
$this->asyncServer->addProcess([HotReload::class]);
|
if ($hotReload) {
|
||||||
} else {
|
$this->asyncServer->addProcess([FileWatcher::class]);
|
||||||
|
}
|
||||||
|
if (!$hotReload) {
|
||||||
|
// 非热更模式可在 Master 进程预扫描,Worker 通过 fork 继承扫描结果。
|
||||||
|
// 热更模式必须让新 Worker 自己加载业务类,避免继承旧类定义后无法重新声明。
|
||||||
di(Router::class)->scan_build_route();
|
di(Router::class)->scan_build_route();
|
||||||
}
|
}
|
||||||
$this->asyncServer->initCoreServers(config('server', []), (int)$input->getOption('daemon'));
|
$this->asyncServer->initCoreServers(config('servers.server', []), (int)$input->getOption('daemon'));
|
||||||
$this->asyncServer->start();
|
$this->asyncServer->start();
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -23,6 +23,6 @@ class ServerProviders extends Providers
|
|||||||
$server = $this->container->get(ServerCommand::class);
|
$server = $this->container->get(ServerCommand::class);
|
||||||
|
|
||||||
$console = $this->container->get(Application::class);
|
$console = $this->container->get(Application::class);
|
||||||
$console->add($server);
|
$console->addCommand($server);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ class State extends Component
|
|||||||
*/
|
*/
|
||||||
public function init(): void
|
public function init(): void
|
||||||
{
|
{
|
||||||
$this->servers = config('server.ports');
|
$this->servers = config('servers.server.ports');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -31,9 +31,13 @@ class State extends Component
|
|||||||
*/
|
*/
|
||||||
public function isRunner(): bool
|
public function isRunner(): bool
|
||||||
{
|
{
|
||||||
|
if ($this->getPidFilePid() !== null || $this->getNamedServerPids() !== []) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
$ports = $this->sortService($this->servers);
|
$ports = $this->sortService($this->servers);
|
||||||
foreach ($ports as $config) {
|
foreach ($ports as $config) {
|
||||||
if (checkPortIsAlready($config['port'])) {
|
if (checkPortIsAlready($config->port)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -47,13 +51,180 @@ class State extends Component
|
|||||||
*/
|
*/
|
||||||
public function exit($port): void
|
public function exit($port): void
|
||||||
{
|
{
|
||||||
if (!($pid = checkPortIsAlready($port))) {
|
$pids = $this->collectStopPids((int)$port);
|
||||||
|
if ($pids === []) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
while (checkPortIsAlready($port)) {
|
|
||||||
Process::kill($pid, 0) && Process::kill($pid, SIGTERM);
|
$this->terminatePids($pids, SIGTERM, 30);
|
||||||
usleep(300);
|
|
||||||
|
$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);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,12 +6,12 @@ class OnTaskFinish
|
|||||||
{
|
{
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param int $task_id
|
* @param int $task_id
|
||||||
* @param mixed $data
|
* @param mixed $data
|
||||||
*/
|
*/
|
||||||
public function __construct(int $task_id, mixed $data)
|
public function __construct(public int $task_id, public mixed $data)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Kiri\Server\Task;
|
||||||
|
|
||||||
|
interface OnTaskInterface
|
||||||
|
{
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int $task_id
|
||||||
|
* @param int $src_worker_id
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
public function process(int $task_id, int $src_worker_id): mixed;
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
+14
-10
@@ -24,7 +24,7 @@ class Task
|
|||||||
*/
|
*/
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
$exception = \config('exception.task');
|
$exception = \config('servers.task.exception');
|
||||||
if (!in_array(ExceptionHandlerInterface::class, class_implements($exception))) {
|
if (!in_array(ExceptionHandlerInterface::class, class_implements($exception))) {
|
||||||
$exception = ExceptionHandlerDispatcher::class;
|
$exception = ExceptionHandlerDispatcher::class;
|
||||||
}
|
}
|
||||||
@@ -67,22 +67,26 @@ class Task
|
|||||||
* @param int $task_id
|
* @param int $task_id
|
||||||
* @param int $src_worker_id
|
* @param int $src_worker_id
|
||||||
* @param mixed $data
|
* @param mixed $data
|
||||||
* @return mixed
|
* @return void
|
||||||
* @throws
|
* @throws
|
||||||
*/
|
*/
|
||||||
public function onTask(Server $server, int $task_id, int $src_worker_id, mixed $data): mixed
|
public function onTask(Server $server, int $task_id, int $src_worker_id, mixed $data): void
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
$data = json_decode($data, true);
|
|
||||||
if (is_null($data)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
[$handler, $params] = [$data[0], $data[1]];
|
[$handler, $params] = [$data[0], $data[1]];
|
||||||
|
|
||||||
$handler[0] = Kiri::getDi()->get($handler[0]);
|
$handler = Kiri::getDi()->make($handler, $params);
|
||||||
return call_user_func($handler, $task_id, $src_worker_id, $params);
|
if (!($handler instanceof OnTaskInterface)) {
|
||||||
|
throw new \Exception('Task process must implements ' . OnTaskInterface::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
$response = call_user_func([$handler, 'process'], $task_id, $src_worker_id);
|
||||||
} catch (\Throwable $throwable) {
|
} catch (\Throwable $throwable) {
|
||||||
return $this->exception->emit($throwable, response());
|
\Kiri::getLogger()->json_log($throwable, ['task_id' => $task_id, 'src_worker_id' => $src_worker_id, 'data' => $data]);
|
||||||
|
|
||||||
|
$response = throwable($throwable);
|
||||||
|
} finally {
|
||||||
|
$server->finish($response);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+30
-4
@@ -2,22 +2,50 @@
|
|||||||
|
|
||||||
namespace Kiri\Server\Task;
|
namespace Kiri\Server\Task;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
use Kiri\Server\ServerInterface;
|
use Kiri\Server\ServerInterface;
|
||||||
|
|
||||||
class TaskExecute implements TaskInterface
|
class TaskExecute implements TaskInterface
|
||||||
{
|
{
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* @param string $handler
|
||||||
|
* @param mixed $data
|
||||||
|
* @param int $dstWorkerId
|
||||||
|
* @param callable|null $finishFinishCallback
|
||||||
|
* @return void
|
||||||
|
* @throws
|
||||||
|
*/
|
||||||
|
public function task(string $handler, mixed $data, int $dstWorkerId = -1, ?callable $finishFinishCallback = null): void
|
||||||
|
{
|
||||||
|
$array = class_implements($handler, true);
|
||||||
|
if (!in_array(OnTaskInterface::class, $array, true)) {
|
||||||
|
throw new Exception('Task is not implement OnTaskInterface');
|
||||||
|
}
|
||||||
|
$server = \Kiri::getDi()->get(ServerInterface::class);
|
||||||
|
|
||||||
|
$server->task([$handler, $data], $dstWorkerId, $finishFinishCallback);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $handler
|
||||||
* @param mixed $data
|
* @param mixed $data
|
||||||
* @param float $timeout
|
* @param float $timeout
|
||||||
* @param int $dstWorkerId
|
* @param int $dstWorkerId
|
||||||
* @return mixed
|
* @return mixed
|
||||||
|
* @throws
|
||||||
*/
|
*/
|
||||||
public function taskWait(mixed $data, float $timeout = 0.5, int $dstWorkerId = -1): mixed
|
public function taskWait(string $handler, mixed $data, float $timeout = 0.5, int $dstWorkerId = -1): mixed
|
||||||
{
|
{
|
||||||
|
$array = class_implements($handler, true);
|
||||||
|
if (!in_array(OnTaskInterface::class, $array, true)) {
|
||||||
|
throw new Exception('Task is not implement OnTaskInterface');
|
||||||
|
}
|
||||||
$server = \Kiri::getDi()->get(ServerInterface::class);
|
$server = \Kiri::getDi()->get(ServerInterface::class);
|
||||||
|
|
||||||
return $server->taskwait($data, $timeout, $dstWorkerId);
|
return $server->taskwait([$handler, $data], $timeout, $dstWorkerId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -45,6 +73,4 @@ class TaskExecute implements TaskInterface
|
|||||||
|
|
||||||
return $server->taskWaitMulti($tasks, $timeout);
|
return $server->taskWaitMulti($tasks, $timeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
+21
-8
@@ -7,11 +7,24 @@ interface TaskInterface
|
|||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array $tasks
|
* @param string $handler
|
||||||
* @param float $timeout
|
* @param mixed $data
|
||||||
* @return false|array
|
* @param int $dstWorkerId
|
||||||
|
* @param callable|null $finishFinishCallback
|
||||||
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function taskWaitMulti(array $tasks, float $timeout = 0.5): false|array;
|
public function task(string $handler, mixed $data, int $dstWorkerId = -1, ?callable $finishFinishCallback = null): void;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $handler
|
||||||
|
* @param mixed $data
|
||||||
|
* @param float $timeout
|
||||||
|
* @param int $dstWorkerId
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
public function taskWait(string $handler, mixed $data, float $timeout = 0.5, int $dstWorkerId = -1): mixed;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array $tasks
|
* @param array $tasks
|
||||||
@@ -20,12 +33,12 @@ interface TaskInterface
|
|||||||
*/
|
*/
|
||||||
public function taskCo(array $tasks, float $timeout = 0.5): false|array;
|
public function taskCo(array $tasks, float $timeout = 0.5): false|array;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param mixed $data
|
* @param array $tasks
|
||||||
* @param float $timeout
|
* @param float $timeout
|
||||||
* @param int $dstWorkerId
|
* @return false|array
|
||||||
* @return mixed
|
|
||||||
*/
|
*/
|
||||||
public function taskWait(mixed $data, float $timeout = 0.5, int $dstWorkerId = -1): mixed;
|
public function taskWaitMulti(array $tasks, float $timeout = 0.5): false|array;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Kiri\Server\Task;
|
||||||
|
|
||||||
|
class TestTask implements OnTaskInterface
|
||||||
|
{
|
||||||
|
|
||||||
|
|
||||||
|
public function __construct($user, $friend)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int $task_id
|
||||||
|
* @param int $src_worker_id
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
public function process(int $task_id, int $src_worker_id): int
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+1
-1
@@ -9,7 +9,7 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"require": {
|
"require": {
|
||||||
"php": ">=8.0",
|
"php": ">=8.5",
|
||||||
"ext-json": "*",
|
"ext-json": "*",
|
||||||
"composer-runtime-api": "^2.0",
|
"composer-runtime-api": "^2.0",
|
||||||
"psr/http-server-middleware": "^1.0",
|
"psr/http-server-middleware": "^1.0",
|
||||||
|
|||||||
Reference in New Issue
Block a user