Files
kiri-http-server/Abstracts/BaseProcess.php
T

124 lines
1.9 KiB
PHP
Raw Normal View History

2022-01-09 03:49:02 +08:00
<?php
2022-01-10 11:39:55 +08:00
namespace Kiri\Server\Abstracts;
2022-01-09 03:49:02 +08:00
use Kiri\Context;
2022-01-12 11:52:58 +08:00
use Kiri\Server\Broadcast\OnBroadcastInterface;
2022-01-10 11:39:55 +08:00
use Kiri\Server\Contract\OnProcessInterface;
2022-01-09 03:49:02 +08:00
use Swoole\Coroutine;
use Swoole\Process;
/**
*
*/
abstract class BaseProcess implements OnProcessInterface
{
protected bool $isStop = false;
protected bool $redirect_stdin_and_stdout = FALSE;
protected int $pipe_type = SOCK_DGRAM;
2022-07-11 16:34:13 +08:00
protected bool $enable_coroutine = false;
2022-01-09 03:49:02 +08:00
2022-06-17 12:27:33 +08:00
public string $name = '';
2022-01-09 03:49:02 +08:00
/**
* @return string
*/
public function getName(): string
{
2022-06-17 12:27:33 +08:00
if (empty($this->name)) {
2022-06-22 18:55:51 +08:00
$this->name = uniqid('p.');
2022-06-17 12:27:33 +08:00
}
2022-01-09 03:49:02 +08:00
return $this->name;
}
/**
* @return bool
*/
public function isStop(): bool
{
return $this->isStop;
}
/**
* @return bool
2022-01-12 11:20:33 +08:00
*/
2022-01-09 03:49:02 +08:00
public function getRedirectStdinAndStdout(): bool
2022-01-12 11:20:33 +08:00
{
2022-01-09 03:49:02 +08:00
return $this->redirect_stdin_and_stdout;
}
/**
* @return int
*/
public function getPipeType(): int
{
return $this->pipe_type;
}
/**
* @return bool
*/
public function isEnableCoroutine(): bool
{
return $this->enable_coroutine;
}
/**
*
*/
public function onProcessStop(): void
{
$this->isStop = true;
}
/**
*
*/
public function onSigterm(): static
{
if (!Context::inCoroutine()) {
2022-06-22 18:43:36 +08:00
Process::signal(SIGTERM, fn($data) => $this->onShutdown($data));
2022-01-09 03:49:02 +08:00
} else {
2022-06-17 13:55:46 +08:00
$listen = function () {
2022-06-22 18:43:36 +08:00
$data = Coroutine::waitSignal(SIGTERM, -1);
2022-01-09 03:49:02 +08:00
if ($data) {
$this->onShutdown($data);
}
2022-06-17 13:55:46 +08:00
};
Coroutine::create($listen);
2022-01-09 03:49:02 +08:00
}
return $this;
}
/**
* @param $data
*/
protected function onShutdown($data): void
{
$this->isStop = true;
2022-01-12 11:20:33 +08:00
$value = Context::getContext('waite:process:message');
2022-06-22 18:55:30 +08:00
\Kiri::getLogger()->alert('Process ' . $this->getName() . ' stop');
2022-04-28 11:56:19 +08:00
if (!is_null($value) && Coroutine::exists((int)$value)) {
Coroutine::cancel((int)$value);
2022-01-12 11:20:33 +08:00
}
2022-01-09 03:49:02 +08:00
}
}