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

114 lines
2.6 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;
2021-05-02 04:12:31 +08:00
use Swoole\Coroutine;
2021-04-09 10:28:01 +08:00
use Swoole\Coroutine\System;
2020-08-31 01:27:08 +08:00
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 10:34:33 +08:00
2021-04-23 03:12:00 +08:00
/**
* @param Server $server
* @param int $worker_id
*
* @return mixed
* @throws Exception
*/
public function onHandler(Server $server, int $worker_id): void
{
putenv('state=start');
putenv('worker=' . $worker_id);
2021-05-02 04:12:31 +08:00
$annotation = $this->settings();
2021-04-23 03:12:00 +08:00
if ($worker_id < $server->setting['worker_num']) {
$this->onWorker($server, $annotation);
} else {
$this->onTask($server, $annotation);
}
}
2021-05-02 04:12:31 +08:00
/**
* @return \Annotation\Annotation
* @throws \Exception
*/
private function settings(): Annotation
{
$content = System::readFile(storage('runtime.php'));
$annotation = Snowflake::app()->getAnnotation();
$annotation->setLoader(unserialize($content));
return $annotation;
}
2021-04-23 03:12:00 +08:00
/**
* @param Server $server
* @param int $worker_id
* @return bool
*/
private function isWorker(Server $server, int $worker_id): bool
{
return $worker_id < $server->setting['worker_num'];
}
/**
* @param Server $server
* @param Annotation $annotation
* @throws ConfigException
* @throws Exception
*/
public function onTask(Server $server, Annotation $annotation)
{
putenv('environmental=' . Snowflake::TASK);
$annotation->runtime(directory('app'), [
CONTROLLER_PATH,
TASK_PATH,
]);
name($server->worker_pid, 'Task#' . $server->worker_id);
Snowflake::setTaskId($server->worker_pid);
fire(Event::SERVER_TASK_START);
}
/**
* @param Server $server
* @param Annotation $annotation
* @throws Exception
*/
public function onWorker(Server $server, Annotation $annotation)
{
name($server->worker_pid, 'Worker#' . $server->worker_id);
$time = microtime(true);
$annotation->runtime(CONTROLLER_PATH);
$this->debug('use time.' . (microtime(true) - $time));
$annotation->runtime(directory('app'), CONTROLLER_PATH);
Snowflake::setWorkerId($server->worker_pid);
putenv('environmental=' . Snowflake::WORKER);
fire(Event::SERVER_WORKER_START, [getenv('worker')]);
}
2021-02-27 04:48:44 +08:00
2020-08-31 01:27:08 +08:00
}