Repository navigation
Expand file tree
/
Copy pathSrvBase.php
More file actions
281 lines (267 loc) · 8.91 KB
/
Copy pathSrvBase.php
File metadata and controls
281 lines (267 loc) · 8.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
<?php
namespace HttpForPHP;
defined('SIGTERM') || define('SIGTERM', 15); //中止服务
defined('SIGUSR1') || define('SIGUSR1', 10); //柔性重启
defined('SIGRTMIN') || define('SIGRTMIN', 34); //SIGRTMIN信号重新打开日志文件
defined('ASYNC_NAME') || define('ASYNC_NAME', 'async');
if (!class_exists('Error')) { //兼容7.0
class Error extends \Exception{}
}
abstract class SrvBase {
use SrvMsg;
//全局变量存放 仅当前的工作进程有效[参见进程隔离]
public static $_SERVER;
public static $isConsole = false;
public static $runConfig = null;
public $isWorkerMan = false;
public $task_worker_num = 0;
/**
* @var Worker2|swoole_http_server $server
*/
public $server; //服务实例
protected $config;
protected $runFile;
public $runDir;
protected $pidFile;
protected $address;
public $port;
protected $ip;
public static $instance;
public static $command = '';
const TYPE_HTTP = 'http';
/**
* SrvBase constructor.
* @param array $config
*/
public function __construct($config)
{
self::$instance = $this;
$this->runFile = $_SERVER['SCRIPT_FILENAME'];
$this->runDir = dirname($this->runFile);
$this->config = $config;
$this->pidFile = $this->getConfig('setting.pidFile', $this->runDir .'/server.pid');
$this->ip = $this->getConfig('ip', '0.0.0.0');
$this->port = $this->getConfig('port', 7900);
$this->task_worker_num = (int)$this->getConfig('setting.task_worker_num', 0);
}
public function getConfig($name, $def=''){
//获取值
if (false === ($pos = strpos($name, '.')))
return isset($this->config[$name]) ? $this->config[$name] : $def;
// 二维数组支持
$name1 = substr($name, 0, $pos);
$name2 = substr($name, $pos + 1);
return isset($this->config[$name1][$name2]) ? $this->config[$name1][$name2] : $def;
}
public function serverName(){
return $this->getConfig('name', basename($this->runFile,'.php'));
}
#引入框架代码初始
protected function initMyPhp(){
if (function_exists('opcache_reset')) {
opcache_reset();
}
$initPhp = $this->getConfig('init_php', $this->runDir. '/base.php') ;
if(!is_file($initPhp)){
throw new \Exception('未配置要引入的运行文件');
}
include $initPhp;
}
public function phpRun($req, $res=null){
$phpRun = $this->getConfig('php_run', 'request_php_run');
if($phpRun instanceof \Closure || function_exists($phpRun)){
return call_user_func($phpRun, $req, $res);
}
throw new \Exception('未配置php_run匿名函数或未定义request_php_run函数');
}
final protected function setProcessTitle($title){
// >=php 5.5
if (function_exists('cli_set_process_title')) {
@cli_set_process_title($title);
} // Need proctitle when php<=5.5 .
elseif (extension_loaded('proctitle') && function_exists('setproctitle')) {
@setproctitle($title);
}
}
//workerman环境检测
public static function workermanCheck()
{
if(\DIRECTORY_SEPARATOR !== '\\'){ //非win
if (!in_array("pcntl", get_loaded_extensions())) {
self::err('Extension pcntl check fail');
return false;
}
if (!in_array("posix", get_loaded_extensions())) {
self::err('Extension posix check fail');
return false;
}
}
$check_func_map = array(
"stream_socket_server",
"stream_socket_accept",
"stream_socket_client",
"pcntl_signal_dispatch",
"pcntl_signal",
"pcntl_alarm",
"pcntl_fork",
"posix_getuid",
"posix_getpwuid",
"posix_kill",
"posix_setsid",
"posix_getpid",
"posix_getpwnam",
"posix_getgrnam",
"posix_getgid",
"posix_setgid",
"posix_initgroups",
"posix_setuid",
"posix_isatty",
);
// 获取php.ini中设置的禁用函数
if ($disable_func_string = ini_get("disable_functions")) {
$disable_func_map = array_flip(explode(",", $disable_func_string));
}
// 遍历查看是否有禁用的函数
foreach ($check_func_map as $func) {
if (isset($disable_func_map[$func])) {
self::err("Function $func may be disabled. Please check disable_functions in php.ini\nsee http://www.workerman.net/doc/workerman/faq/disable-function-check.html\n");
return false;
}
}
return true;
}
/**
* Safe Echo.
* @param string $msg
* @return bool
*/
public static function safeEcho($msg)
{
$stream = \STDOUT;
$line = $white = $green = $end = '';
//输出装饰
$line = "\033[1A\n\033[K";
$white = "\033[47;30m";
$green = "\033[32;40m";
$end = "\033[0m";
$msg = \str_replace(array('<n>', '<w>', '<g>'), array($line, $white, $green), $msg);
$msg = \str_replace(array('</n>', '</w>', '</g>'), $end, $msg);
\fwrite($stream, $msg);
\fflush($stream);
return true;
}
/****** 分隔线 ******/
#woker进程回调
protected function onWorkerStart($server, $worker_id){
//todo
}
/** 返回当前进程的id
* @return int
*/
abstract public function workerId();
/** 异步任务
* @param $data
* @return int|bool
*/
abstract public function task($data);
abstract public function getHeader($req);
abstract public function getRawBody($req);
/**
* 发送http数据
* @param $response
* @param $code
* @param $header
* @param $content
* @return void
*/
abstract public function httpSend($response, $code, &$header, &$content);
/** 关闭连接
* @param $fd
* @return bool
*/
abstract public function close($fd);
/** 连接信息
* @param $fd
* @return array|null
*/
abstract public function clientInfo($fd);
//初始服务
abstract protected function init();
//运行
abstract protected function exec();
//初始服务之前执行
protected function beforeInit(){
//todo
}
//初始服务之后执行
protected function afterInit(){
//todo
}
//reload -g会等所有客户端连接断开后重启 stop -g会等所有客户端连接断开后关闭
public function start(){
$this->beforeInit();
//初始服务
$this->init();
$this->afterInit();
//启动
$this->exec();
}
abstract public function relog();
// 结束当前worker进程
public function stopWorker(){
static::$instance->isWorkerMan ? \Workerman\Worker::stopAll() : static::$instance->server->stop();
}
public function stop($sig=SIGTERM){
if($pid=self::pid()){
static::safeEcho("Stopping...".PHP_EOL);
if(posix_kill($pid, $sig)){ //15 可安全关闭(等待任务处理结束)服务器
sleep(1);
while(self::pid()){
static::safeEcho("Waiting for ". $this->serverName() ." to shutdown...".PHP_EOL);
sleep(1);
}
file_exists($this->pidFile) && @unlink($this->pidFile);
static::safeEcho($this->serverName()." stopped!".PHP_EOL);
}else{
static::safeEcho('PID:'.$pid.' stop fail!'.PHP_EOL);
return false;
}
}else{
static::safeEcho('PID invalid! Process is not running.'.PHP_EOL);
}
return true;
}
public function reload($sig=SIGUSR1){
if($pid=self::pid()){
$ret = posix_kill($pid, $sig); //10
if($ret){
static::safeEcho('reload ok!'.PHP_EOL);
return true;
}else{
static::safeEcho('reload fail!'.PHP_EOL);
}
}else{
static::safeEcho('PID invalid! Process is not running.'.PHP_EOL);
}
return false;
}
public function status(){
if($pid=self::pid()){
static::safeEcho($this->serverName().' (pid '.$pid.') is running...'.PHP_EOL);
return true;
}else{
static::safeEcho($this->serverName()." is stopped".PHP_EOL);
return false;
}
}
//检查进程pid是否存在
public function pid(){
if(file_exists($this->pidFile) && $pid = file_get_contents($this->pidFile)){
if(posix_kill($pid, 0)) { //检测进程是否存在,不会发送信号
return $pid;
}
}
return false;
}
abstract public function run(&$argv);
}