Files
kiri-core/http-server/Worker/OnWorkerStart.php
T

106 lines
2.3 KiB
PHP
Raw Normal View History

2021-08-29 01:18:42 +08:00
<?php
namespace Server\Worker;
use Annotation\Annotation;
2021-08-29 04:44:33 +08:00
use Annotation\Inject;
2021-08-29 01:18:42 +08:00
use Exception;
2021-08-29 04:44:33 +08:00
use Http\Route\Router;
2021-08-29 01:18:42 +08:00
use Kiri\Abstracts\Config;
2021-09-04 00:11:53 +08:00
use Kiri\Di\NoteManager;
2021-08-29 01:18:42 +08:00
use Kiri\Exception\ConfigException;
use Kiri\Kiri;
use Psr\EventDispatcher\EventDispatcherInterface;
use ReflectionException;
2021-09-04 00:08:34 +08:00
use Server\ServerManager;
2021-08-29 01:18:42 +08:00
class OnWorkerStart implements EventDispatcherInterface
{
2021-09-06 14:20:04 +08:00
/**
* @var Annotation
*/
2021-09-06 14:30:20 +08:00
#[Inject(Annotation::class)]
public Annotation $annotation;
2021-08-29 01:18:42 +08:00
2021-09-06 14:20:04 +08:00
/**
* @var Router
*/
2021-09-06 14:30:20 +08:00
#[Inject(Router::class)]
public Router $router;
2021-08-29 01:18:42 +08:00
2021-09-06 14:20:04 +08:00
/**
* @param object $event
* @return void
* @throws ConfigException
* @throws ReflectionException
* @throws Exception
*/
2021-09-06 14:30:20 +08:00
public function dispatch(object $event)
{
$isWorker = $event->workerId < $event->server->setting['worker_num'];
$this->interpretDirectory();
if ($isWorker) {
ServerManager::setEnv('environmental', Kiri::WORKER);
Kiri::getFactory()->getRouter()->_loader();
echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m Worker[%d].%d start.", $event->server->worker_pid, $event->workerId) . PHP_EOL;
$this->setProcessName(sprintf('Worker[%d].%d', $event->server->worker_pid, $event->workerId));
} else {
ServerManager::setEnv('environmental', Kiri::TASK);
echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m Tasker[%d].%d start.", $event->server->worker_pid, $event->workerId) . PHP_EOL;
$this->setProcessName(sprintf('Tasker[%d].%d', $event->server->worker_pid, $event->workerId));
}
}
/**
* @param $prefix
* @throws ConfigException
*/
protected function setProcessName($prefix)
{
if (Kiri::getPlatform()->isMac()) {
return;
}
$name = Config::get('id', 'system-service');
if (!empty($prefix)) {
$name .= '.' . $prefix;
}
swoole_set_process_name($name);
}
/**
* @throws ReflectionException
* @throws Exception
*/
private function interpretDirectory()
{
$di = Kiri::getDi();
$fileLists = $this->annotation->read(APP_PATH . 'app');
foreach ($fileLists->runtime(APP_PATH . 'app') as $class) {
foreach (NoteManager::getTargetNote($class) as $value) {
$value->execute($class);
}
$methods = $di->getMethodAttribute($class);
foreach ($methods as $method => $attribute) {
if (empty($attribute)) {
continue;
}
foreach ($attribute as $item) {
$item->execute($class, $method);
}
}
}
}
2021-08-29 01:18:42 +08:00
}