diff --git a/config/laravels.php b/config/laravels.php index 22a98520..279c53f9 100644 --- a/config/laravels.php +++ b/config/laravels.php @@ -77,7 +77,7 @@ 'enable_reuse_port' => true, 'enable_coroutine' => false, 'http_compression' => false, - + 'server_timeout' => -1, // Slow log // 'request_slowlog_timeout' => 2, // 'request_slowlog_file' => storage_path(sprintf('logs/slow-%s.log', date('Y-m'))), diff --git a/src/LaravelS.php b/src/LaravelS.php index 77183752..a031d117 100644 --- a/src/LaravelS.php +++ b/src/LaravelS.php @@ -14,6 +14,7 @@ use Hhxsv5\LaravelS\Swoole\InotifyTrait; use Hhxsv5\LaravelS\Swoole\Process\CustomProcessTrait; use Hhxsv5\LaravelS\Swoole\Process\ProcessTitleTrait; +use Hhxsv5\LaravelS\Swoole\Process\ServerTimeoutTrait; use Hhxsv5\LaravelS\Swoole\Request; use Hhxsv5\LaravelS\Swoole\Server; use Hhxsv5\LaravelS\Swoole\StaticResponse; @@ -37,7 +38,7 @@ class LaravelS extends Server /** * Fix conflicts of traits */ - use InotifyTrait, LaravelTrait, LogTrait, ProcessTitleTrait, TimerTrait, CustomProcessTrait; + use InotifyTrait, LaravelTrait, LogTrait, ProcessTitleTrait, TimerTrait, CustomProcessTrait, ServerTimeoutTrait; /**@var array */ protected $laravelConf; @@ -117,6 +118,8 @@ public function onWorkerStart(HttpServer $server, $workerId) // Fire WorkerStart event $this->fireEvent('WorkerStart', WorkerStartInterface::class, func_get_args()); + + $this->registerSignal(); } public function onWorkerStop(HttpServer $server, $workerId) @@ -149,6 +152,7 @@ public function onRequest(SwooleRequest $swooleRequest, SwooleResponse $swooleRe { try { parent::onRequest($swooleRequest, $swooleResponse); + $this->handleServerTimeout(); $laravelRequest = $this->convertRequest($this->laravel, $swooleRequest); $this->laravel->bindRequest($laravelRequest); $this->laravel->fireEvent('laravels.received_request', [$laravelRequest]); @@ -218,6 +222,7 @@ protected function handleDynamicResource(Laravel $laravel, IlluminateRequest $la } $response->setChunkLimit($this->conf['swoole']['buffer_output_size']); $response->send($this->conf['enable_gzip']); + $this->resetAlarm(); $laravel->clean(); return true; } diff --git a/src/Swoole/Process/ServerTimeoutTrait.php b/src/Swoole/Process/ServerTimeoutTrait.php new file mode 100644 index 00000000..d8335078 --- /dev/null +++ b/src/Swoole/Process/ServerTimeoutTrait.php @@ -0,0 +1,37 @@ +getServerTimeout() != -1) { + \Swoole\Process::alarm(-1); + } + } + + public function handleServerTimeout() + { + if ($this->getServerTimeout() != -1) { + \Swoole\Process::alarm($this->conf['swoole']['server_timeout'] * 1000 * 1000); + } + } + + public function registerSignal() + { + if ($this->getServerTimeout() != -1) { + pcntl_signal(SIGALRM, function () { + \Swoole\Process::alarm(-1); + throw new \Exception(); + }); + } + } + + public function getServerTimeout() + { + return $this->conf['swoole']['server_timeout']; + } +}