RPCService.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: liyunlong
  5. * Date: 2018-12-22
  6. * Time: 16:57
  7. */
  8. namespace common\libs\swoole;
  9. class RPCService
  10. {
  11. /**
  12. * 配置对象
  13. * @var array
  14. */
  15. protected $settings = [];
  16. /**
  17. * Yii::$app
  18. * @var null
  19. */
  20. private $app = null;
  21. private $swooleContorller = null;
  22. function __construct($settings,$app, &$swooleContorller){
  23. $this->check();
  24. $this->settings = $settings;
  25. $this->app = $app;
  26. $this->swooleContorller = $swooleContorller;
  27. }
  28. /**
  29. * [check description]
  30. */
  31. private function check(){
  32. /**
  33. * 检测 PDO_MYSQL
  34. */
  35. if (!extension_loaded('pdo_mysql')) {
  36. exit('error:请安装PDO_MYSQL扩展' . PHP_EOL);
  37. }
  38. /**
  39. * 检查exec 函数是否启用
  40. */
  41. if (!function_exists('exec')) {
  42. exit('error:exec函数不可用' . PHP_EOL);
  43. }
  44. /**
  45. * 检查命令 lsof 命令是否存在
  46. */
  47. exec("whereis lsof", $out);
  48. if (strpos($out[0], "/usr/sbin/lsof") === false ) {
  49. exit('error:找不到lsof命令,请确保lsof在/usr/sbin下' . PHP_EOL);
  50. }
  51. }
  52. /**
  53. * 获取指定端口的服务占用列表
  54. * @param $port
  55. * @return array
  56. */
  57. private function bindPort($port) {
  58. $res = [];
  59. $cmd = "/usr/sbin/lsof -i :{$port}|awk '$1 != \"COMMAND\" {print $1, $2, $9}'";
  60. exec($cmd, $out);
  61. if ($out) {
  62. foreach ($out as $v) {
  63. $a = explode(' ', $v);
  64. list($ip, $p) = explode(':', $a[2]);
  65. $res[$a[1]] = [
  66. 'cmd' => $a[0],
  67. 'ip' => $ip,
  68. 'port' => $p,
  69. ];
  70. }
  71. }
  72. return $res;
  73. }
  74. /**
  75. * 启动服务
  76. * @throws \yii\base\Exception
  77. */
  78. public function serviceStart(){
  79. $pidfile = $this->settings['pidfile'];
  80. $host = $this->settings['host'];
  81. $port = $this->settings['port'];
  82. $this->msg("服务正在启动...");
  83. if (!is_writable(dirname($pidfile))) {
  84. $this->error("pid文件需要写入权限");
  85. }
  86. if (file_exists($pidfile)) {
  87. $pid = explode("\n", file_get_contents($pidfile));
  88. $cmd = "ps ax | awk '{ print $1 }' | grep -e \"^{$pid[0]}$\"";
  89. exec($cmd, $out);
  90. if (!empty($out)) {
  91. $this->msg("[warning]:pid文件已存在,服务已经启动,进程id为:{$pid[0]}",true);
  92. } else {
  93. $this->msg("[warning]:pid文件已存在,可能是服务上次异常退出");
  94. unlink($pidfile);
  95. }
  96. }
  97. $bind = $this->bindPort($port);
  98. if ($bind) {
  99. foreach ($bind as $k => $v) {
  100. if ($v['ip'] == '*' || $v['ip'] == $host) {
  101. $this->error("服务启动失败,{$host}:{$port}端口已经被进程ID:{$k}占用");
  102. }
  103. }
  104. }
  105. //启动
  106. $server = new RPCServer($this->settings,$this->app,$this->swooleContorller);
  107. foreach($this->settings['ipWhiteList'] as $ip){
  108. $server->addAllowIP($ip);
  109. }
  110. $server->addAllowUser($this->settings['username'], $this->settings['password']);
  111. $server->run();
  112. }
  113. /**
  114. * 查看服务状态
  115. */
  116. public function serviceStats(){
  117. $client = new \swoole_http_client($this->settings['host'], $this->settings['port']);
  118. // if (!$client->connect($this->settings['host'], $this->settings['port'], $this->settings['client_timeout'])){
  119. // exit("Error: connect server failed. code[{$client->errCode}]\n");
  120. // }
  121. // $client->send('stats');
  122. //
  123. // echo $client->recv();
  124. $client->on('message', function ($cli, $frame){
  125. var_dump($frame);
  126. echo(PHP_EOL);
  127. $cli->close();
  128. });
  129. $client->upgrade('/', function ($cli){
  130. $cli->push('stats');
  131. // $cli->close();
  132. });
  133. }
  134. /**
  135. * 查看进程列表
  136. */
  137. public function serviceList(){
  138. $cmd = "ps aux|grep " . $this->settings['process_name'] . "|grep -v grep|awk '{print $1, $2, $6, $8, $9, $11}'";
  139. exec($cmd, $out);
  140. if (empty($out)) {
  141. $this->msg("没有发现正在运行服务",true);
  142. }
  143. $this->msg("本机运行的服务进程列表:");
  144. $this->msg("USER PID RSS(kb) STAT START COMMAND");
  145. foreach ($out as $v) {
  146. $this->msg($v);
  147. }
  148. }
  149. /**
  150. * 停止服务
  151. * @param bool $isForce
  152. * @param callable|null $callback
  153. */
  154. public function serviceStop($isForce = false, callable $callback = null){
  155. $pidfile = $this->settings['pidfile'];
  156. $this->msg("正在停止服务...");
  157. if (!file_exists($pidfile)) {
  158. $this->msg("pid文件:". $pidfile ."不存在");
  159. } else {
  160. $pid = explode("\n", file_get_contents($pidfile));
  161. if($isForce && !empty($pid)){
  162. foreach($pid as $id){
  163. if($id){
  164. $this->_kill($id);
  165. }
  166. }
  167. }
  168. if(!$isForce){
  169. if ($pid[0]) {
  170. $this->_kill($pid[0]);
  171. }
  172. }
  173. //确保停止服务后swoole-task-pid文件被删除
  174. if (file_exists($pidfile)) {
  175. unlink($pidfile);
  176. }
  177. $this->msg("服务已停止");
  178. }
  179. if($callback !== null) $callback();
  180. }
  181. /**
  182. * 杀进程
  183. * @param $pid
  184. */
  185. private function _kill($pid){
  186. $cmd = "kill {$pid}";
  187. exec($cmd, $sign);
  188. do {
  189. $out = [];
  190. $c = "ps ax | awk '{ print $1 }' | grep -e \"^{$pid}$\"";
  191. exec($c, $out);
  192. if (empty($out)) {
  193. break;
  194. }else{
  195. exec("kill -9 {$pid}");
  196. }
  197. } while (true);
  198. }
  199. /**
  200. * 停止服务
  201. * @param $msg
  202. * @param bool $exit
  203. */
  204. private function msg($msg,$exit=false){
  205. if($exit){
  206. exit($msg . PHP_EOL);
  207. }else{
  208. echo $msg . PHP_EOL;
  209. }
  210. }
  211. /**
  212. * 停止服务
  213. * @param $msg
  214. */
  215. private function error($msg){
  216. exit("[error]:".$msg . PHP_EOL);
  217. }
  218. }