SocketWorker.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. <?php
  2. namespace Man\Core;
  3. require_once WORKERMAN_ROOT_DIR . 'man/Core/Events/Select.php';
  4. require_once WORKERMAN_ROOT_DIR . 'man/Core/AbstractWorker.php';
  5. require_once WORKERMAN_ROOT_DIR . 'man/Core/Lib/Config.php';
  6. /**
  7. * SocketWorker 监听某个端口,对外提供网络服务的worker
  8. *
  9. * @author walkor <worker-man@qq.com>
  10. *
  11. * <b>使用示例:</b>
  12. * <pre>
  13. * <code>
  14. * $worker = new SocketWorker();
  15. * $worker->start();
  16. * <code>
  17. * </pre>
  18. */
  19. abstract class SocketWorker extends AbstractWorker
  20. {
  21. /**
  22. * udp最大包长 linux:65507 mac:9216
  23. * @var integer
  24. */
  25. const MAX_UDP_PACKEG_SIZE = 65507;
  26. /**
  27. * 停止服务后等待EXIT_WAIT_TIME秒后还没退出则强制退出
  28. * @var integer
  29. */
  30. const EXIT_WAIT_TIME = 3;
  31. /**
  32. * worker的传输层协议
  33. * @var string
  34. */
  35. protected $protocol = "tcp";
  36. /**
  37. * worker监听端口的Socket
  38. * @var resource
  39. */
  40. protected $mainSocket = null;
  41. /**
  42. * worker接受的所有链接
  43. * @var array
  44. */
  45. protected $connections = array();
  46. /**
  47. * worker的所有读buffer
  48. * @var array
  49. */
  50. protected $recvBuffers = array();
  51. /**
  52. * 当前处理的fd
  53. * @var integer
  54. */
  55. protected $currentDealFd = 0;
  56. /**
  57. * UDP当前处理的客户端地址
  58. * @var string
  59. */
  60. protected $currentClientAddress = '';
  61. /**
  62. * 是否是长链接,(短连接每次请求后服务器主动断开,长连接一般是客户端主动断开)
  63. * @var bool
  64. */
  65. protected $isPersistentConnection = false;
  66. /**
  67. * 事件轮询库的名称
  68. * @var string
  69. */
  70. protected $eventLoopName ="\\Man\\Core\\Events\\Select";
  71. /**
  72. * 时间轮询库实例
  73. * @var object
  74. */
  75. protected $event = null;
  76. /**
  77. * 该worker进程处理多少请求后退出,0表示不自动退出
  78. * @var integer
  79. */
  80. protected $maxRequests = 0;
  81. /**
  82. * 预读长度
  83. * @var integer
  84. */
  85. protected $prereadLength = 4;
  86. /**
  87. * 该进程使用的php文件
  88. * @var array
  89. */
  90. protected $includeFiles = array();
  91. /**
  92. * 统计信息
  93. * @var array
  94. */
  95. protected $statusInfo = array(
  96. 'start_time' => 0, // 该进程开始时间戳
  97. 'total_request' => 0, // 该进程处理的总请求数
  98. 'packet_err' => 0, // 该进程收到错误数据包的总数
  99. 'throw_exception' => 0, // 该进程逻辑处理时收到异常的总数
  100. 'thunder_herd' => 0, // 该进程受惊群效应影响的总数
  101. 'client_close' => 0, // 客户端提前关闭链接总数
  102. 'send_fail' => 0, // 发送数据给客户端失败总数
  103. );
  104. /**
  105. * 用户worker继承此worker类必须实现该方法,根据具体协议和当前收到的数据决定是否继续收包
  106. * @param string $recv_str 收到的数据包
  107. * @return int/false 返回0表示接收完毕/>0表示还有多少字节没有接收到/false出错
  108. */
  109. abstract public function dealInput($recv_str);
  110. /**
  111. * 用户worker继承此worker类必须实现该方法,根据包中的数据处理逻辑
  112. * 逻辑处理
  113. * @param string $recv_str 收到的数据包
  114. * @return void
  115. */
  116. abstract public function dealProcess($recv_str);
  117. /**
  118. * 构造函数
  119. * @param int $port
  120. * @param string $ip
  121. * @param string $protocol
  122. * @return void
  123. */
  124. public function __construct()
  125. {
  126. // worker name
  127. $this->workerName = get_class($this);
  128. // 是否开启长连接
  129. $this->isPersistentConnection = (bool)Lib\Config::get( $this->workerName . '.persistent_connection');
  130. // 最大请求数,如果没有配置则使用PHP_INT_MAX
  131. $this->maxRequests = (int)Lib\Config::get( $this->workerName . '.max_requests');
  132. $this->maxRequests = $this->maxRequests <= 0 ? PHP_INT_MAX : $this->maxRequests;
  133. $preread_length = (int)Lib\Config::get( $this->workerName . '.preread_length');
  134. if($preread_length > 0)
  135. {
  136. $this->prereadLength = $preread_length;
  137. }
  138. elseif(!$this->isPersistentConnection)
  139. {
  140. $this->prereadLength = 65535;
  141. }
  142. // worker启动时间
  143. $this->statusInfo['start_time'] = time();
  144. //事件轮询库
  145. if(extension_loaded('libevent'))
  146. {
  147. $this->setEventLoopName('Libevent');
  148. }
  149. // 检查退出状态
  150. $this->addShutdownHook();
  151. // 初始化事件轮询库
  152. // $this->event = new Libevent();
  153. // $this->event = new Select();
  154. $this->event = new $this->eventLoopName();
  155. }
  156. /**
  157. * 让该worker实例开始服务
  158. *
  159. * @return void
  160. */
  161. public function start()
  162. {
  163. // 安装信号处理函数
  164. $this->installSignal();
  165. // 触发该worker进程onStart事件,该进程整个生命周期只触发一次
  166. if($this->onStart())
  167. {
  168. return;
  169. }
  170. if($this->protocol == 'udp')
  171. {
  172. // 添加读udp事件
  173. $this->event->add($this->mainSocket, Events\BaseEvent::EV_READ, array($this, 'recvUdp'));
  174. }
  175. else
  176. {
  177. // 添加accept事件
  178. $ret = $this->event->add($this->mainSocket, Events\BaseEvent::EV_READ, array($this, 'accept'));
  179. }
  180. // 主体循环,整个子进程会阻塞在这个函数上
  181. $ret = $this->event->loop();
  182. $this->notice('worker loop exit');
  183. exit(0);
  184. }
  185. /**
  186. * 停止服务
  187. * @param bool $exit 是否退出
  188. * @return void
  189. */
  190. public function stop($exit = true)
  191. {
  192. // 触发该worker进程onStop事件
  193. if($this->onStop())
  194. {
  195. return;
  196. }
  197. // 标记这个worker开始停止服务
  198. if($this->workerStatus != self::STATUS_SHUTDOWN)
  199. {
  200. // 停止接收连接
  201. $this->event->del($this->mainSocket, Events\BaseEvent::EV_READ);
  202. fclose($this->mainSocket);
  203. $this->workerStatus = self::STATUS_SHUTDOWN;
  204. }
  205. // 没有链接要处理了
  206. if($this->allTaskHasDone())
  207. {
  208. if($exit)
  209. {
  210. exit(0);
  211. }
  212. }
  213. }
  214. /**
  215. * 设置worker监听的socket
  216. * @param resource $socket
  217. * @return void
  218. */
  219. public function setListendSocket($socket)
  220. {
  221. // 初始化
  222. $this->mainSocket = $socket;
  223. // 设置监听socket非阻塞
  224. stream_set_blocking($this->mainSocket, 0);
  225. // 获取协议
  226. $mata_data = stream_get_meta_data($socket);
  227. $this->protocol = substr($mata_data['stream_type'], 0, 3);
  228. }
  229. /**
  230. * 设置worker的事件轮询库的名称
  231. * @param string
  232. * @return void
  233. */
  234. public function setEventLoopName($event_loop_name)
  235. {
  236. $this->eventLoopName = "\\Man\\Core\\Events\\".$event_loop_name;
  237. require_once WORKERMAN_ROOT_DIR . 'man/Core/Events/'.ucfirst(str_replace('WORKERMAN', '', $event_loop_name)).'.php';
  238. }
  239. /**
  240. * 接受一个链接
  241. * @param resource $socket
  242. * @param $null_one $flag
  243. * @param $null_two $base
  244. * @return void
  245. */
  246. public function accept($socket, $null_one = null, $null_two = null)
  247. {
  248. // 获得一个连接
  249. $new_connection = @stream_socket_accept($socket, 0);
  250. // 可能是惊群效应
  251. if(false === $new_connection)
  252. {
  253. $this->statusInfo['thunder_herd']++;
  254. return false;
  255. }
  256. // 接受请求数加1
  257. $this->statusInfo['total_request'] ++;
  258. // 连接的fd序号
  259. $fd = (int) $new_connection;
  260. $this->connections[$fd] = $new_connection;
  261. $this->recvBuffers[$fd] = array('buf'=>'', 'remain_len'=>$this->prereadLength);
  262. // 非阻塞
  263. stream_set_blocking($this->connections[$fd], 0);
  264. $this->event->add($this->connections[$fd], Events\BaseEvent::EV_READ , array($this, 'dealInputBase'), $fd);
  265. return $new_connection;
  266. }
  267. /**
  268. * 接收Udp数据
  269. * 如果数据超过一个udp包长,需要业务自己解析包体,判断数据是否全部到达
  270. * @param resource $socket
  271. * @param $null_one $flag
  272. * @param $null_two $base
  273. * @return void
  274. */
  275. public function recvUdp($socket, $null_one = null, $null_two = null)
  276. {
  277. $data = stream_socket_recvfrom($socket , self::MAX_UDP_PACKEG_SIZE, 0, $address);
  278. // 可能是惊群效应
  279. if(false === $data || empty($address))
  280. {
  281. $this->statusInfo['thunder_herd']++;
  282. return false;
  283. }
  284. // 接受请求数加1
  285. $this->statusInfo['total_request'] ++;
  286. $this->currentClientAddress = $address;
  287. if(0 === $this->dealInput($data))
  288. {
  289. $this->dealProcess($data);
  290. }
  291. }
  292. /**
  293. * 处理受到的数据
  294. * @param event_buffer $event_buffer
  295. * @param int $fd
  296. * @return void
  297. */
  298. public function dealInputBase($connection, $flag, $fd = null)
  299. {
  300. $this->currentDealFd = $fd;
  301. $buffer = stream_socket_recvfrom($connection, $this->recvBuffers[$fd]['remain_len']);
  302. // 出错了
  303. if('' == $buffer)
  304. {
  305. if(feof($connection))
  306. {
  307. // 客户端提前断开链接
  308. $this->statusInfo['client_close']++;
  309. // 如果该链接对应的buffer有数据,说明放生错误
  310. if(!empty($this->recvBuffers[$fd]['buf']))
  311. {
  312. $this->notice("CLIENT_CLOSE\nCLIENT_IP:".$this->getRemoteIp()."\nBUFFER:[".var_export($this->recvBuffers[$fd]['buf'],true)."]\n");
  313. }
  314. }
  315. else
  316. {
  317. // 如果该链接对应的buffer有数据,说明放生错误
  318. if(!empty($this->recvBuffers[$fd]['buf']))
  319. {
  320. $this->notice("RECV_TIMEOUT\nCLIENT_IP:".$this->getRemoteIp()."\nBUFFER:[".var_export($this->recvBuffers[$fd]['buf'],true)."]\n");
  321. }
  322. }
  323. // 关闭链接
  324. $this->closeClient($fd);
  325. if($this->workerStatus == self::STATUS_SHUTDOWN)
  326. {
  327. $this->stop();
  328. }
  329. return;
  330. }
  331. $this->recvBuffers[$fd]['buf'] .= $buffer;
  332. $remain_len = $this->dealInput($this->recvBuffers[$fd]['buf']);
  333. // 包接收完毕
  334. if(0 === $remain_len)
  335. {
  336. // 执行处理
  337. try{
  338. // 业务处理
  339. $this->dealProcess($this->recvBuffers[$fd]['buf']);
  340. }
  341. catch(\Exception $e)
  342. {
  343. $this->notice('CODE:' . $e->getCode() . ' MESSAGE:' . $e->getMessage()."\n".$e->getTraceAsString()."\nCLIENT_IP:".$this->getRemoteIp()."\nBUFFER:[".var_export($this->recvBuffers[$fd]['buf'],true)."]\n");
  344. $this->statusInfo['throw_exception'] ++;
  345. $this->sendToClient($e->getMessage());
  346. }
  347. // 是否是长连接
  348. if($this->isPersistentConnection)
  349. {
  350. // 清空缓冲buffer
  351. $this->recvBuffers[$fd] = array('buf'=>'', 'remain_len'=>$this->prereadLength);
  352. }
  353. else
  354. {
  355. // 关闭链接
  356. $this->closeClient($fd);
  357. }
  358. }
  359. // 出错
  360. else if(false === $remain_len)
  361. {
  362. // 出错
  363. $this->statusInfo['packet_err']++;
  364. $this->sendToClient('packet_err:'.$this->recvBuffers[$fd]['buf']);
  365. $this->notice("PACKET_ERROR\nCLIENT_IP:".$this->getRemoteIp()."\nBUFFER:[".var_export($this->recvBuffers[$fd]['buf'],true)."]\n");
  366. $this->closeClient($fd);
  367. }
  368. else
  369. {
  370. $this->recvBuffers[$fd]['remain_len'] = $remain_len;
  371. }
  372. // 检查是否是关闭状态或者是否到达请求上限
  373. if($this->workerStatus == self::STATUS_SHUTDOWN || $this->statusInfo['total_request'] >= $this->maxRequests)
  374. {
  375. // 关闭链接
  376. if($this->isPersistentConnection)
  377. {
  378. $this->closeClient($fd);
  379. }
  380. // 停止服务
  381. $this->stop();
  382. // EXIT_WAIT_TIME秒后退出进程
  383. pcntl_alarm(self::EXIT_WAIT_TIME);
  384. }
  385. }
  386. /**
  387. * 根据fd关闭链接
  388. * @param int $fd
  389. * @return void
  390. */
  391. protected function closeClient($fd)
  392. {
  393. // udp忽略
  394. if($this->protocol != 'udp')
  395. {
  396. $this->event->del($this->connections[$fd], Events\BaseEvent::EV_READ);
  397. fclose($this->connections[$fd]);
  398. unset($this->connections[$fd], $this->recvBuffers[$fd]);
  399. }
  400. }
  401. /**
  402. * 安装信号处理函数
  403. * @return void
  404. */
  405. protected function installSignal()
  406. {
  407. // 闹钟信号
  408. $this->event->add(SIGALRM, Events\BaseEvent::EV_SIGNAL, array($this, 'signalHandler'), SIGALRM);
  409. // 终止进程信号
  410. $this->event->add(SIGINT, Events\BaseEvent::EV_SIGNAL, array($this, 'signalHandler'), SIGINT);
  411. // 平滑重启信号
  412. $this->event->add(SIGHUP, Events\BaseEvent::EV_SIGNAL, array($this, 'signalHandler'), SIGHUP);
  413. // 报告进程状态
  414. $this->event->add(SIGUSR1, Events\BaseEvent::EV_SIGNAL, array($this, 'signalHandler'), SIGUSR1);
  415. // 报告该进程使用的文件
  416. $this->event->add(SIGUSR2, Events\BaseEvent::EV_SIGNAL, array($this, 'signalHandler'), SIGUSR2);
  417. // 设置忽略信号
  418. pcntl_signal(SIGTTIN, SIG_IGN);
  419. pcntl_signal(SIGTTOU, SIG_IGN);
  420. pcntl_signal(SIGQUIT, SIG_IGN);
  421. pcntl_signal(SIGPIPE, SIG_IGN);
  422. pcntl_signal(SIGCHLD, SIG_IGN);
  423. }
  424. /**
  425. * 设置server信号处理函数
  426. * @param null $null
  427. * @param int $signal
  428. */
  429. public function signalHandler($signal, $null = null, $null = null)
  430. {
  431. switch($signal)
  432. {
  433. // 时钟处理函数
  434. case SIGALRM:
  435. // 停止服务后EXIT_WAIT_TIME秒还没退出则强制退出
  436. if($this->workerStatus == self::STATUS_SHUTDOWN)
  437. {
  438. exit(0);
  439. }
  440. break;
  441. // 停止该进程
  442. case SIGINT:
  443. // 平滑重启
  444. case SIGHUP:
  445. $this->stop();
  446. // EXIT_WAIT_TIME秒后退出进程
  447. pcntl_alarm(self::EXIT_WAIT_TIME);
  448. break;
  449. // 报告进程状态
  450. case SIGUSR1:
  451. $this->writeStatusToQueue();
  452. break;
  453. // 报告进程使用的php文件
  454. case SIGUSR2:
  455. $this->writeFilesListToQueue();
  456. break;
  457. }
  458. }
  459. /**
  460. * 发送数据到客户端
  461. * @return bool
  462. */
  463. public function sendToClient($str_to_send)
  464. {
  465. // tcp
  466. if($this->protocol != 'udp')
  467. {
  468. // tcp 如果一次没写完(一般是缓冲区满的情况),则阻塞写
  469. if(!$this->blockWrite($this->connections[$this->currentDealFd], $str_to_send, 500))
  470. {
  471. $this->notice('sendToClient fail ,Data length = ' . strlen($str_to_send));
  472. $this->statusInfo['send_fail']++;
  473. return false;
  474. }
  475. return true;
  476. }
  477. // udp 直接发送,要求数据包不能超过65515
  478. return strlen($str_to_send) == stream_socket_sendto($this->mainSocket, $str_to_send, 0, $this->currentClientAddress);
  479. }
  480. /**
  481. * 向fd写数据,如果socket缓冲区满了,则改用阻塞模式写数据
  482. * @param resource $fd
  483. * @param string $str_to_write
  484. * @param int $time_out 单位毫秒
  485. * @return bool
  486. */
  487. protected function blockWrite($fd, $str_to_write, $timeout_ms = 500)
  488. {
  489. $send_len = @fwrite($fd, $str_to_write);
  490. if($send_len == strlen($str_to_write))
  491. {
  492. return true;
  493. }
  494. // 客户端关闭
  495. if(feof($fd))
  496. {
  497. $this->notice("blockWrite client close");
  498. return false;
  499. }
  500. // 设置阻塞
  501. stream_set_blocking($fd, 1);
  502. // 设置超时
  503. $timeout_sec = floor($timeout_ms/1000);
  504. $timeout_ms = $timeout_ms%1000;
  505. stream_set_timeout($fd, $timeout_sec, $timeout_ms*1000);
  506. $send_len += @fwrite($fd, substr($str_to_write, $send_len));
  507. // 改回非阻塞
  508. stream_set_blocking($fd, 0);
  509. return $send_len == strlen($str_to_write);
  510. }
  511. /**
  512. * 获取客户端ip
  513. * @param int $fd 已经链接的socket id
  514. * @return string
  515. */
  516. public function getRemoteIp($fd = null)
  517. {
  518. if(empty($fd))
  519. {
  520. if(!isset($this->connections[$this->currentDealFd]))
  521. {
  522. return '0.0.0.0';
  523. }
  524. $fd = $this->currentDealFd;
  525. }
  526. $ip = '';
  527. if($this->protocol == 'udp')
  528. {
  529. $sock_name = $this->currentClientAddress;
  530. }
  531. else
  532. {
  533. $sock_name = stream_socket_get_name($this->connections[$fd], true);
  534. }
  535. if($sock_name)
  536. {
  537. $tmp = explode(':', $sock_name);
  538. $ip = $tmp[0];
  539. }
  540. return $ip;
  541. }
  542. /**
  543. * 获取本地ip
  544. * @return string
  545. */
  546. public function getLocalIp()
  547. {
  548. $ip = '';
  549. $sock_name = '';
  550. if($this->protocol == 'udp' || !isset($this->connections[$this->currentDealFd]))
  551. {
  552. $sock_name = stream_socket_get_name($this->mainSocket, false);
  553. }
  554. else
  555. {
  556. $sock_name = stream_socket_get_name($this->connections[$this->currentDealFd], false);
  557. }
  558. if($sock_name)
  559. {
  560. $tmp = explode(':', $sock_name);
  561. $ip = $tmp[0];
  562. }
  563. if(empty($ip) || '127.0.0.1' == $ip)
  564. {
  565. $ip = gethostbyname(trim(`hostname`));
  566. }
  567. return $ip;
  568. }
  569. /**
  570. * 将当前worker进程状态写入消息队列
  571. * @return void
  572. */
  573. protected function writeStatusToQueue()
  574. {
  575. if(!Master::getQueueId())
  576. {
  577. return;
  578. }
  579. $error_code = 0;
  580. msg_send(Master::getQueueId(), self::MSG_TYPE_STATUS, array_merge($this->statusInfo, array('memory'=>memory_get_usage(true), 'pid'=>posix_getpid(), 'worker_name' => $this->workerName)), true, false, $error_code);
  581. }
  582. /**
  583. * 开发环境将当前进程使用的文件写入消息队列,用于FileMonitor监控文件更新
  584. * @return void
  585. */
  586. protected function writeFilesListToQueue()
  587. {
  588. if(!Master::getQueueId())
  589. {
  590. return;
  591. }
  592. $error_code = 0;
  593. $flip_file_list = array_flip(get_included_files());
  594. $file_list = array_diff_key($flip_file_list, $this->includeFiles);
  595. $this->includeFiles = $flip_file_list;
  596. if($file_list)
  597. {
  598. msg_send(Master::getQueueId(), self::MSG_TYPE_FILE_MONITOR, array_keys($file_list), true, false, $error_code);
  599. }
  600. }
  601. /**
  602. * 是否所有任务都已经完成
  603. * @return bool
  604. */
  605. protected function allTaskHasDone()
  606. {
  607. // 如果是长链接并且没有要处理的数据则是任务都处理完了
  608. return $this->noConnections() || ($this->isPersistentConnection && $this->allBufferIsEmpty());
  609. }
  610. /**
  611. * 检查是否所有的链接的缓冲区都是空
  612. * @return bool
  613. */
  614. protected function allBufferIsEmpty()
  615. {
  616. foreach($this->recvBuffers as $fd => $buf)
  617. {
  618. if(!empty($buf['buf']))
  619. {
  620. return false;
  621. }
  622. }
  623. return true;
  624. }
  625. /**
  626. * 该进程收到的任务是否都已经完成,重启进程时需要判断
  627. * @return bool
  628. */
  629. protected function noConnections()
  630. {
  631. return empty($this->connections);
  632. }
  633. /**
  634. * 该worker进程开始服务的时候会触发一次,可以在这里做一些全局的事情
  635. * @return bool
  636. */
  637. protected function onStart()
  638. {
  639. return false;
  640. }
  641. /**
  642. * 该worker进程停止服务的时候会触发一次,可以在这里做一些全局的事情
  643. * @return bool
  644. */
  645. protected function onStop()
  646. {
  647. return false;
  648. }
  649. }