Compare commits
106 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| eeb925b5b9 | |||
| 59042c0110 | |||
| 7c459cc9bc | |||
| 968cdbd11a | |||
| 37b59c8536 | |||
| 9376a73628 | |||
| eebaf63999 | |||
| e399837dad | |||
| 7b8a43f94f | |||
| c0f8133926 | |||
| f533d3262b | |||
| c767a1745a | |||
| 251e05dbf7 | |||
| 5defd5fb30 | |||
| 95f52b58fd | |||
| 0a97c9b29a | |||
| 3336573b4d | |||
| 44187c2354 | |||
| a058f3ed99 | |||
| faff485006 | |||
| e2b012126a | |||
| b36e21d8ee | |||
| d191296ecc | |||
| 03825dcb09 | |||
| d500bb78c8 | |||
| e2cac499b6 | |||
| bb557a9aa9 | |||
| 89cc6a04eb | |||
| 91e5c4d66a | |||
| 7e5301f02a | |||
| f76f4c02b6 | |||
| 2afe84694d | |||
| 8f80811da6 | |||
| e46ad90c46 | |||
| 4172349872 | |||
| 0849870234 | |||
| 9fcd47ecd1 | |||
| 3bfcaf8236 | |||
| 23110643e0 | |||
| d9980e9e1b | |||
| a580607ec8 | |||
| 1e5fe2412a | |||
| 2be7134ea6 | |||
| 125dd9e5b2 | |||
| 7fa1110a50 | |||
| b23c7eff83 | |||
| 2e86a73187 | |||
| 263b4d53eb | |||
| ddf25de2c5 | |||
| 54c34ccf8f | |||
| ad9f536c90 | |||
| c068c2db4f | |||
| c4bca4f88e | |||
| f6a00d89c1 | |||
| 7f93ab046b | |||
| 64514b069e | |||
| e669d80bb9 | |||
| b3777a64e3 | |||
| f858cecf1a | |||
| e0eda4b42c | |||
| b54d956a2d | |||
| bce6870538 | |||
| ab1a18a886 | |||
| 26bd43510e | |||
| cb73717c7f | |||
| 7360a8107b | |||
| cc98a527cd | |||
| 694bde36d9 | |||
| bbae787d4b | |||
| dc15054c86 | |||
| 787f035d62 | |||
| 09ec4eb9c3 | |||
| 60d08ccaca | |||
| 8c5eefb9a7 | |||
| 9cb6db5e26 | |||
| 82ff5c5d42 | |||
| a5378658ee | |||
| ac629ece15 | |||
| 42794168b5 | |||
| e626b38d67 | |||
| 0e34ee9542 | |||
| eaed9020db | |||
| e1841d908b | |||
| 53bcb44b0e | |||
| f7e5faa668 | |||
| 9b22f66571 | |||
| 90154ece54 | |||
| e6c051ad24 | |||
| b5937acf3c | |||
| 97d11abd4e | |||
| 133c05be44 | |||
| f3244cce0f | |||
| e4321de504 | |||
| e1e44da5b2 | |||
| a756532738 | |||
| 80b9ae8f1e | |||
| 0e1fcef911 | |||
| 92dd75b82c | |||
| 12a1aac9e5 | |||
| 917e82064a | |||
| b14b18040b | |||
| def6675c81 | |||
| 6cdb51dd18 | |||
| e9367ec735 | |||
| 684c5a3ebb | |||
| 858b9bc9f9 |
+33
-82
@@ -3,30 +3,28 @@
|
||||
namespace Kiri\Server\Abstracts;
|
||||
|
||||
use Exception;
|
||||
use Kiri\Exception\ConfigException;
|
||||
use Kiri\Abstracts\Component;
|
||||
use Kiri\Error\StdoutLogger;
|
||||
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;
|
||||
use Kiri\Server\Task\Task;
|
||||
use Kiri\Di\Inject\Container;
|
||||
use Psr\Container\ContainerExceptionInterface;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Container\NotFoundExceptionInterface;
|
||||
use ReflectionException;
|
||||
use Swoole\Server;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class AsyncServer implements ServerInterface
|
||||
class AsyncServer extends Component implements ServerInterface
|
||||
{
|
||||
|
||||
use TraitServer;
|
||||
use TraitProcess;
|
||||
|
||||
|
||||
/**
|
||||
@@ -35,13 +33,6 @@ class AsyncServer implements ServerInterface
|
||||
private ?Server $server = null;
|
||||
|
||||
|
||||
/**
|
||||
* @var ContainerInterface
|
||||
*/
|
||||
#[Container(ContainerInterface::class)]
|
||||
public ContainerInterface $container;
|
||||
|
||||
|
||||
/**
|
||||
* @param array $service
|
||||
* @param int $daemon
|
||||
@@ -50,15 +41,15 @@ class AsyncServer implements ServerInterface
|
||||
*/
|
||||
public function initCoreServers(array $service, int $daemon = 0): void
|
||||
{
|
||||
$service = $this->genConfigService($service);
|
||||
$this->createBaseServer(array_pop($service), $daemon);
|
||||
foreach ($service as $value) {
|
||||
$this->addListener($value);
|
||||
$service = $this->createBaseServer($this->genConfigService($service), $daemon);
|
||||
if (isset($this->server->setting[Constant::OPTION_TASK_WORKER_NUM])) {
|
||||
$this->container->get(Task::class)->initTaskWorker($this->server);
|
||||
}
|
||||
foreach ($this->_process as $process) {
|
||||
$this->server->addProcess($process);
|
||||
}
|
||||
on(OnServerBeforeStart::class, [$this, 'onSignal']);
|
||||
|
||||
foreach ($this->_process as $process) $this->server->addProcess($process);
|
||||
foreach ($service as $value) $this->addListener($value);
|
||||
|
||||
$this->provider->on(OnServerBeforeStart::class, [$this, 'onSignal']);
|
||||
}
|
||||
|
||||
|
||||
@@ -70,60 +61,40 @@ class AsyncServer implements ServerInterface
|
||||
{
|
||||
$this->server->shutdown();
|
||||
|
||||
event(new OnShutdown());
|
||||
$this->dispatch->dispatch(new OnShutdown());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param SConfig $config
|
||||
* @param array $service
|
||||
* @param int $daemon
|
||||
* @return void
|
||||
* @throws
|
||||
* @return array
|
||||
* @throws ContainerExceptionInterface
|
||||
* @throws NotFindClassException
|
||||
* @throws NotFoundExceptionInterface
|
||||
*/
|
||||
private function createBaseServer(SConfig $config, int $daemon = 0): void
|
||||
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->initServer($match, $config, $daemon);
|
||||
$this->onEventListen($this->server, \config('server.events', []));
|
||||
$this->onEventListen($this->server, $config->events);
|
||||
$this->onTaskListen();
|
||||
}
|
||||
|
||||
$this->container->get(StdoutLogger::class)->println('Listen address ' . $config->host . '::' . $config->port);
|
||||
|
||||
/**
|
||||
* @param $match
|
||||
* @param $config
|
||||
* @param $daemon
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
private function initServer($match, $config, $daemon): void
|
||||
{
|
||||
$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->_listenDump($config);
|
||||
|
||||
$this->event($this->server, array_merge(\config('servers.server.events', []), $config->events));
|
||||
$this->container->bind(ServerInterface::class, $this->server);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
private function onTaskListen(): void
|
||||
{
|
||||
if (!isset($this->server->setting[Constant::OPTION_TASK_WORKER_NUM])) {
|
||||
return;
|
||||
}
|
||||
$this->container->get(Task::class)->initTaskWorker($this->server);
|
||||
return $service;
|
||||
}
|
||||
|
||||
|
||||
@@ -135,7 +106,7 @@ class AsyncServer implements ServerInterface
|
||||
*/
|
||||
protected function systemConfig(SConfig $config, int $daemon): array
|
||||
{
|
||||
$settings = array_merge(\config('server.settings', []), $config->settings);
|
||||
$settings = array_merge(\config('servers.server.settings', []), $config->settings);
|
||||
$settings[Constant::OPTION_DAEMONIZE] = (bool)$daemon;
|
||||
$settings[Constant::OPTION_ENABLE_REUSE_PORT] = true;
|
||||
$settings[Constant::OPTION_PID_FILE] = storage('.swoole.pid');
|
||||
@@ -157,29 +128,10 @@ class AsyncServer implements ServerInterface
|
||||
if ($port === false) {
|
||||
throw new Exception('Listen port fail.' . swoole_last_error());
|
||||
}
|
||||
$this->_listenDump($config);
|
||||
$port->set($this->resetSettings($config->type, $config->settings));
|
||||
$this->onEventListen($port, $config->getEvents());
|
||||
}
|
||||
$this->event($port, $config->getEvents());
|
||||
|
||||
|
||||
/**
|
||||
* @param SConfig $config
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
protected function _listenDump(SConfig $config): void
|
||||
{
|
||||
$writeln = $this->container->get(OutputInterface::class);
|
||||
if ($config->type == Constant::SERVER_TYPE_HTTP) {
|
||||
$writeln->writeln('Add http port listen ' . $config->host . '::' . $config->port);
|
||||
} else if ($config->type == Constant::SERVER_TYPE_WEBSOCKET) {
|
||||
$writeln->writeln('Add wss port listen ' . $config->host . '::' . $config->port);
|
||||
} else if ($config->type == Constant::SERVER_TYPE_UDP) {
|
||||
$writeln->writeln('Add udp port listen ' . $config->host . '::' . $config->port);
|
||||
} else {
|
||||
$writeln->writeln('Add tcp port listen ' . $config->host . '::' . $config->port);
|
||||
}
|
||||
$this->container->get(StdoutLogger::class)->println('Listen address ' . $config->host . '::' . $config->port);
|
||||
}
|
||||
|
||||
|
||||
@@ -210,11 +162,12 @@ class AsyncServer implements ServerInterface
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
private function onEventListen(Server\Port|Server $base, array $events): void
|
||||
private function event(Server\Port|Server $base, array $events): void
|
||||
{
|
||||
$container = $this->container;
|
||||
foreach ($events as $name => $event) {
|
||||
if (is_array($event) && is_string($event[0])) {
|
||||
$event[0] = $this->container->get($event[0]);
|
||||
$event[0] = $container->get($event[0]);
|
||||
}
|
||||
$base->on($name, $event);
|
||||
}
|
||||
@@ -227,9 +180,7 @@ class AsyncServer implements ServerInterface
|
||||
*/
|
||||
public function start(): void
|
||||
{
|
||||
event(new OnServerBeforeStart());
|
||||
$this->dispatch->dispatch(new OnServerBeforeStart());
|
||||
$this->server->start();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Kiri\Server\Abstracts;
|
||||
|
||||
|
||||
use Kiri\Di\Context;
|
||||
use Kiri\Di\Inject\Container;
|
||||
use Kiri\Error\StdoutLogger;
|
||||
use Kiri\Server\Contract\OnProcessInterface;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Swoole\Coroutine;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
abstract class BaseProcess implements OnProcessInterface
|
||||
{
|
||||
|
||||
private bool $stop = false;
|
||||
|
||||
|
||||
protected bool $redirect_stdin_and_stdout = FALSE;
|
||||
|
||||
|
||||
protected int $pipe_type = SOCK_DGRAM;
|
||||
|
||||
|
||||
protected bool $enable_coroutine = false;
|
||||
|
||||
|
||||
/**
|
||||
* @var StdoutLogger
|
||||
*/
|
||||
#[Container(LoggerInterface::class)]
|
||||
public StdoutLogger $logger;
|
||||
|
||||
|
||||
/**
|
||||
* @var \Kiri\Di\Container
|
||||
*/
|
||||
#[Container(ContainerInterface::class)]
|
||||
public \Kiri\Di\Container $container;
|
||||
|
||||
|
||||
public string $name = '';
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getName(): string
|
||||
{
|
||||
if (empty($this->name)) {
|
||||
$this->name = uniqid('p.');
|
||||
}
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isStop(): bool
|
||||
{
|
||||
return $this->stop;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function getRedirectStdinAndStdout(): bool
|
||||
{
|
||||
return $this->redirect_stdin_and_stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getPipeType(): int
|
||||
{
|
||||
return $this->pipe_type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isEnableCoroutine(): bool
|
||||
{
|
||||
return $this->enable_coroutine;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function stop(): void
|
||||
{
|
||||
$this->stop = true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
abstract public function onSigterm(): static;
|
||||
|
||||
|
||||
/**
|
||||
* @param $data
|
||||
* @return void
|
||||
*/
|
||||
protected function onShutdown($data): void
|
||||
{
|
||||
$this->stop = true;
|
||||
$value = Context::get('waite:process:message');
|
||||
$this->logger->alert('Process ' . $this->getName() . ' stop');
|
||||
if (!is_null($value) && Coroutine::exists((int)$value)) {
|
||||
Coroutine::cancel((int)$value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
<?php
|
||||
|
||||
namespace Kiri\Server\Abstracts;
|
||||
|
||||
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\ServerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Swoole\Event;
|
||||
use Swoole\Process;
|
||||
use Kiri\Server\Processes\AbstractProcess;
|
||||
|
||||
class HotReload extends AbstractProcess
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @var mixed
|
||||
*/
|
||||
protected mixed $pipe;
|
||||
|
||||
|
||||
/**
|
||||
* @var LoggerInterface|StdoutLogger
|
||||
*/
|
||||
#[Container(LoggerInterface::class)]
|
||||
public StdoutLogger|LoggerInterface $logger;
|
||||
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected bool $enable_coroutine = false;
|
||||
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected array $watches = [];
|
||||
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected bool $enable_queue = false;
|
||||
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected bool $reloading = false;
|
||||
|
||||
|
||||
/**
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
di(EventProvider::class)->on(OnWorkerStart::class, [di(Router::class), 'scan_build_route']);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getName(): string
|
||||
{
|
||||
return 'hotReload';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function onSigterm(): void
|
||||
{
|
||||
// TODO: Implement onSigterm() method.
|
||||
$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
|
||||
*/
|
||||
public function reload(): void
|
||||
{
|
||||
if ($this->reloading) {
|
||||
return;
|
||||
}
|
||||
$this->reloading = true;
|
||||
|
||||
di(StdoutLogger::class)->println('reloading server[' . \config('site.id', 'system-service') . '], please waite.');
|
||||
|
||||
$this->clear();
|
||||
di(ServerInterface::class)->reload();
|
||||
$this->addListen();
|
||||
|
||||
$this->reloading = false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Kiri\Server\Abstracts;
|
||||
|
||||
use Closure;
|
||||
use Exception;
|
||||
use Kiri;
|
||||
use Kiri\Abstracts\Component;
|
||||
use Kiri\Di\Inject\Container;
|
||||
use Kiri\Error\StdoutLogger;
|
||||
use Kiri\Server\Contract\OnProcessInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use ReflectionException;
|
||||
use Swoole\Process;
|
||||
use Kiri\Server\ServerInterface;
|
||||
use Kiri\Server\Events\OnServerBeforeStart;
|
||||
|
||||
class ProcessManager extends Component
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @var StdoutLogger
|
||||
*/
|
||||
#[Container(LoggerInterface::class)]
|
||||
public StdoutLogger $logger;
|
||||
|
||||
|
||||
/** @var array<string, BaseProcess> */
|
||||
private array $_process = [];
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
public function init(): void
|
||||
{
|
||||
on(OnServerBeforeStart::class, [$this, 'OnServerBeforeStart']);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param OnServerBeforeStart $beforeStart
|
||||
* @return void
|
||||
*/
|
||||
public function OnServerBeforeStart(OnServerBeforeStart $beforeStart): void
|
||||
{
|
||||
$server = Kiri::getDi()->get(ServerInterface::class);
|
||||
foreach ($this->_process as $custom) {
|
||||
$server->addProcess(new Process(function (Process $process) use ($custom) {
|
||||
$this->extracted($custom, $process);
|
||||
},
|
||||
$custom->getRedirectStdinAndStdout(),
|
||||
$custom->getPipeType(),
|
||||
$custom->isEnableCoroutine()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return Process[]
|
||||
*/
|
||||
public function getProcesses(): array
|
||||
{
|
||||
return $this->_process;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string|OnProcessInterface|BaseProcess $custom
|
||||
* @throws
|
||||
*/
|
||||
public function add(string|OnProcessInterface|BaseProcess $custom): void
|
||||
{
|
||||
if (is_string($custom)) {
|
||||
$custom = Kiri::getDi()->get($custom);
|
||||
}
|
||||
|
||||
if (isset($this->_process[$custom->getName()])) {
|
||||
throw new Exception('Process(' . $custom->getName() . ') is exists.');
|
||||
}
|
||||
|
||||
$this->_process[$custom->getName()] = $custom;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function shutdown(): void
|
||||
{
|
||||
foreach ($this->_process as $process) {
|
||||
Process::kill($process->pid, 0) && Process::kill($process->pid, 15);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param BaseProcess $customProcess
|
||||
* @return Closure
|
||||
*/
|
||||
public function resolve(BaseProcess $customProcess): Closure
|
||||
{
|
||||
return static function (Process $process) use ($customProcess) {
|
||||
$this->extracted($customProcess, $process);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string|null $name
|
||||
* @param string $tag
|
||||
* @return array|Process|null
|
||||
*/
|
||||
public function get(?string $name = null, string $tag = 'default'): array|Process|null
|
||||
{
|
||||
$process = $this->_process[$tag] ?? null;
|
||||
if (empty($process)) {
|
||||
return null;
|
||||
}
|
||||
if (!empty($name)) {
|
||||
if (!isset($process[$name])) {
|
||||
return null;
|
||||
}
|
||||
return $process[$name];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function stop(): void
|
||||
{
|
||||
foreach ($this->_process as $process) {
|
||||
Process::kill($process->pid, 0) && Process::kill($process->pid, 15);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array|null $processes
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
public function batch(?array $processes): void
|
||||
{
|
||||
if (empty($processes)) {
|
||||
return;
|
||||
}
|
||||
foreach ($processes as $process) {
|
||||
$this->add($process);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $message
|
||||
* @param string $name
|
||||
* @return void
|
||||
*/
|
||||
public function push(string $name, string $message): void
|
||||
{
|
||||
if (!isset($this->_process[$name])) {
|
||||
return;
|
||||
}
|
||||
$process = $this->_process[$name];
|
||||
$process->write($message);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $custom
|
||||
* @param Process $process
|
||||
* @return void
|
||||
* @throws Kiri\Exception\ConfigException
|
||||
* @throws ReflectionException
|
||||
*/
|
||||
public function extracted(mixed $custom, Process $process): void
|
||||
{
|
||||
set_env('environmental', Kiri::PROCESS);
|
||||
$system = sprintf('[%s].Custom Process', \config('id', 'system-service'));
|
||||
$this->logger->alert($system . ' ' . $custom->getName() . ' start.');
|
||||
if (Kiri::getPlatform()->isLinux()) {
|
||||
$process->name($system . '[' . $process->pid . '].' . $custom->getName());
|
||||
}
|
||||
$custom->onSigterm()->process($process);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+19
-7
@@ -4,6 +4,8 @@
|
||||
namespace Kiri\Server\Abstracts;
|
||||
|
||||
|
||||
use Kiri\Error\StdoutLogger;
|
||||
|
||||
/**
|
||||
* Class Server
|
||||
* @package Server\Abstracts
|
||||
@@ -11,12 +13,22 @@ namespace Kiri\Server\Abstracts;
|
||||
abstract class Server
|
||||
{
|
||||
|
||||
/**
|
||||
* Server constructor.
|
||||
* @throws
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
/**
|
||||
* Server constructor.
|
||||
* @throws
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return StdoutLogger
|
||||
*/
|
||||
protected function getLogger(): StdoutLogger
|
||||
{
|
||||
return \Kiri::getLogger();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -4,75 +4,24 @@ namespace Kiri\Server\Abstracts;
|
||||
|
||||
use Exception;
|
||||
use Kiri;
|
||||
use Kiri\Di\Inject\Container;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Swoole\Http\Server as HServer;
|
||||
use Swoole\Process;
|
||||
use Swoole\Server;
|
||||
use Kiri\Server\Processes\AbstractProcess;
|
||||
use Kiri\Server\Constant;
|
||||
use Kiri\Server\Config;
|
||||
use Kiri\Error\StdoutLogger;
|
||||
use Swoole\WebSocket\Server as WServer;
|
||||
use Swoole\Process;
|
||||
|
||||
trait TraitServer
|
||||
{
|
||||
|
||||
|
||||
private array $_process = [];
|
||||
|
||||
|
||||
/**
|
||||
* @var StdoutLogger
|
||||
*/
|
||||
#[Container(LoggerInterface::class)]
|
||||
public StdoutLogger $logger;
|
||||
|
||||
|
||||
/**
|
||||
* @param string|array|BaseProcess $class
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function addProcess(string|array|BaseProcess $class): void
|
||||
{
|
||||
if (!is_array($class)) {
|
||||
$class = [$class];
|
||||
}
|
||||
foreach ($class as $name) {
|
||||
if (is_string($name)) {
|
||||
$name = Kiri::getDi()->get($name);
|
||||
}
|
||||
if (isset($this->_process[$name->getName()])) {
|
||||
throw new Exception('Process(' . $name->getName() . ') is exists.');
|
||||
}
|
||||
$this->_process[$name->getName()] = $this->genProcess($name);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param BaseProcess $name
|
||||
* @return Process
|
||||
*/
|
||||
private function genProcess(BaseProcess $name): Process
|
||||
{
|
||||
return new Process(function (Process $process) use ($name) {
|
||||
$process->name($name->getName());
|
||||
$name->onSigterm()->process($process);
|
||||
},
|
||||
$name->getRedirectStdinAndStdout(),
|
||||
$name->getPipeType(),
|
||||
$name->isEnableCoroutine());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function onSignal(): void
|
||||
{
|
||||
$signal = \config('signal', []);
|
||||
$signal = \config('servers.signal', []);
|
||||
$this->onPcntlSignal(SIGINT, [$this, 'onSigint']);
|
||||
foreach ($signal as $sig => $value) {
|
||||
if (is_array($value) && is_string($value[0])) {
|
||||
@@ -94,10 +43,10 @@ trait TraitServer
|
||||
public function onSigint($no, array $signInfo): void
|
||||
{
|
||||
try {
|
||||
$this->logger->alert('Pid ' . getmypid() . ' get signo ' . $no);
|
||||
Kiri::getLogger()->alert('Pid ' . getmypid() . ' get signo ' . $no);
|
||||
$this->shutdown();
|
||||
} catch (\Throwable $exception) {
|
||||
error($exception);
|
||||
\Kiri::getLogger()->json_log($exception);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,16 +58,7 @@ trait TraitServer
|
||||
*/
|
||||
private function onPcntlSignal($signal, $callback): void
|
||||
{
|
||||
pcntl_signal($signal, $callback);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getProcess(): array
|
||||
{
|
||||
return $this->_process;
|
||||
\pcntl_signal($signal, $callback);
|
||||
}
|
||||
|
||||
|
||||
@@ -182,10 +122,10 @@ trait TraitServer
|
||||
{
|
||||
return match ($type) {
|
||||
Constant::SERVER_TYPE_BASE, Constant::SERVER_TYPE_TCP,
|
||||
Constant::SERVER_TYPE_UDP => Server::class,
|
||||
Constant::SERVER_TYPE_HTTP => HServer::class,
|
||||
Constant::SERVER_TYPE_UDP => Server::class,
|
||||
Constant::SERVER_TYPE_HTTP => HServer::class,
|
||||
Constant::SERVER_TYPE_WEBSOCKET => WServer::class,
|
||||
default => null
|
||||
default => null
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
|
||||
namespace Kiri\Server\Events;
|
||||
|
||||
use Kiri\Exception\ConfigException;
|
||||
use Swoole\Server;
|
||||
use Kiri;
|
||||
|
||||
/**
|
||||
*
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace Kiri\Server\Handler;
|
||||
|
||||
use Exception;
|
||||
use Kiri;
|
||||
use Kiri\Server\Abstracts\Server;
|
||||
use Kiri\Server\Contract\OnPipeMessageInterface;
|
||||
|
||||
@@ -21,13 +21,17 @@ class OnPipeMessage extends Server
|
||||
*/
|
||||
public function onPipeMessage(\Swoole\Server $server, int $src_worker_id, mixed $message): void
|
||||
{
|
||||
if (is_string($message)) {
|
||||
$message = unserialize($message);
|
||||
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()->json_log($throwable, ['src_worker_id' => $src_worker_id, 'message' => $message]);
|
||||
}
|
||||
if (!is_object($message) || !($message instanceof OnPipeMessageInterface)) {
|
||||
return;
|
||||
}
|
||||
call_user_func([$message, 'process'], $server, $src_worker_id);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Kiri\Server\Handler;
|
||||
|
||||
use Exception;
|
||||
use Kiri\Di\Inject\Container;
|
||||
use Kiri\Di\Context;
|
||||
use Kiri\Di\Interface\ResponseEmitterInterface;
|
||||
use Kiri\Router\Base\ExceptionHandlerDispatcher;
|
||||
use Kiri\Router\Constrict\ConstrictRequest as CQ;
|
||||
use Kiri\Router\Constrict\ConstrictResponse;
|
||||
use Kiri\Router\DataGrip;
|
||||
use Kiri\Router\Interface\ExceptionHandlerInterface;
|
||||
use Kiri\Router\Interface\OnRequestInterface;
|
||||
use Kiri\Router\RouterCollector;
|
||||
use Psr\Container\ContainerExceptionInterface;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Container\NotFoundExceptionInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use ReflectionException;
|
||||
use Swoole\Http\Request;
|
||||
use Swoole\Http\Response;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* OnRequest event
|
||||
*/
|
||||
class OnRequest implements OnRequestInterface
|
||||
{
|
||||
|
||||
/**
|
||||
* @var RouterCollector
|
||||
*/
|
||||
public RouterCollector $router;
|
||||
|
||||
|
||||
/**
|
||||
* @var ExceptionHandlerInterface
|
||||
*/
|
||||
public ExceptionHandlerInterface $exception;
|
||||
|
||||
|
||||
/**
|
||||
* @var ResponseEmitterInterface
|
||||
*/
|
||||
public ResponseEmitterInterface $responseEmitter;
|
||||
|
||||
|
||||
/**
|
||||
* @var ConstrictResponse
|
||||
*/
|
||||
#[Container(ConstrictResponse::class)]
|
||||
public ConstrictResponse $constrictResponse;
|
||||
|
||||
|
||||
/**
|
||||
* @param ResponseInterface $response
|
||||
* @param ContainerInterface $container
|
||||
* @param DataGrip $dataGrip
|
||||
* @throws
|
||||
*/
|
||||
public function __construct(public ResponseInterface $response, public ContainerInterface $container,
|
||||
public DataGrip $dataGrip)
|
||||
{
|
||||
$this->responseEmitter = $this->response->emmit;
|
||||
$exception = \config('exception.http');
|
||||
if (!in_array(ExceptionHandlerInterface::class, class_implements($exception))) {
|
||||
$exception = ExceptionHandlerDispatcher::class;
|
||||
}
|
||||
$this->exception = $this->container->get($exception);
|
||||
$this->router = $this->dataGrip->get(ROUTER_TYPE_HTTP);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Request $request
|
||||
* @param Response $response
|
||||
* @throws
|
||||
*/
|
||||
public function onRequest(Request $request, Response $response): void
|
||||
{
|
||||
/** @var CQ $PsrRequest */
|
||||
try {
|
||||
$PsrRequest = $this->initRequestAndResponse($request);
|
||||
|
||||
$PsrResponse = $this->router->query($request->server['path_info'], $request->getMethod())
|
||||
->run($PsrRequest);
|
||||
} catch (Throwable $throwable) {
|
||||
$PsrResponse = $this->exception->emit($throwable, $this->constrictResponse);
|
||||
} finally {
|
||||
$this->responseEmitter->response($PsrResponse, $response, $PsrRequest);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Request $request
|
||||
* @return ServerRequestInterface
|
||||
*/
|
||||
public function initRequestAndResponse(Request $request): ServerRequestInterface
|
||||
{
|
||||
$response = new ConstrictResponse($this->response->contentType);
|
||||
|
||||
Context::set(ResponseInterface::class, $response);
|
||||
|
||||
return Context::set(RequestInterface::class, CQ::builder($request));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,7 +6,6 @@ use Kiri;
|
||||
use Kiri\Di\Inject\Container;
|
||||
use Kiri\Error\StdoutLogger;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use ReflectionException;
|
||||
use Kiri\Server\Abstracts\Server;
|
||||
use Kiri\Server\Events\OnBeforeShutdown;
|
||||
use Kiri\Server\Events\OnShutdown;
|
||||
@@ -35,10 +34,8 @@ class OnServer extends Server
|
||||
*/
|
||||
public function onStart(SServer $server): void
|
||||
{
|
||||
Kiri::setProcessName(sprintf('start[%d].server', $server->master_pid));
|
||||
foreach (config('server.ports') as $value) {
|
||||
$this->logger->alert('Listen ' . $value['type'] . ' address ' . $value['host'] . '::' . $value['port']);
|
||||
}
|
||||
Kiri::setProcessName(sprintf('Master[%d]', $server->master_pid));
|
||||
|
||||
event(new OnStart($server));
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
namespace Kiri\Server\Handler;
|
||||
|
||||
use Kiri;
|
||||
use ReflectionException;
|
||||
use Kiri\Server\Abstracts\Server;
|
||||
use Kiri\Server\Events\OnManagerStart;
|
||||
use Kiri\Server\Events\OnManagerStop;
|
||||
@@ -23,7 +22,7 @@ class OnServerManager extends Server
|
||||
*/
|
||||
public function onManagerStart(\Swoole\Server $server): void
|
||||
{
|
||||
Kiri::setProcessName(sprintf('manger process[%d]', $server->manager_pid));
|
||||
Kiri::setProcessName(sprintf('Manger[%d]', $server->manager_pid));
|
||||
|
||||
event(new OnManagerStart($server));
|
||||
}
|
||||
|
||||
+120
-104
@@ -3,7 +3,10 @@
|
||||
namespace Kiri\Server\Handler;
|
||||
|
||||
use Kiri;
|
||||
use Kiri\Abstracts\CoordinatorManager;
|
||||
use Kiri\Coordinator;
|
||||
use Kiri\Core\Help;
|
||||
use Kiri\Di\Inject\Container;
|
||||
use Kiri\Events\EventDispatch;
|
||||
use Kiri\Server\Events\OnAfterWorkerStart;
|
||||
use Kiri\Server\Events\OnBeforeWorkerStart;
|
||||
@@ -12,8 +15,8 @@ use Kiri\Server\Events\OnWorkerError;
|
||||
use Kiri\Server\Events\OnWorkerExit;
|
||||
use Kiri\Server\Events\OnWorkerStart;
|
||||
use Kiri\Server\Events\OnWorkerStop;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Swoole\Server;
|
||||
use Kiri\Di\Inject\Container;
|
||||
use Swoole\Timer;
|
||||
use Throwable;
|
||||
use function config;
|
||||
@@ -27,126 +30,139 @@ class OnServerWorker extends Kiri\Server\Abstracts\Server
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @var EventDispatch
|
||||
*/
|
||||
#[Container(EventDispatch::class)]
|
||||
public EventDispatch $dispatch;
|
||||
/**
|
||||
* @var EventDispatch
|
||||
*/
|
||||
#[Container(EventDispatch::class)]
|
||||
public EventDispatch $dispatch;
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function init(): void
|
||||
{
|
||||
on(OnBeforeWorkerStart::class, [$this, 'onWorkerNameAlias']);
|
||||
}
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function init(): void
|
||||
{
|
||||
on(OnBeforeWorkerStart::class, [$this, 'onWorkerNameAlias']);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param OnBeforeWorkerStart $workerStart
|
||||
* @return void
|
||||
*/
|
||||
public function onWorkerNameAlias(OnBeforeWorkerStart $workerStart): void
|
||||
{
|
||||
set_env('environmental_workerId', $workerStart->workerId);
|
||||
if ($workerStart->workerId < $workerStart->server->setting['worker_num']) {
|
||||
$this->processName($workerStart->server, 'Worker');
|
||||
set_env('environmental', Kiri::WORKER);
|
||||
} else {
|
||||
$this->processName($workerStart->server, 'Tasker');
|
||||
set_env('environmental', Kiri::TASK);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @param OnBeforeWorkerStart $workerStart
|
||||
* @return void
|
||||
*/
|
||||
public function onWorkerNameAlias(OnBeforeWorkerStart $workerStart): void
|
||||
{
|
||||
if ($workerStart->workerId < $workerStart->server->setting['worker_num']) {
|
||||
$this->processName($workerStart->server, 'Worker');
|
||||
set_env('environmental', Kiri::WORKER);
|
||||
} else {
|
||||
$this->processName($workerStart->server, 'Tasker');
|
||||
set_env('environmental', Kiri::TASK);
|
||||
}
|
||||
set_env('environmental_worker_id', $workerStart->workerId);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $workerId
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function onWorkerStart(Server $server, int $workerId): void
|
||||
{
|
||||
$this->dispatch->dispatch(new OnBeforeWorkerStart($server, $workerId));
|
||||
if ($workerId < $server->setting['worker_num']) {
|
||||
$this->dispatch->dispatch(new OnWorkerStart($server, $workerId));
|
||||
} else {
|
||||
$this->dispatch->dispatch(new OnTaskerStart($server, $workerId));
|
||||
}
|
||||
$this->dispatch->dispatch(new OnAfterWorkerStart($server, $workerId));
|
||||
}
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $workerId
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function onWorkerStart(Server $server, int $workerId): void
|
||||
{
|
||||
try {
|
||||
$this->dispatch->dispatch(new OnBeforeWorkerStart($server, $workerId));
|
||||
if ($workerId < $server->setting['worker_num']) {
|
||||
CoordinatorManager::utility(Coordinator::WORKER_START)->waite();
|
||||
|
||||
$this->dispatch->dispatch(new OnWorkerStart($server, $workerId));
|
||||
} else {
|
||||
$this->dispatch->dispatch(new OnTaskerStart($server, $workerId));
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
\Kiri::getLogger()->json_log($exception);
|
||||
} finally {
|
||||
$this->dispatch->dispatch(new OnAfterWorkerStart($server, $workerId));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param string $prefix
|
||||
* @return void
|
||||
*/
|
||||
protected function processName(Server $server, string $prefix): void
|
||||
{
|
||||
Kiri::setProcessName(sprintf($prefix . ' Process[%d].%d', $server->worker_pid, $server->worker_id));
|
||||
}
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param string $prefix
|
||||
* @return void
|
||||
*/
|
||||
protected function processName(Server $server, string $prefix): void
|
||||
{
|
||||
Kiri::setProcessName(sprintf($prefix . '[%d]', $server->worker_pid));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $workerId
|
||||
* @throws
|
||||
*/
|
||||
public function onWorkerStop(Server $server, int $workerId): void
|
||||
{
|
||||
event(new OnWorkerStop($server, $workerId));
|
||||
Timer::clearAll();
|
||||
}
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $workerId
|
||||
* @throws
|
||||
*/
|
||||
public function onWorkerStop(Server $server, int $workerId): void
|
||||
{
|
||||
event(new OnWorkerStop($server, $workerId));
|
||||
Timer::clearAll();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $workerId
|
||||
* @throws
|
||||
*/
|
||||
public function onWorkerExit(Server $server, int $workerId): void
|
||||
{
|
||||
event(new OnWorkerExit($server, $workerId));
|
||||
}
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $workerId
|
||||
* @throws
|
||||
*/
|
||||
public function onWorkerExit(Server $server, int $workerId): void
|
||||
{
|
||||
event(new OnWorkerExit($server, $workerId));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $worker_id
|
||||
* @param int $worker_pid
|
||||
* @param int $exit_code
|
||||
* @param int $signal
|
||||
* @throws
|
||||
*/
|
||||
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));
|
||||
/**
|
||||
* @param Server $server
|
||||
* @param int $worker_id
|
||||
* @param int $worker_pid
|
||||
* @param int $exit_code
|
||||
* @param int $signal
|
||||
* @throws
|
||||
*/
|
||||
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));
|
||||
|
||||
debug_print_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
|
||||
$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));
|
||||
debug_print_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
|
||||
|
||||
error($message);
|
||||
|
||||
$this->system_mail($message);
|
||||
}
|
||||
/** @var RequestInterface $context */
|
||||
$context = Kiri\Di\Context::get(RequestInterface::class);
|
||||
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));
|
||||
} 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),
|
||||
$context->getMethod(), $context->getUri()->getPath(), $context->getUri()->getQuery());
|
||||
}
|
||||
$this->getLogger()->println($message);
|
||||
$this->system_mail($message);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $messageContent
|
||||
* @throws
|
||||
*/
|
||||
protected function system_mail($messageContent): void
|
||||
{
|
||||
try {
|
||||
$email = config('email', ['enable' => false]);
|
||||
if (!empty($email) && ($email['enable'] ?? false)) {
|
||||
Help::sendEmail($email, 'Service Error', $messageContent);
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
error($e, ['email']);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @param $messageContent
|
||||
* @throws
|
||||
*/
|
||||
protected function system_mail($messageContent): void
|
||||
{
|
||||
try {
|
||||
$email = config('email', ['enable' => false]);
|
||||
if (!empty($email) && ($email['enable'] ?? false)) {
|
||||
Help::sendEmail($email, 'Service Error', $messageContent);
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
\Kiri::getLogger()->json_log($e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
-376
@@ -1,376 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Kiri\Server;
|
||||
|
||||
use Kiri\Di\Context;
|
||||
use Kiri\Router\Router;
|
||||
use Kiri\Server\Abstracts\BaseProcess;
|
||||
use Kiri\Server\Events\OnWorkerStart;
|
||||
use Swoole\Coroutine;
|
||||
use Swoole\Event;
|
||||
use Swoole\Process;
|
||||
|
||||
class HotReload extends BaseProcess
|
||||
{
|
||||
|
||||
/**
|
||||
* @var array|mixed
|
||||
*/
|
||||
private array $watchFiles = [];
|
||||
|
||||
|
||||
private array $md5Map = [];
|
||||
|
||||
/**
|
||||
* @var array|string[]
|
||||
*/
|
||||
private array $dirs = [APP_PATH . 'app', APP_PATH . 'routes'];
|
||||
|
||||
|
||||
private bool $forceFile = false;
|
||||
|
||||
|
||||
protected mixed $inotify = null;
|
||||
|
||||
|
||||
/**
|
||||
* @param Router $router
|
||||
*/
|
||||
public function __construct(public Router $router)
|
||||
{
|
||||
on(OnWorkerStart::class, [$this->router, 'scan_build_route']);
|
||||
|
||||
$this->forceFile = \config('reload.forceFile', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getName(): string
|
||||
{
|
||||
// TODO: Change the autogenerated stub
|
||||
return '[' . \config('id', 'system-service') . '].hot.load';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function onSigterm(): static
|
||||
{
|
||||
// TODO: Implement onSigterm() method.
|
||||
if (Context::inCoroutine()) {
|
||||
Coroutine::create(fn() => $this->onShutdown(Coroutine::waitSignal(SIGTERM | SIGINT)));
|
||||
} else {
|
||||
pcntl_signal(SIGTERM, [$this, 'onStop']);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $data
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function onStop($data): void
|
||||
{
|
||||
$this->clearWatch();
|
||||
|
||||
if (is_resource($this->inotify)) {
|
||||
Event::del($this->inotify);
|
||||
}
|
||||
|
||||
$this->onShutdown($data);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Process|null $process
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function process(?Process $process): void
|
||||
{
|
||||
// TODO: Implement process() method.
|
||||
if (!$this->forceFile && extension_loaded('inotify')) {
|
||||
$this->onInotifyReload();
|
||||
} else {
|
||||
$this->onCrontabReload();
|
||||
}
|
||||
$process->exit(0);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
private function onCrontabReload(): void
|
||||
{
|
||||
$this->loadDirs();
|
||||
$this->tick();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
private function onInotifyReload(): void
|
||||
{
|
||||
$this->inotify = inotify_init();
|
||||
foreach ($this->dirs as $dir) {
|
||||
if (!is_dir($dir)) {
|
||||
continue;
|
||||
}
|
||||
$this->watch(rtrim($dir, '/'));
|
||||
}
|
||||
Event::add($this->inotify, fn() => $this->check());
|
||||
Event::cycle(fn() => function () {
|
||||
Event::dispatch();
|
||||
}, true);
|
||||
Event::wait();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $isReload
|
||||
* @throws
|
||||
*/
|
||||
private function loadDirs(bool $isReload = false): void
|
||||
{
|
||||
foreach ($this->dirs as $value) {
|
||||
if (is_bool($path = realpath($value))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!is_dir($path)) continue;
|
||||
|
||||
$this->loadByDir($path, $isReload);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws
|
||||
*/
|
||||
public function tick(): void
|
||||
{
|
||||
$isReloading = Context::get('isReloading', false);
|
||||
if ($isReloading) {
|
||||
return;
|
||||
}
|
||||
|
||||
$pid = (int)file_get_contents(storage('.swoole.pid'));
|
||||
if ($pid <= 0 || !Process::kill($pid, 0) || $this->isStop()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->loadDirs(true);
|
||||
|
||||
sleep(2);
|
||||
|
||||
$this->tick();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $path
|
||||
* @param bool $isReload
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
private function loadByDir($path, bool $isReload = false): void
|
||||
{
|
||||
if (!is_string($path) || $this->isStop()) {
|
||||
return;
|
||||
}
|
||||
$path = rtrim($path, '/');
|
||||
foreach (glob(realpath($path) . '/*') as $value) {
|
||||
if ($this->isStop()) {
|
||||
break;
|
||||
}
|
||||
if (is_dir($value)) {
|
||||
$this->loadByDir($value, $isReload);
|
||||
}
|
||||
if (is_file($value)) {
|
||||
if ($this->checkFile($value, $isReload)) {
|
||||
$this->timerReload();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @param $isReload
|
||||
* @return bool
|
||||
*/
|
||||
private function checkFile($value, $isReload): bool
|
||||
{
|
||||
$md5 = md5($value);
|
||||
$mTime = filectime($value);
|
||||
if (!isset($this->md5Map[$md5])) {
|
||||
if ($isReload) {
|
||||
return true;
|
||||
}
|
||||
$this->md5Map[$md5] = $mTime;
|
||||
} else {
|
||||
if ($this->md5Map[$md5] != $mTime) {
|
||||
if ($isReload) {
|
||||
return true;
|
||||
}
|
||||
$this->md5Map[$md5] = $mTime;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 开始监听
|
||||
*/
|
||||
public function check(): void
|
||||
{
|
||||
if (!($events = inotify_read($this->inotify))) {
|
||||
return;
|
||||
}
|
||||
if (Context::exists('isReloading')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$eventList = [IN_CREATE, IN_DELETE, IN_MODIFY, IN_MOVED_TO, IN_MOVED_FROM];
|
||||
foreach ($events as $ev) {
|
||||
if (empty($ev['name'])) {
|
||||
continue;
|
||||
}
|
||||
if ($ev['mask'] == IN_IGNORED) {
|
||||
continue;
|
||||
}
|
||||
if (!in_array($ev['mask'], $eventList)) {
|
||||
continue;
|
||||
}
|
||||
$fileType = strstr($ev['name'], '.');
|
||||
//非重启类型
|
||||
if ($fileType !== '.php') {
|
||||
continue;
|
||||
}
|
||||
if (Context::exists('swoole_timer_after')) {
|
||||
return;
|
||||
}
|
||||
$int = @swoole_timer_after(2000, fn() => $this->reload());
|
||||
Context::set('swoole_timer_after', $int);
|
||||
Context::set('isReloading', true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws
|
||||
*/
|
||||
public function reload(): void
|
||||
{
|
||||
$this->trigger_reload();
|
||||
|
||||
$this->clearWatch();
|
||||
foreach ($this->dirs as $root) {
|
||||
$this->watch($root);
|
||||
}
|
||||
Context::remove('swoole_timer_after');
|
||||
Context::remove('isReloading');
|
||||
$this->md5Map = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws
|
||||
*/
|
||||
public function timerReload(): void
|
||||
{
|
||||
Context::set('isReloading', true);
|
||||
$this->trigger_reload();
|
||||
|
||||
Context::set('swoole_timer_after', -1);
|
||||
|
||||
$this->loadDirs();
|
||||
|
||||
Context::set('isReloading', false);
|
||||
|
||||
$this->tick();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 重启
|
||||
* @throws
|
||||
*/
|
||||
public function trigger_reload(): void
|
||||
{
|
||||
$this->logger->failure('Wait trigger server Reload' . PHP_EOL);
|
||||
di(ServerInterface::class)->reload(false);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws
|
||||
*/
|
||||
public function clearWatch(): void
|
||||
{
|
||||
foreach ($this->watchFiles as $wd) {
|
||||
try {
|
||||
inotify_rm_watch($this->inotify, $wd);
|
||||
} catch (\Throwable $exception) {
|
||||
trigger_print_error($exception, 'throwable');
|
||||
}
|
||||
}
|
||||
$this->watchFiles = [];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $dir
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function watch($dir): bool
|
||||
{
|
||||
//目录不存在
|
||||
if (!is_dir($dir)) {
|
||||
return trigger_print_error("[$dir] is not a directory.");
|
||||
}
|
||||
//避免重复监听
|
||||
if (isset($this->watchFiles[$dir])) {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
if (in_array($dir, [APP_PATH . 'commands', APP_PATH . '.git', APP_PATH . '.gitee'])) {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
$wd = @inotify_add_watch($this->inotify, $dir, IN_MODIFY | IN_DELETE | IN_CREATE | IN_MOVE);
|
||||
$this->watchFiles[$dir] = $wd;
|
||||
|
||||
$files = scandir($dir);
|
||||
foreach ($files as $f) {
|
||||
if ($f == '.' or $f == '..' or $f == 'runtime' or preg_match('/\.txt/', $f) or preg_match('/\.sql/', $f) or preg_match('/\.log/', $f)) {
|
||||
continue;
|
||||
}
|
||||
$path = $dir . '/' . $f;
|
||||
//递归目录
|
||||
if (is_dir($path)) {
|
||||
$this->watch($path);
|
||||
continue;
|
||||
}
|
||||
|
||||
//检测文件类型
|
||||
if (strstr($f, '.') == '.php') {
|
||||
$wd = @inotify_add_watch($this->inotify, $path, IN_MODIFY | IN_DELETE | IN_CREATE | IN_MOVE);
|
||||
$this->watchFiles[$path] = $wd;
|
||||
}
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
|
||||
namespace Kiri\Server\Processes;
|
||||
|
||||
|
||||
use Swoole\Coroutine;
|
||||
use Swoole\Process;
|
||||
use const SIGHUP;
|
||||
use const SIGTERM;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
abstract class AbstractProcess implements OnProcessInterface
|
||||
{
|
||||
|
||||
private bool $stop = false;
|
||||
|
||||
|
||||
public Process $process;
|
||||
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected bool $redirect_stdin_and_stdout = FALSE;
|
||||
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected int $pipe_type = SOCK_DGRAM;
|
||||
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected bool $enable_coroutine = false;
|
||||
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected bool $enable_queue = false;
|
||||
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public string $name = '';
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isEnableQueue(): bool
|
||||
{
|
||||
return $this->enable_queue;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getName(): string
|
||||
{
|
||||
if (empty($this->name)) {
|
||||
$this->name = uniqid('p.');
|
||||
}
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isStop(): bool
|
||||
{
|
||||
return $this->stop;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function getRedirectStdinAndStdout(): bool
|
||||
{
|
||||
return $this->redirect_stdin_and_stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getPipeType(): int
|
||||
{
|
||||
return $this->pipe_type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isEnableCoroutine(): bool
|
||||
{
|
||||
return $this->enable_coroutine;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function stop(): void
|
||||
{
|
||||
$this->stop = true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
abstract public function onSigterm(): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param Process $process
|
||||
* @return AbstractProcess
|
||||
*/
|
||||
public function onShutdown(Process $process): static
|
||||
{
|
||||
$this->process = $process;
|
||||
if ($this->enable_coroutine) {
|
||||
$array['enable_deadlock_check'] = false;
|
||||
$array['deadlock_check_disable_trace'] = false;
|
||||
$array['exit_condition'] = [$this, 'exit_condition'];
|
||||
Coroutine::set($array);
|
||||
Coroutine::create(fn() => $this->coroutineWaitSignal());
|
||||
} else {
|
||||
$process::signal(SIGTERM | SIGINT | SIGUSR1, [$this, 'pointWaitSignal']);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
public function exit_condition(): bool
|
||||
{
|
||||
return Coroutine::stats()['coroutine_num'] === 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $signal
|
||||
* @return void
|
||||
*/
|
||||
public function pointWaitSignal($signal): void
|
||||
{
|
||||
$this->stop = true;
|
||||
|
||||
$this->onSigterm();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function coroutineWaitSignal(): void
|
||||
{
|
||||
$value = Coroutine::waitSignal(SIGTERM);
|
||||
if ($value) {
|
||||
$this->stop = true;
|
||||
}
|
||||
$this->onSigterm();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,25 +1,25 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Kiri\Server\Contract;
|
||||
|
||||
|
||||
use Swoole\Process;
|
||||
|
||||
|
||||
/**
|
||||
* Interface BaseProcess
|
||||
* @package Contract
|
||||
*/
|
||||
interface OnProcessInterface
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param ?Process $process
|
||||
*/
|
||||
public function process(?Process $process): void;
|
||||
|
||||
|
||||
|
||||
}
|
||||
<?php
|
||||
|
||||
|
||||
namespace Kiri\Server\Processes;
|
||||
|
||||
|
||||
use Swoole\Process;
|
||||
|
||||
|
||||
/**
|
||||
* Interface AbstractProcess
|
||||
* @package Contract
|
||||
*/
|
||||
interface OnProcessInterface
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param ?Process $process
|
||||
*/
|
||||
public function process(?Process $process): void;
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace Kiri\Server\Processes;
|
||||
|
||||
use Exception;
|
||||
use Kiri;
|
||||
use Swoole\Process;
|
||||
|
||||
trait TraitProcess
|
||||
{
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private array $_process = [];
|
||||
|
||||
|
||||
/**
|
||||
* @param string|array|AbstractProcess $class
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function addProcess(string|array|AbstractProcess $class): void
|
||||
{
|
||||
if (!is_array($class)) $class = [$class];
|
||||
foreach ($class as $name) {
|
||||
if (is_string($name)) $name = Kiri::getDi()->get($name);
|
||||
if (isset($this->_process[$name->getName()])) {
|
||||
throw new Exception('AbstractProcess(' . $name->getName() . ') is exists.');
|
||||
}
|
||||
$this->_process[$name->getName()] = $this->genProcess($name);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param AbstractProcess $name
|
||||
* @return Process
|
||||
*/
|
||||
private function genProcess(AbstractProcess $name): Process
|
||||
{
|
||||
return new Process(function (Process $process) use ($name) {
|
||||
$process->name('[' . \config('site.id', 'system-service') . '].' . $name->getName() . '[' . $process->pid . ']');
|
||||
$name->onShutdown($process)->process($process);
|
||||
},
|
||||
$name->getRedirectStdinAndStdout(),
|
||||
$name->getPipeType(),
|
||||
$name->isEnableCoroutine());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return AbstractProcess|null
|
||||
*/
|
||||
public function getProcess(string $name): ?Process
|
||||
{
|
||||
return $this->_process[$name] ?? null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getProcesses(): array
|
||||
{
|
||||
return $this->_process;
|
||||
}
|
||||
}
|
||||
+40
-26
@@ -6,17 +6,21 @@ namespace Kiri\Server;
|
||||
|
||||
use Exception;
|
||||
use Kiri;
|
||||
use Kiri\Server\Events\OnWorkerStart;
|
||||
use Kiri\Events\EventProvider;
|
||||
use Kiri\Events\EventDispatch;
|
||||
use Kiri\Router\Router;
|
||||
use Kiri\Server\Abstracts\AsyncServer;
|
||||
use Kiri\Server\Events\OnShutdown;
|
||||
use ReflectionException;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use function config;
|
||||
use Kiri\Server\Abstracts\HotReload;
|
||||
use Kiri\Di\Inject\Container;
|
||||
|
||||
defined('ROUTER_TYPE_HTTP') or define('ROUTER_TYPE_HTTP', 'http');
|
||||
defined('PID_PATH') or define('PID_PATH', APP_PATH . 'storage/server.pid');
|
||||
@@ -29,25 +33,36 @@ class ServerCommand extends Command
|
||||
{
|
||||
|
||||
|
||||
public AsyncServer $manager;
|
||||
public State $state;
|
||||
public EventDispatch $dispatch;
|
||||
public Router $router;
|
||||
#[Container(State::class)]
|
||||
public State $state;
|
||||
|
||||
|
||||
/**
|
||||
* @param string|null $name
|
||||
* @throws Exception
|
||||
* @var ContainerInterface
|
||||
*/
|
||||
public function __construct(string $name = null)
|
||||
{
|
||||
parent::__construct($name);
|
||||
$container = Kiri::getDi();
|
||||
$this->manager = $container->get(AsyncServer::class);
|
||||
$this->state = $container->get(State::class);
|
||||
$this->dispatch = $container->get(EventDispatch::class);
|
||||
$this->router = $container->get(Router::class);
|
||||
}
|
||||
#[Container(ContainerInterface::class)]
|
||||
public ContainerInterface $container;
|
||||
|
||||
|
||||
/**
|
||||
* @var AsyncServer
|
||||
*/
|
||||
#[Container(AsyncServer::class)]
|
||||
public AsyncServer $asyncServer;
|
||||
|
||||
|
||||
/**
|
||||
* @var EventDispatch
|
||||
*/
|
||||
#[Container(EventDispatch::class)]
|
||||
public EventDispatch $eventDispatch;
|
||||
|
||||
|
||||
/**
|
||||
* @var EventProvider
|
||||
*/
|
||||
#[Container(EventProvider::class)]
|
||||
public EventProvider $eventProvider;
|
||||
|
||||
|
||||
/**
|
||||
@@ -99,12 +114,12 @@ class ServerCommand extends Command
|
||||
*/
|
||||
protected function stop(): int
|
||||
{
|
||||
$configs = config('server', []);
|
||||
$instances = $this->manager->sortService($configs['ports'] ?? []);
|
||||
$configs = config('servers.server', []);
|
||||
$instances = $this->asyncServer->sortService($configs['ports'] ?? []);
|
||||
foreach ($instances as $config) {
|
||||
$this->state->exit($config->port);
|
||||
}
|
||||
$this->dispatch->dispatch(new OnShutdown());
|
||||
$this->eventDispatch->dispatch(new OnShutdown());
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -116,15 +131,14 @@ class ServerCommand extends Command
|
||||
*/
|
||||
protected function start(InputInterface $input): int
|
||||
{
|
||||
$daemon = (int)$input->getOption('daemon');
|
||||
if (config('reload.hot', false) === true) {
|
||||
$this->manager->addProcess(HotReload::class);
|
||||
$this->asyncServer->addProcess(config('process', []));
|
||||
if (\config('servers.reload.hot', false) === true) {
|
||||
$this->asyncServer->addProcess([HotReload::class]);
|
||||
} else {
|
||||
$this->router->scan_build_route();
|
||||
di(Router::class)->scan_build_route();
|
||||
}
|
||||
$this->manager->addProcess(config('processes', []));
|
||||
$this->manager->initCoreServers(config('server', []), $daemon);
|
||||
$this->manager->start();
|
||||
$this->asyncServer->initCoreServers(config('servers.server', []), (int)$input->getOption('daemon'));
|
||||
$this->asyncServer->start();
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -23,6 +23,6 @@ class ServerProviders extends Providers
|
||||
$server = $this->container->get(ServerCommand::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
|
||||
{
|
||||
$this->servers = config('server.ports');
|
||||
$this->servers = config('servers.server.ports');
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -6,12 +6,12 @@ class OnTaskFinish
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param int $task_id
|
||||
* @param mixed $data
|
||||
*/
|
||||
public function __construct(int $task_id, mixed $data)
|
||||
{
|
||||
}
|
||||
/**
|
||||
* @param int $task_id
|
||||
* @param 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;
|
||||
|
||||
|
||||
}
|
||||
+18
-19
@@ -5,13 +5,8 @@ namespace Kiri\Server\Task;
|
||||
|
||||
use Kiri;
|
||||
use Kiri\Router\Base\ExceptionHandlerDispatcher;
|
||||
use Kiri\Router\DataGrip;
|
||||
use Kiri\Router\Interface\ExceptionHandlerInterface;
|
||||
use Kiri\Server\Constant;
|
||||
use Psr\Container\ContainerExceptionInterface;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Container\NotFoundExceptionInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Swoole\Server;
|
||||
|
||||
/**
|
||||
@@ -25,17 +20,15 @@ class Task
|
||||
|
||||
|
||||
/**
|
||||
* @param ContainerInterface $container
|
||||
* @throws ContainerExceptionInterface
|
||||
* @throws NotFoundExceptionInterface
|
||||
*
|
||||
*/
|
||||
public function __construct(public ContainerInterface $container)
|
||||
public function __construct()
|
||||
{
|
||||
$exception = \config('exception.task');
|
||||
$exception = \config('servers.task.exception');
|
||||
if (!in_array(ExceptionHandlerInterface::class, class_implements($exception))) {
|
||||
$exception = ExceptionHandlerDispatcher::class;
|
||||
}
|
||||
$this->exception = $this->container->get($exception);
|
||||
$this->exception = Kiri::getDi()->get($exception);
|
||||
}
|
||||
|
||||
|
||||
@@ -74,20 +67,26 @@ class Task
|
||||
* @param int $task_id
|
||||
* @param int $src_worker_id
|
||||
* @param mixed $data
|
||||
* @return mixed
|
||||
* @return void
|
||||
* @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 {
|
||||
$data = json_decode($data, true);
|
||||
if (is_null($data)) {
|
||||
return null;
|
||||
[$handler, $params] = [$data[0], $data[1]];
|
||||
|
||||
$handler = Kiri::getDi()->make($handler, $params);
|
||||
if (!($handler instanceof OnTaskInterface)) {
|
||||
throw new \Exception('Task process must implements ' . OnTaskInterface::class);
|
||||
}
|
||||
$data[0] = Kiri::getDi()->get($data[0]);
|
||||
return call_user_func($data, $task_id, $src_worker_id);
|
||||
|
||||
$response = call_user_func([$handler, 'process'], $task_id, $src_worker_id);
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+34
-12
@@ -2,30 +2,50 @@
|
||||
|
||||
namespace Kiri\Server\Task;
|
||||
|
||||
use Kiri\Di\Inject\Container;
|
||||
use Exception;
|
||||
use Kiri\Server\ServerInterface;
|
||||
|
||||
class TaskExecute implements TaskInterface
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @var ServerInterface
|
||||
* @param string $handler
|
||||
* @param mixed $data
|
||||
* @param int $dstWorkerId
|
||||
* @param callable|null $finishFinishCallback
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
#[Container(ServerInterface::class)]
|
||||
public ServerInterface $server;
|
||||
|
||||
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 float $timeout
|
||||
* @param int $dstWorkerId
|
||||
* @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
|
||||
{
|
||||
return $this->server->taskwait($data, $timeout, $dstWorkerId);
|
||||
$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);
|
||||
|
||||
return $server->taskwait([$handler, $data], $timeout, $dstWorkerId);
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +56,9 @@ class TaskExecute implements TaskInterface
|
||||
*/
|
||||
public function taskCo(array $tasks, float $timeout = 0.5): false|array
|
||||
{
|
||||
return $this->server->taskCo($tasks, $timeout);
|
||||
$server = \Kiri::getDi()->get(ServerInterface::class);
|
||||
|
||||
return $server->taskCo($tasks, $timeout);
|
||||
}
|
||||
|
||||
|
||||
@@ -47,8 +69,8 @@ class TaskExecute implements TaskInterface
|
||||
*/
|
||||
public function taskWaitMulti(array $tasks, float $timeout = 0.5): false|array
|
||||
{
|
||||
return $this->server->taskWaitMulti($tasks, $timeout);
|
||||
$server = \Kiri::getDi()->get(ServerInterface::class);
|
||||
|
||||
return $server->taskWaitMulti($tasks, $timeout);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+21
-8
@@ -7,11 +7,24 @@ interface TaskInterface
|
||||
|
||||
|
||||
/**
|
||||
* @param array $tasks
|
||||
* @param float $timeout
|
||||
* @return false|array
|
||||
* @param string $handler
|
||||
* @param mixed $data
|
||||
* @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
|
||||
@@ -20,12 +33,12 @@ interface TaskInterface
|
||||
*/
|
||||
public function taskCo(array $tasks, float $timeout = 0.5): false|array;
|
||||
|
||||
|
||||
/**
|
||||
* @param mixed $data
|
||||
* @param array $tasks
|
||||
* @param float $timeout
|
||||
* @param int $dstWorkerId
|
||||
* @return mixed
|
||||
* @return false|array
|
||||
*/
|
||||
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": {
|
||||
"php": ">=8.0",
|
||||
"php": ">=8.4",
|
||||
"ext-json": "*",
|
||||
"composer-runtime-api": "^2.0",
|
||||
"psr/http-server-middleware": "^1.0",
|
||||
|
||||
Reference in New Issue
Block a user