This commit is contained in:
2020-11-05 19:23:05 +08:00
parent 6b9134a064
commit 4dc3ff8e6f
+383 -389
View File
@@ -40,450 +40,444 @@ use Swoole\Runtime;
*/ */
class Server extends Application class Server extends Application
{ {
use Action; use Action;
const HTTP = 'HTTP'; const HTTP = 'HTTP';
const TCP = 'TCP'; const TCP = 'TCP';
const PACKAGE = 'PACKAGE'; const PACKAGE = 'PACKAGE';
const WEBSOCKET = 'WEBSOCKET'; const WEBSOCKET = 'WEBSOCKET';
private array $listening = []; private array $listening = [];
private array $server = [ private array $server = [
'HTTP' => [SWOOLE_TCP, Http::class], 'HTTP' => [SWOOLE_TCP, Http::class],
'TCP' => [SWOOLE_TCP, Receive::class], 'TCP' => [SWOOLE_TCP, Receive::class],
'PACKAGE' => [SWOOLE_UDP, Packet::class], 'PACKAGE' => [SWOOLE_UDP, Packet::class],
'WEBSOCKET' => [SWOOLE_SOCK_TCP, Websocket::class], 'WEBSOCKET' => [SWOOLE_SOCK_TCP, Websocket::class],
]; ];
/** @var Http|Websocket|Packet|Receive */ /** @var Http|Websocket|Packet|Receive */
private $baseServer; private $baseServer;
public int $daemon = 0; public int $daemon = 0;
private array $listenTypes = []; private array $listenTypes = [];
private array $process = []; private array $process = [];
/** /**
* @param $name * @param $name
* @param $process * @param $process
*/ */
public function addProcess($name, $process) public function addProcess($name, $process)
{ {
$this->process[$name] = $process; $this->process[$name] = $process;
} }
/** /**
* @param array $configs * @param array $configs
* @return Http|Packet|Receive|Websocket * @return Http|Packet|Receive|Websocket
* @throws Exception * @throws Exception
*/ */
public function initCore(array $configs) public function initCore(array $configs)
{ {
$annotation = Snowflake::app()->annotation; $annotation = Snowflake::app()->annotation;
$annotation->register('tcp', Tcp::class); $annotation->register('tcp', Tcp::class);
$annotation->register('http', Annotation::class); $annotation->register('http', Annotation::class);
$annotation->register('websocket', AWebsocket::class); $annotation->register('websocket', AWebsocket::class);
$this->enableCoroutine((bool)Config::get('settings.enable_coroutine')); $this->enableCoroutine((bool)Config::get('settings.enable_coroutine'));
$this->orders($configs); $this->orders($configs);
$this->onProcessListener(); $this->onProcessListener();
return $this->getServer(); return $this->getServer();
} }
private function orders($configs) private function orders($configs)
{ {
$servers = $this->sortServers($configs); $servers = $this->sortServers($configs);
foreach ($servers as $server) { foreach ($servers as $server) {
$this->create($server); $this->create($server);
if (!$this->baseServer) { if (!$this->baseServer) {
return null; return null;
} }
} }
} }
/** /**
* @return void * @return void
* *
* start server * start server
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function start() public function start()
{ {
$configs = Config::get('servers', true); $configs = Config::get('servers', true);
Snowflake::clearWorkerId(); Snowflake::clearWorkerId();
$baseServer = $this->initCore($configs); $baseServer = $this->initCore($configs);
if (!$baseServer) { if (!$baseServer) {
return; return;
} }
$baseServer->start(); $baseServer->start();
} }
/** /**
* @param $host * @param $host
* @param $Port * @param $Port
* @throws Exception * @throws Exception
*/ */
public function error_stop($host, $Port) public function error_stop($host, $Port)
{ {
$this->error(sprintf('Port %s::%d is already.', $host, $Port)); $this->error(sprintf('Port %s::%d is already.', $host, $Port));
if ($this->baseServer) { if ($this->baseServer) {
$this->baseServer->shutdown(); $this->baseServer->shutdown();
} }
} }
/** /**
* @return bool * @return bool
* @throws ConfigException * @throws ConfigException
*/ */
public function isRunner() public function isRunner()
{ {
$port = $this->sortServers(Config::get('servers')); $port = $this->sortServers(Config::get('servers'));
if (empty($port)) { if (empty($port)) {
return false; return false;
} }
if (Snowflake::isLinux()) { if (Snowflake::isLinux()) {
exec('netstat -tunlp | grep ' . $port[0]['port'], $output); exec('netstat -tunlp | grep ' . $port[0]['port'], $output);
} else { } else {
exec('lsof -i :' . $port[0]['port'] . ' | grep -i "LISTEN"', $output); exec('lsof -i :' . $port[0]['port'] . ' | grep -i "LISTEN"', $output);
} }
return !empty($output); return !empty($output);
} }
/** /**
* @return void * @return void
* *
* start server * start server
* @throws Exception * @throws Exception
*/ */
public function shutdown() public function shutdown()
{ {
$this->stop($this); $this->stop($this);
} }
/** /**
* @param bool $isEnable * @param bool $isEnable
*/ */
private function enableCoroutine($isEnable = true) private function enableCoroutine($isEnable = true)
{ {
if (!$isEnable) { if (!$isEnable) {
return; return;
} }
Runtime::enableCoroutine(true, SWOOLE_HOOK_TCP | Runtime::enableCoroutine(true, SWOOLE_HOOK_TCP |
SWOOLE_HOOK_UNIX | SWOOLE_HOOK_UNIX |
SWOOLE_HOOK_UDP | SWOOLE_HOOK_UDP |
SWOOLE_HOOK_UDG | SWOOLE_HOOK_UDG |
SWOOLE_HOOK_SSL | SWOOLE_HOOK_SSL |
SWOOLE_HOOK_TLS | SWOOLE_HOOK_TLS |
SWOOLE_HOOK_SLEEP | SWOOLE_HOOK_SLEEP |
SWOOLE_HOOK_STREAM_FUNCTION | SWOOLE_HOOK_STREAM_FUNCTION |
SWOOLE_HOOK_PROC SWOOLE_HOOK_PROC
); );
} }
/** /**
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function onProcessListener() public function onProcessListener()
{ {
$processes = Config::get('processes'); $processes = Config::get('processes');
if (!empty($processes) && is_array($processes)) { if (!empty($processes) && is_array($processes)) {
return $this->deliveryProcess(merge($processes, $this->process)); return $this->deliveryProcess(merge($processes, $this->process));
} }
return $this->deliveryProcess($this->process); return $this->deliveryProcess($this->process);
} }
/** /**
* @param $processes * @param $processes
* @throws Exception * @throws Exception
*/ */
private function deliveryProcess($processes) private function deliveryProcess($processes)
{ {
$application = Snowflake::app(); $application = Snowflake::app();
if (empty($processes) || !is_array($processes)) { if (empty($processes) || !is_array($processes)) {
return; return;
} }
foreach ($processes as $name => $process) { foreach ($processes as $name => $process) {
$is_enable_coroutine = true; $is_enable_coroutine = true;
if (is_array($process)) { if (is_array($process)) {
[$process, $is_enable_coroutine] = $process; [$process, $is_enable_coroutine] = $process;
} }
$this->debug(sprintf('Process %s', $process)); $this->debug(sprintf('Process %s', $process));
if (!is_string($process)) { if (!is_string($process)) {
continue; continue;
} }
$system = new $process(Snowflake::app(), $name, $is_enable_coroutine); $system = new $process(Snowflake::app(), $name, $is_enable_coroutine);
$this->baseServer->addProcess($system); $this->baseServer->addProcess($system);
$application->set($process, $system); $application->set($process, $system);
} }
} }
/** /**
* @param $daemon * @param $daemon
* @return Server * @return Server
*/ */
public function setDaemon($daemon) public function setDaemon($daemon)
{ {
if (!in_array($daemon, [0, 1])) { if (!in_array($daemon, [0, 1])) {
return $this; return $this;
} }
$this->daemon = $daemon; $this->daemon = $daemon;
return $this; return $this;
} }
/** /**
* @return Http|Websocket|Packet|Receive * @return Http|Websocket|Packet|Receive
*/ */
public function getServer() public function getServer()
{ {
return $this->baseServer; return $this->baseServer;
} }
/** /**
* @param $config * @param $config
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function create($config) private function create($config)
{ {
$settings = Config::get('settings', false, []); $settings = Config::get('settings', false, []);
if (!isset($this->server[$config['type']])) { if (!isset($this->server[$config['type']])) {
throw new Exception('Unknown server type(' . $config['type'] . ').'); throw new Exception('Unknown server type(' . $config['type'] . ').');
} }
$server = $this->dispatchCreate($config, $settings); $server = $this->dispatchCreate($config, $settings);
if (isset($config['events'])) { if (isset($config['events'])) {
$this->createEventListen($config); $this->createEventListen($config);
} }
return $server; return $server;
} }
/** /**
* @param $config * @param $config
* @throws Exception * @throws Exception
*/ */
protected function createEventListen($config) protected function createEventListen($config)
{ {
if (!is_array($config['events'])) { if (!is_array($config['events'])) {
return; return;
} }
$event = Snowflake::app()->event; $event = Snowflake::app()->event;
foreach ($config['events'] as $name => $_event) { foreach ($config['events'] as $name => $_event) {
$event->on($name, $_event); $event->on($name, $_event);
} }
} }
/** /**
* @param $config * @param $config
* @param $settings * @param $settings
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function dispatchCreate($config, $settings) private function dispatchCreate($config, $settings)
{ {
if (!($this->baseServer instanceof \Swoole\Server)) { if (!($this->baseServer instanceof \Swoole\Server)) {
$this->parseServer($config, $settings); $this->parseServer($config, $settings);
} else { } else {
if ($this->isUse($config['port'])) { if ($this->isUse($config['port'])) {
return $this->error_stop($config['host'], $config['port']); return $this->error_stop($config['host'], $config['port']);
} }
$newListener = $this->baseServer->addlistener($config['host'], $config['port'], $config['mode']); $newListener = $this->baseServer->addlistener($config['host'], $config['port'], $config['mode']);
if (isset($config['settings']) && is_array($config['settings'])) { if (isset($config['settings']) && is_array($config['settings'])) {
$newListener->set($config['settings']); $newListener->set($config['settings']);
} }
$this->onListenerBind($config, $this->baseServer); $this->onListenerBind($config, $this->baseServer);
} }
return $this->baseServer; return $this->baseServer;
} }
/** /**
* @param $config * @param $config
* @param $settings * @param $settings
* @return void * @return void
* @throws Exception * @throws Exception
*/ */
private function parseServer($config, $settings) private function parseServer($config, $settings)
{ {
$class = $this->dispatch($config['type']); $class = $this->dispatch($config['type']);
if ($this->isUse($config['port'])) { if ($this->isUse($config['port'])) {
return $this->error_stop($config['host'], $config['port']); return $this->error_stop($config['host'], $config['port']);
} }
$this->baseServer = new $class($config['host'], $config['port'], SWOOLE_PROCESS, $config['mode']); $this->baseServer = new $class($config['host'], $config['port'], SWOOLE_PROCESS, $config['mode']);
$settings['daemonize'] = $this->daemon; $settings['daemonize'] = $this->daemon;
if (!isset($settings['pid_file'])) { if (!isset($settings['pid_file'])) {
$settings['pid_file'] = APP_PATH . 'storage/server.pid'; $settings['pid_file'] = APP_PATH . 'storage/server.pid';
} }
if ($this->baseServer instanceof Websocket) { if ($this->baseServer instanceof Websocket) {
$this->onLoadWebsocketHandler(); $this->onLoadWebsocketHandler();
} else if ($this->baseServer instanceof Http) { } else if ($this->baseServer instanceof Http) {
$this->onLoadHttpHandler(); $this->onLoadHttpHandler();
} }
$this->baseServer->set($settings); $this->baseServer->set($settings);
} }
/** /**
* @param $config * @param $config
* @param $newListener * @param $newListener
* @return void * @return void
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
* @throws NotFindClassException * @throws NotFindClassException
*/ */
private function onListenerBind($config, $newListener) private function onListenerBind($config, $newListener)
{ {
$this->debug(sprintf('Listener %s::%d -> %s', $config['host'], $config['port'], $config['mode'])); $this->debug(sprintf('Listener %s::%d -> %s', $config['host'], $config['port'], $config['mode']));
if ($config['type'] == self::WEBSOCKET) { if ($config['type'] == self::WEBSOCKET) {
throw new Exception('Base server must instanceof \Swoole\Websocket\Server::class.'); throw new Exception('Base server must instanceof \Swoole\Websocket\Server::class.');
} else if (!in_array($config['type'], [self::HTTP, self::TCP, self::PACKAGE])) { } else if (!in_array($config['type'], [self::HTTP, self::TCP, self::PACKAGE])) {
throw new Exception('Unknown server type(' . $config['type'] . ').'); throw new Exception('Unknown server type(' . $config['type'] . ').');
} }
if (in_array($config['type'], $this->listenTypes)) { if (in_array($config['type'], $this->listenTypes)) {
return; return;
} }
if ($config['type'] == self::HTTP) { if ($config['type'] == self::HTTP) {
if (in_array($config['type'], $this->listenTypes)) { if (in_array($config['type'], $this->listenTypes)) {
throw new Exception('Base server must instanceof \Swoole\Websocket\Server::class.'); throw new Exception('Base server must instanceof \Swoole\Websocket\Server::class.');
} }
$this->onBind($newListener, 'request', [Snowflake::createObject(OnRequest::class), 'onHandler']); $this->onBind($newListener, 'request', [Snowflake::createObject(OnRequest::class), 'onHandler']);
} else { } else {
$this->noHttp($newListener, $config); $this->noHttp($newListener, $config);
} }
array_push($this->listenTypes, $config['type']); array_push($this->listenTypes, $config['type']);
} }
/** /**
* @param $newListener * @param $newListener
* @param $config * @param $config
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
private function noHttp($newListener, $config) private function noHttp($newListener, $config)
{ {
$class = [ $this->onBind($newListener, 'connect', [Snowflake::createObject(OnConnect::class), 'onHandler']);
'pack' => $config['resolve']['pack'] ?? null, $this->onBind($newListener, 'close', [Snowflake::createObject(OnClose::class), 'onHandler']);
'unpack' => $config['resolve']['unpack'] ?? null if ($config['type'] == self::TCP) {
]; $this->onBind($newListener, 'receive', [$class = new OnReceive(), 'onHandler']);
$this->onBind($newListener, 'connect', [Snowflake::createObject(OnConnect::class), 'onHandler']); } else {
$this->onBind($newListener, 'close', [Snowflake::createObject(OnClose::class), 'onHandler']); $this->onBind($newListener, 'packet', [$class = new OnPacket(), 'onHandler']);
if ($config['type'] == self::TCP) { }
$class['class'] = OnReceive::class; $class->pack = $config['resolve']['pack'] ?? null;
$callback = Snowflake::createObject($class); $class->unpack = $config['resolve']['unpack'] ?? null;
$this->onBind($newListener, 'receive', [$callback, 'onHandler']); }
} else {
$class['class'] = OnPacket::class;
$callback = Snowflake::createObject($class);
$this->onBind($newListener, 'packet', [$callback, 'onHandler']);
}
}
/** /**
* @param $server * @param $server
* @param $name * @param $name
* @param $callback * @param $callback
* @throws Exception * @throws Exception
*/ */
private function onBind($server, $name, $callback) private function onBind($server, $name, $callback)
{ {
if (in_array($name, $this->listening)) { if (in_array($name, $this->listening)) {
return; return;
} }
if ($name === 'request') { if ($name === 'request') {
$this->onLoadHttpHandler(); $this->onLoadHttpHandler();
} }
array_push($this->listening, $name); array_push($this->listening, $name);
$server->on($name, $callback); $server->on($name, $callback);
} }
/** /**
* Load router handler * Load router handler
* @throws Exception * @throws Exception
*/ */
public function onLoadHttpHandler() public function onLoadHttpHandler()
{ {
$event = Snowflake::app()->getEvent(); $event = Snowflake::app()->getEvent();
$event->on(Event::SERVER_WORKER_START, function () { $event->on(Event::SERVER_WORKER_START, function () {
$router = Snowflake::app()->getRouter(); $router = Snowflake::app()->getRouter();
$router->loadRouterSetting(); $router->loadRouterSetting();
}); });
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function onLoadWebsocketHandler() public function onLoadWebsocketHandler()
{ {
$event = Snowflake::app()->getEvent(); $event = Snowflake::app()->getEvent();
$event->on(Event::SERVER_WORKER_START, function () { $event->on(Event::SERVER_WORKER_START, function () {
/** @var AWebsocket $websocket */ /** @var AWebsocket $websocket */
$websocket = Snowflake::app()->annotation->get('websocket'); $websocket = Snowflake::app()->annotation->get('websocket');
$websocket->registration_notes(APP_PATH . 'app/Websocket', 'App\\Websocket'); $websocket->registration_notes(APP_PATH . 'app/Websocket', 'App\\Websocket');
}); });
} }
/** /**
* @param $type * @param $type
* @return string * @return string
*/ */
private function dispatch($type) private function dispatch($type)
{ {
$default = [ $default = [
self::HTTP => Http::class, self::HTTP => Http::class,
self::WEBSOCKET => Websocket::class, self::WEBSOCKET => Websocket::class,
self::TCP => Receive::class, self::TCP => Receive::class,
self::PACKAGE => Packet::class self::PACKAGE => Packet::class
]; ];
return $default[$type] ?? Receive::class; return $default[$type] ?? Receive::class;
} }
/** /**
* @param $servers * @param $servers
* @return array * @return array
*/ */
private function sortServers($servers) private function sortServers($servers)
{ {
$array = []; $array = [];
foreach ($servers as $server) { foreach ($servers as $server) {
switch ($server['type']) { switch ($server['type']) {
case self::WEBSOCKET: case self::WEBSOCKET:
array_unshift($array, $server); array_unshift($array, $server);
break; break;
case self::HTTP: case self::HTTP:
case self::PACKAGE | self::TCP: case self::PACKAGE | self::TCP:
$array[] = $server; $array[] = $server;
break; break;
default: default:
$array[] = $server; $array[] = $server;
} }
} }
return $array; return $array;
} }
} }