Files
kiri-core/HttpServer/Events/OnWorkerStart.php
T

103 lines
2.3 KiB
PHP
Raw Normal View History

2020-08-31 01:27:08 +08:00
<?php
2020-10-29 18:17:25 +08:00
declare(strict_types=1);
2020-08-31 01:27:08 +08:00
2020-09-02 11:38:47 +08:00
namespace HttpServer\Events;
2020-08-31 01:27:08 +08:00
2021-04-09 02:29:40 +08:00
use Annotation\Annotation;
2020-08-31 01:27:08 +08:00
use Exception;
2020-09-04 01:05:33 +08:00
use HttpServer\Abstracts\Callback;
2020-08-31 01:27:08 +08:00
use Snowflake\Event;
2020-09-07 16:50:26 +08:00
use Snowflake\Exception\ConfigException;
2020-08-31 01:27:08 +08:00
use Snowflake\Snowflake;
use Swoole\Server;
/**
* Class OnWorkerStart
2020-09-02 11:38:47 +08:00
* @package HttpServer\Events
2020-08-31 01:27:08 +08:00
*/
class OnWorkerStart extends Callback
{
2021-04-09 02:29:40 +08:00
/**
* @throws Exception
*/
2021-04-09 02:53:03 +08:00
public function injectLoader($isWorker = false)
2021-04-09 02:29:40 +08:00
{
$runtime = file_get_contents(storage('runtime.php'));
$annotation = Snowflake::app()->getAnnotation();
$annotation->setLoader(unserialize($runtime));
2021-04-09 03:12:37 +08:00
if ($isWorker) {
$annotation->runtime(CONTROLLER_PATH);
$annotation->runtime(APP_PATH, CONTROLLER_PATH);
} else {
$annotation->runtime(MODEL_PATH);
}
return $isWorker;
2021-04-09 02:29:40 +08:00
}
2021-04-07 02:21:29 +08:00
/**
* @param Server $server
* @param int $worker_id
*
* @return mixed
* @throws Exception
*/
public function onHandler(Server $server, int $worker_id): void
{
2021-04-09 03:12:37 +08:00
putenv('state=start');
putenv('worker=' . $worker_id);
2021-04-09 03:14:08 +08:00
$isWorker = $this->injectLoader($this->isWorker($worker_id));
$this->{$isWorker ? 'onWorker' : 'onTask'}($server);
2021-04-07 02:21:29 +08:00
}
2021-04-09 02:35:29 +08:00
/**
* @param Server $server
* @param int $worker_id
* @return bool
*/
private function isWorker(int $worker_id): bool
{
return $worker_id < $this->server->setting['worker_num'];
}
2021-04-07 02:21:29 +08:00
/**
* @param Server $server
* @param int $worker_id
* @throws Exception
*/
2021-04-09 03:12:37 +08:00
public function onTask(Server $server)
2021-04-07 02:21:29 +08:00
{
putenv('environmental=' . Snowflake::TASK);
Snowflake::setTaskId($server->worker_pid);
fire(Event::SERVER_TASK_START);
}
/**
* @param Server $server
* @param int $worker_id
* @throws Exception
*/
2021-04-09 03:12:37 +08:00
public function onWorker(Server $server)
2021-04-07 02:21:29 +08:00
{
Snowflake::setWorkerId($server->worker_pid);
putenv('environmental=' . Snowflake::WORKER);
try {
2021-04-09 03:12:37 +08:00
fire(Event::SERVER_WORKER_START, [getenv('worker')]);
2021-04-07 02:21:29 +08:00
} catch (\Throwable $exception) {
$this->addError($exception, 'throwable');
write($exception->getMessage(), 'worker');
}
}
2021-02-27 04:48:44 +08:00
2021-02-28 17:15:06 +08:00
2020-08-31 01:27:08 +08:00
}