This commit is contained in:
as2252258@163.com
2021-03-28 16:09:18 +08:00
parent 7ea7b1e36e
commit 86e8ad68e9
11 changed files with 1341 additions and 1145 deletions
+3 -3
View File
@@ -126,11 +126,11 @@ class Loader extends BaseObject
*/ */
public function _scanDir(DirectoryIterator $paths, $namespace) public function _scanDir(DirectoryIterator $paths, $namespace)
{ {
/** @var DirectoryIterator $path */
$DIRECTORY = $this->createDirectoryMap($paths); $DIRECTORY = $this->createDirectoryMap($paths);
foreach ($paths as $path) { foreach ($paths as $path) {
if ($path->getFilename() === '.' || $path->getFilename() === '..') { if ($path->isDot()) continue;
continue;
}
if (str_starts_with($path->getFilename(), '.')) { if (str_starts_with($path->getFilename(), '.')) {
continue; continue;
} }
-2
View File
@@ -36,8 +36,6 @@ abstract class Callback extends HttpService
protected function clear(Server $server, $worker_id, $message) protected function clear(Server $server, $worker_id, $message)
{ {
try { try {
Snowflake::clearProcessId($server->worker_pid);
/** @var Process $logger */ /** @var Process $logger */
$logger = Snowflake::app()->get(LoggerProcess::class); $logger = Snowflake::app()->get(LoggerProcess::class);
$logger->write(Json::encode([$this->_MESSAGE[$message] . $worker_id, 'app'])); $logger->write(Json::encode([$this->_MESSAGE[$message] . $worker_id, 'app']));
+4 -7
View File
@@ -5,12 +5,8 @@ namespace HttpServer;
use Exception; use Exception;
use ReflectionException;
use Snowflake\Abstracts\Input; use Snowflake\Abstracts\Input;
use Snowflake\Event;
use Snowflake\Exception\ComponentException;
use Snowflake\Exception\ConfigException; use Snowflake\Exception\ConfigException;
use Snowflake\Exception\NotFindPropertyException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
/** /**
@@ -44,15 +40,16 @@ class Command extends \Console\Command
return 'I don\'t know what I want to do.'; return 'I don\'t know what I want to do.';
} }
if ($manager->isRunner() && $dtl->get('action') == 'start') { /** @var Shutdown $shutdown */
$shutdown = Snowflake::app()->get('shutdown');
if ($shutdown->isRunning() && $dtl->get('action') == 'start') {
return 'Service is running. Please use restart.'; return 'Service is running. Please use restart.';
} }
$manager->shutdown(); $shutdown->shutdown();
if ($dtl->get('action') == 'stop') { if ($dtl->get('action') == 'stop') {
return 'shutdown success.'; return 'shutdown success.';
} }
return $manager->start(); return $manager->start();
} }
+3
View File
@@ -26,6 +26,9 @@ class OnBeforeReload extends Callback
{ {
$event = Snowflake::app()->getEvent(); $event = Snowflake::app()->getEvent();
$event->trigger(Event::SERVER_BEFORE_RELOAD, [$server]); $event->trigger(Event::SERVER_BEFORE_RELOAD, [$server]);
Snowflake::clearWorkerPid();
Snowflake::clearTaskPid();
} }
} }
+2
View File
@@ -69,6 +69,8 @@ class OnWorkerStart extends Callback
{ {
putenv('environmental=' . Snowflake::TASK); putenv('environmental=' . Snowflake::TASK);
Snowflake::setTaskId($server->worker_pid);
fire(Event::SERVER_TASK_START); fire(Event::SERVER_TASK_START);
} }
+123
View File
@@ -0,0 +1,123 @@
<?php
namespace HttpServer;
use Exception;
use Snowflake\Abstracts\Component;
/**
* Class Shutdown
* @package HttpServer
*/
class Shutdown extends Component
{
private string $taskDirectory;
private string $workerDirectory;
private string $managerDirectory;
private string $processDirectory;
public function init()
{
$this->taskDirectory = storage(null, 'pid/task');
$this->workerDirectory = storage(null, 'pid/worker');
$this->managerDirectory = storage(null, 'pid/manager');
$this->processDirectory = storage(null, 'pid/process');
}
/**
* @throws Exception
*/
public function shutdown(): void
{
$master_pid = Server()->setting['pid_file'] ?? PID_PATH;
clearstatcache($master_pid);
if (file_exists($master_pid)) {
$this->close($master_pid);
}
$this->closeOther();
}
/**
* 关闭其他进程
*/
private function closeOther(): void
{
$this->directoryCheck($this->managerDirectory);
$this->directoryCheck($this->taskDirectory);
$this->directoryCheck($this->workerDirectory);
$this->directoryCheck($this->processDirectory);
}
/**
* @return bool
* @throws Exception
* check server is running.
*/
public function isRunning()
{
$master_pid = Server()->setting['pid_file'] ?? PID_PATH;
return $this->pidIsExists($master_pid);
}
/**
* @param $content
* @return bool
*/
public function pidIsExists($content): bool
{
$content = shell_exec('ps -eo pid,cmd,state | grep ' . $content . ' | grep -v grep');
if (empty($content)) {
return false;
}
return true;
}
/**
* @param string $path
*/
public function directoryCheck(string $path)
{
$dir = new \DirectoryIterator($path);
if ($dir->getSize() < 1) {
return true;
}
foreach ($dir as $value) {
/** @var \DirectoryIterator $value */
if (!$value->valid()) continue;
$this->close($value->getRealPath());
}
return false;
}
/**
* @param string $value
*/
public function close(string $value)
{
$resource = fopen($value, 'r');
$content = fgets($resource);
fclose($resource);
while ($this->pidIsExists($content)) {
exec('kill -15 ' . $content);
sleep(1);
}
@unlink($value);
}
}
+2
View File
@@ -22,6 +22,7 @@ use HttpServer\Service\Http;
use HttpServer\Service\Packet; use HttpServer\Service\Packet;
use HttpServer\Service\Receive; use HttpServer\Service\Receive;
use HttpServer\Service\Websocket; use HttpServer\Service\Websocket;
use HttpServer\Shutdown;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
use Kafka\Producer; use Kafka\Producer;
use Annotation\Annotation as SAnnotation; use Annotation\Annotation as SAnnotation;
@@ -482,6 +483,7 @@ abstract class BaseApplication extends Service
'rpc' => ['class' => \Rpc\Producer::class], 'rpc' => ['class' => \Rpc\Producer::class],
'rpc-service' => ['class' => \Rpc\Service::class], 'rpc-service' => ['class' => \Rpc\Service::class],
'http2' => ['class' => Http2::class], 'http2' => ['class' => Http2::class],
'shutdown' => ['class' => Shutdown::class],
]); ]);
} }
} }
+2
View File
@@ -14,6 +14,7 @@ use HttpServer\Http\Response;
use HttpServer\HttpFilter; use HttpServer\HttpFilter;
use HttpServer\Route\Router; use HttpServer\Route\Router;
use HttpServer\Server; use HttpServer\Server;
use HttpServer\Shutdown;
use Kafka\Producer; use Kafka\Producer;
use Snowflake\Async; use Snowflake\Async;
use Snowflake\Cache\Redis; use Snowflake\Cache\Redis;
@@ -50,6 +51,7 @@ use Rpc\Producer as RPCProducer;
* @property HttpFilter $filter * @property HttpFilter $filter
* @property RPCProducer $rpc * @property RPCProducer $rpc
* @property Channel $channel * @property Channel $channel
* @property Shutdown $shutdown
*/ */
trait TraitApplication trait TraitApplication
{ {
+1 -1
View File
@@ -34,7 +34,7 @@ abstract class Process extends \Swoole\Process implements SProcess
{ {
parent::__construct([$this, '_load'], false, 1, $enable_coroutine); parent::__construct([$this, '_load'], false, 1, $enable_coroutine);
$this->application = $application; $this->application = $application;
Snowflake::setWorkerId($this->pid); Snowflake::setProcessId($this->pid);
} }
/** /**
+63 -5
View File
@@ -152,7 +152,7 @@ class Snowflake
$default = APP_PATH . 'storage' . DIRECTORY_SEPARATOR; $default = APP_PATH . 'storage' . DIRECTORY_SEPARATOR;
$path = Config::get('storage', false, $default); $path = Config::get('storage', false, $default);
if (!is_dir($path)) { if (!is_dir($path)) {
mkdir($path); mkdir($path, 0777, true);
} }
return $path; return $path;
} }
@@ -176,6 +176,17 @@ class Snowflake
} }
/**
* @param $workerId
* @return mixed
* @throws Exception
*/
public static function setManagerId($workerId): mixed
{
return self::writeFile(storage($workerId . '.sock', 'pid/manager'), $workerId);
}
/** /**
* @param $workerId * @param $workerId
* @return mixed * @return mixed
@@ -183,7 +194,7 @@ class Snowflake
*/ */
public static function setProcessId($workerId): mixed public static function setProcessId($workerId): mixed
{ {
return self::writeFile(storage('socket.sock'), $workerId); return self::writeFile(storage($workerId . '.sock', 'pid/process'), $workerId);
} }
@@ -197,10 +208,23 @@ class Snowflake
if (empty($workerId)) { if (empty($workerId)) {
return $workerId; return $workerId;
} }
return self::writeFile(storage($workerId . '.sock', 'worker'), $workerId); return self::writeFile(storage($workerId . '.sock', 'pid/worker'), $workerId);
} }
/**
* @param $workerId
* @return mixed
* @throws Exception
*/
public static function setTaskId($workerId): mixed
{
if (empty($workerId)) {
return $workerId;
}
return self::writeFile(storage($workerId . '.sock', 'pid/task'), $workerId);
}
/** /**
* @param $fileName * @param $fileName
* @param $content * @param $content
@@ -236,11 +260,45 @@ class Snowflake
/** /**
* @param $workerId * @param $workerId
* @param bool $isWorker
* @throws Exception * @throws Exception
*/ */
public static function clearProcessId($workerId) public static function clearProcessId($workerId, $isWorker = false)
{ {
@unlink(storage($workerId . '.sock', 'worker')); clearstatcache();
$directory = $isWorker === true ? 'pid/worker' : 'pid/task';
if (!file_exists($file = storage($workerId, $directory))) {
return;
}
shell_exec('rm -rf ' . $file);
}
/**
* @param string|null $taskPid
* @throws Exception
*/
public static function clearTaskPid(string $taskPid = null)
{
if (empty($taskPid)) {
exec('rm -rf ' . storage(null, 'pid/task'));
} else {
static::clearProcessId($taskPid);
}
}
/**
* @param $taskPid
* @throws Exception
*/
public static function clearWorkerPid($taskPid = null)
{
if (empty($taskPid)) {
exec('rm -rf ' . storage(null, 'pid/worker'));
} else {
static::clearProcessId($taskPid, true);
}
} }
+31 -20
View File
@@ -9,6 +9,10 @@ use HttpServer\Http\HttpParams;
use HttpServer\Http\Request; use HttpServer\Http\Request;
use HttpServer\Http\Response; use HttpServer\Http\Response;
use HttpServer\Route\Router; use HttpServer\Route\Router;
use HttpServer\Service\Http;
use HttpServer\Service\Packet;
use HttpServer\Service\Receive;
use HttpServer\Service\Websocket;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
use Snowflake\Abstracts\Config; use Snowflake\Abstracts\Config;
use Snowflake\Error\Logger; use Snowflake\Error\Logger;
@@ -467,6 +471,20 @@ if (!function_exists('Input')) {
} }
if (!function_exists('Server')) {
/**
* @return Http|Packet|Receive|Websocket|null
* @throws Exception
*/
function Server(): Http|Packet|Receive|Websocket|null
{
return Snowflake::app()->getSwoole();
}
}
if (!function_exists('storage')) { if (!function_exists('storage')) {
/** /**
@@ -477,14 +495,18 @@ if (!function_exists('storage')) {
*/ */
function storage($fileName = '', $path = ''): string function storage($fileName = '', $path = ''): string
{ {
$basePath = Snowflake::getStoragePath();
if (empty($path)) { $basePath = rtrim(Snowflake::getStoragePath(), '/');
$fileName = rtrim($basePath, '/') . '/' . $fileName; if (!empty($path)) {
} else if (empty($fileName)) { $path = ltrim($path, '/');
return rtrim(initDir($basePath, $path)); if (!is_dir($basePath . '/' . $path)) {
} else { mkdir($basePath . '/' . $path, 0777, true);
$fileName = rtrim(initDir($basePath, $path)) . '/' . $fileName;
} }
}
if (empty($fileName)) {
return $basePath . '/' . $path . '/';
}
$fileName = $basePath . '/' . $path . '/' . $fileName;
if (!file_exists($fileName)) { if (!file_exists($fileName)) {
touch($fileName); touch($fileName);
} }
@@ -498,20 +520,9 @@ if (!function_exists('storage')) {
* @return false|string * @return false|string
* @throws Exception * @throws Exception
*/ */
function initDir($basePath, $path): bool|string function initDir($path): bool|string
{ {
$explode = array_filter(explode('/', $path)); return mkdir($path, 0777, true);
$_path = '/' . trim($basePath, '/') . '/';
foreach ($explode as $value) {
$_path .= $value . '/';
if (!is_dir(rtrim($_path, '/'))) {
mkdir(rtrim($_path, '/'));
}
if (!is_dir($_path)) {
throw new Exception('System error, directory ' . $_path . ' is not writable');
}
}
return realpath($_path);
} }