88 lines
1.6 KiB
PHP
88 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace Kiri\Server\Abstracts;
|
|
|
|
use Swoole\Process;
|
|
|
|
trait ReloadWorkers
|
|
{
|
|
|
|
/**
|
|
* @return void
|
|
*/
|
|
private function reloadWorkers(): bool
|
|
{
|
|
$pid = $this->getMasterPid();
|
|
if ($pid === null) {
|
|
return false;
|
|
}
|
|
|
|
return Process::kill($pid, SIGUSR1);
|
|
}
|
|
|
|
private function getMasterPid(): ?int
|
|
{
|
|
$processes = $this->listProcesses();
|
|
$candidates = [];
|
|
|
|
$pidFile = function_exists('storage') ? storage('.swoole.pid') : '';
|
|
if (is_file($pidFile)) {
|
|
$candidates[] = (int)trim((string)file_get_contents($pidFile));
|
|
}
|
|
|
|
foreach ($processes as $process) {
|
|
if ($this->isMasterProcessCommand($process['command'])) {
|
|
$candidates[] = (int)$process['pid'];
|
|
}
|
|
}
|
|
|
|
foreach ($candidates
|
|
|> array_filter(...)
|
|
|> array_unique(...)
|
|
|> array_values(...) as $pid) {
|
|
if ($this->isProcessAlive($pid) && $this->isMasterPid($pid, $processes)) {
|
|
return $pid;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private function isMasterPid(int $pid, array $processes): bool
|
|
{
|
|
foreach ($processes as $process) {
|
|
if ((int)$process['pid'] === $pid) {
|
|
return $this->isMasterProcessCommand($process['command']) && $this->isSameAppProcess($pid);
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
private function listProcesses(): array
|
|
{
|
|
$lines = [];
|
|
exec('ps -eo pid=,ppid=,args=', $lines);
|
|
|
|
$processes = [];
|
|
foreach ($lines as $line) {
|
|
$line = trim($line);
|
|
if ($line === '') {
|
|
continue;
|
|
}
|
|
|
|
$parts = preg_split('/\s+/', $line, 3);
|
|
if (count($parts) < 3) {
|
|
continue;
|
|
}
|
|
|
|
$processes[] = [
|
|
'pid' => (int)$parts[0],
|
|
'ppid' => (int)$parts[1],
|
|
'command' => $parts[2],
|
|
];
|
|
}
|
|
|
|
return $processes;
|
|
}
|
|
}
|