kefu/server/components/Command.php

148 lines
3.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace server\components;
use server\event\Websocket;
/**
* Swoole 命令行支持操作start|stop|restart|reload
*/
class Command
{
protected $config = [];
protected $daemon = 0;
public function execute($argv)
{
if(count($argv) < 2 || count($argv) > 3){
echo "invalid argument action. expected start|stop|restart|reload [-d]\n";
return false;
}
if(count($argv) == 3 && $argv[2] == '-d'){
$this->daemon = 1;
}
$action = $argv[1];
$this->init();
if (in_array($action, ['start', 'stop', 'reload', 'restart'])) {
$this->$action();
} else {
echo "invalid argument action:{$action}, expected start|stop|restart|reload .\n";
}
}
protected function init()
{
$this->config = [];
if (empty($this->config['pid_file'])) {
$this->config['pid_file'] = '/usr/local/swoole.pid';
}
// 避免pid混乱
// $this->config['pid_file'] .= '_' . $this->getPort();
}
/**
* 启动server
* @access protected
* @return void
*/
protected function start()
{
$pid = $this->getMasterPid();
if ($this->isRunning($pid)) {
echo "swoole server process is already running\n";
return false;
}
echo "---------------------------------------------- SERVER STATUS ----------------------------------------------------\n";
echo "starting swoole server...\n";
echo ("swoole ws server started: <ws://0.0.0.0:12800>\n");
echo("you can exit with `CTRL-C`\n");
echo "---------------------------------------------- SERVER STATUS ----------------------------------------------------\n";
new Websocket($this->daemon);
}
/**
* 平滑重启server
*/
protected function reload()
{
$pid = $this->getMasterPid();
if (!$this->isRunning($pid)) {
echo "no swoole server process running.\n";
return false;
}
echo "reloading swoole server...\n";
\swoole_process::kill($pid, SIGUSR1);
echo "> success\n";
}
/**
* 停止server
*/
protected function stop()
{
$pid = $this->getMasterPid();
if (!$this->isRunning($pid)) {
echo "no swoole server process running.\n";
return false;
}
echo "stopping swoole server...\n";
\swoole_process::kill($pid, SIGTERM);
$this->removePid();
echo "> success\n";
}
/**
* 重启server
*/
protected function restart()
{
$pid = $this->getMasterPid();
if ($this->isRunning($pid)) {
$this->stop();
}
sleep(1);
$this->start($this->daemon);
}
/**
* 获取主进程PID
*/
protected function getMasterPid()
{
$pidFile = $this->config['pid_file'];
if (is_file($pidFile)) {
$masterPid = (int) file_get_contents($pidFile);
} else {
$masterPid = 0;
}
return $masterPid;
}
/**
* 删除PID文件
*/
protected function removePid()
{
$masterPid = $this->config['pid_file'];
if (is_file($masterPid)) {
unlink($masterPid);
}
}
/**
* 判断PID是否在运行
*/
protected function isRunning($pid)
{
if (empty($pid)) {
return false;
}
return \swoole_process::kill($pid, 0);
}
}