SocketWorker.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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. continue;
  308. }
  309. // 客户端提前断开链接
  310. $this->statusInfo['client_close']++;
  311. // 如果该链接对应的buffer有数据,说明放生错误
  312. if(!empty($this->recvBuffers[$fd]['buf']))
  313. {
  314. $this->notice("CLIENT_CLOSE\nCLIENT_IP:".$this->getRemoteIp()."\nBUFFER:[".var_export($this->recvBuffers[$fd]['buf'],true)."]\n");
  315. }
  316. // 关闭链接
  317. $this->closeClient($fd);
  318. if($this->workerStatus == self::STATUS_SHUTDOWN)
  319. {
  320. $this->stop();
  321. }
  322. return;
  323. }
  324. $this->recvBuffers[$fd]['buf'] .= $buffer;
  325. $remain_len = $this->dealInput($this->recvBuffers[$fd]['buf']);
  326. // 包接收完毕
  327. if(0 === $remain_len)
  328. {
  329. // 执行处理
  330. try{
  331. // 业务处理
  332. $this->dealProcess($this->recvBuffers[$fd]['buf']);
  333. }
  334. catch(\Exception $e)
  335. {
  336. $this->notice('CODE:' . $e->getCode() . ' MESSAGE:' . $e->getMessage()."\n".$e->getTraceAsString()."\nCLIENT_IP:".$this->getRemoteIp()."\nBUFFER:[".var_export($this->recvBuffers[$fd]['buf'],true)."]\n");
  337. $this->statusInfo['throw_exception'] ++;
  338. $this->sendToClient($e->getMessage());
  339. }
  340. // 是否是长连接
  341. if($this->isPersistentConnection)
  342. {
  343. // 清空缓冲buffer
  344. $this->recvBuffers[$fd] = array('buf'=>'', 'remain_len'=>$this->prereadLength);
  345. }
  346. else
  347. {
  348. // 关闭链接
  349. $this->closeClient($fd);
  350. }
  351. }
  352. // 出错
  353. else if(false === $remain_len)
  354. {
  355. // 出错
  356. $this->statusInfo['packet_err']++;
  357. $this->sendToClient('packet_err:'.$this->recvBuffers[$fd]['buf']);
  358. $this->notice("PACKET_ERROR\nCLIENT_IP:".$this->getRemoteIp()."\nBUFFER:[".var_export($this->recvBuffers[$fd]['buf'],true)."]\n");
  359. $this->closeClient($fd);
  360. }
  361. else
  362. {
  363. $this->recvBuffers[$fd]['remain_len'] = $remain_len;
  364. }
  365. // 检查是否是关闭状态或者是否到达请求上限
  366. if($this->workerStatus == self::STATUS_SHUTDOWN || $this->statusInfo['total_request'] >= $this->maxRequests)
  367. {
  368. // 关闭链接
  369. if($this->isPersistentConnection)
  370. {
  371. $this->closeClient($fd);
  372. }
  373. // 停止服务
  374. $this->stop();
  375. // EXIT_WAIT_TIME秒后退出进程
  376. pcntl_alarm(self::EXIT_WAIT_TIME);
  377. }
  378. }
  379. /**
  380. * 根据fd关闭链接
  381. * @param int $fd
  382. * @return void
  383. */
  384. protected function closeClient($fd)
  385. {
  386. // udp忽略
  387. if($this->protocol != 'udp')
  388. {
  389. $this->event->del($this->connections[$fd], Events\BaseEvent::EV_READ);
  390. fclose($this->connections[$fd]);
  391. unset($this->connections[$fd], $this->recvBuffers[$fd]);
  392. }
  393. }
  394. /**
  395. * 安装信号处理函数
  396. * @return void
  397. */
  398. protected function installSignal()
  399. {
  400. // 闹钟信号
  401. $this->event->add(SIGALRM, Events\BaseEvent::EV_SIGNAL, array($this, 'signalHandler'), SIGALRM);
  402. // 终止进程信号
  403. $this->event->add(SIGINT, Events\BaseEvent::EV_SIGNAL, array($this, 'signalHandler'), SIGINT);
  404. // 平滑重启信号
  405. $this->event->add(SIGHUP, Events\BaseEvent::EV_SIGNAL, array($this, 'signalHandler'), SIGHUP);
  406. // 报告进程状态
  407. $this->event->add(SIGUSR1, Events\BaseEvent::EV_SIGNAL, array($this, 'signalHandler'), SIGUSR1);
  408. // 报告该进程使用的文件
  409. $this->event->add(SIGUSR2, Events\BaseEvent::EV_SIGNAL, array($this, 'signalHandler'), SIGUSR2);
  410. // 设置忽略信号
  411. pcntl_signal(SIGTTIN, SIG_IGN);
  412. pcntl_signal(SIGTTOU, SIG_IGN);
  413. pcntl_signal(SIGQUIT, SIG_IGN);
  414. pcntl_signal(SIGPIPE, SIG_IGN);
  415. pcntl_signal(SIGCHLD, SIG_IGN);
  416. }
  417. /**
  418. * 设置server信号处理函数
  419. * @param null $null
  420. * @param int $signal
  421. */
  422. public function signalHandler($signal, $null = null, $null = null)
  423. {
  424. switch($signal)
  425. {
  426. // 时钟处理函数
  427. case SIGALRM:
  428. // 停止服务后EXIT_WAIT_TIME秒还没退出则强制退出
  429. if($this->workerStatus == self::STATUS_SHUTDOWN)
  430. {
  431. exit(0);
  432. }
  433. break;
  434. // 停止该进程
  435. case SIGINT:
  436. // 平滑重启
  437. case SIGHUP:
  438. $this->stop();
  439. // EXIT_WAIT_TIME秒后退出进程
  440. pcntl_alarm(self::EXIT_WAIT_TIME);
  441. break;
  442. // 报告进程状态
  443. case SIGUSR1:
  444. $this->writeStatusToQueue();
  445. break;
  446. // 报告进程使用的php文件
  447. case SIGUSR2:
  448. $this->writeFilesListToQueue();
  449. break;
  450. }
  451. }
  452. /**
  453. * 发送数据到客户端
  454. * @return bool
  455. */
  456. public function sendToClient($str_to_send)
  457. {
  458. // tcp
  459. if($this->protocol != 'udp')
  460. {
  461. // tcp 如果一次没写完(一般是缓冲区满的情况),则阻塞写
  462. if(!$this->blockWrite($this->connections[$this->currentDealFd], $str_to_send, 500))
  463. {
  464. $this->notice('sendToClient fail ,Data length = ' . strlen($str_to_send));
  465. $this->statusInfo['send_fail']++;
  466. return false;
  467. }
  468. return true;
  469. }
  470. // udp 直接发送,要求数据包不能超过65515
  471. return strlen($str_to_send) == stream_socket_sendto($this->mainSocket, $str_to_send, 0, $this->currentClientAddress);
  472. }
  473. /**
  474. * 向fd写数据,如果socket缓冲区满了,则改用阻塞模式写数据
  475. * @param resource $fd
  476. * @param string $str_to_write
  477. * @param int $time_out 单位毫秒
  478. * @return bool
  479. */
  480. protected function blockWrite($fd, $str_to_write, $timeout_ms = 500)
  481. {
  482. $send_len = @fwrite($fd, $str_to_write);
  483. if($send_len == strlen($str_to_write))
  484. {
  485. return true;
  486. }
  487. // 客户端关闭
  488. if(feof($fd))
  489. {
  490. $this->notice("blockWrite client close");
  491. return false;
  492. }
  493. // 设置阻塞
  494. stream_set_blocking($fd, 1);
  495. // 设置超时
  496. $timeout_sec = floor($timeout_ms/1000);
  497. $timeout_ms = $timeout_ms%1000;
  498. stream_set_timeout($fd, $timeout_sec, $timeout_ms*1000);
  499. $send_len += @fwrite($fd, substr($str_to_write, $send_len));
  500. // 改回非阻塞
  501. stream_set_blocking($fd, 0);
  502. return $send_len == strlen($str_to_write);
  503. }
  504. /**
  505. * 获取客户端ip
  506. * @param int $fd 已经链接的socket id
  507. * @return string
  508. */
  509. public function getRemoteIp($fd = null)
  510. {
  511. if(empty($fd))
  512. {
  513. if(!isset($this->connections[$this->currentDealFd]))
  514. {
  515. return '0.0.0.0';
  516. }
  517. $fd = $this->currentDealFd;
  518. }
  519. $ip = '';
  520. if($this->protocol == 'udp')
  521. {
  522. $sock_name = $this->currentClientAddress;
  523. }
  524. else
  525. {
  526. $sock_name = stream_socket_get_name($this->connections[$fd], true);
  527. }
  528. if($sock_name)
  529. {
  530. $tmp = explode(':', $sock_name);
  531. $ip = $tmp[0];
  532. }
  533. return $ip;
  534. }
  535. /**
  536. * 获取本地ip
  537. * @return string
  538. */
  539. public function getLocalIp()
  540. {
  541. $ip = '';
  542. $sock_name = '';
  543. if($this->protocol == 'udp' || !isset($this->connections[$this->currentDealFd]))
  544. {
  545. $sock_name = stream_socket_get_name($this->mainSocket, false);
  546. }
  547. else
  548. {
  549. $sock_name = stream_socket_get_name($this->connections[$this->currentDealFd], false);
  550. }
  551. if($sock_name)
  552. {
  553. $tmp = explode(':', $sock_name);
  554. $ip = $tmp[0];
  555. }
  556. if(empty($ip) || '127.0.0.1' == $ip)
  557. {
  558. $ip = gethostbyname(trim(`hostname`));
  559. }
  560. return $ip;
  561. }
  562. /**
  563. * 将当前worker进程状态写入消息队列
  564. * @return void
  565. */
  566. protected function writeStatusToQueue()
  567. {
  568. if(!Master::getQueueId())
  569. {
  570. return;
  571. }
  572. $error_code = 0;
  573. 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);
  574. }
  575. /**
  576. * 开发环境将当前进程使用的文件写入消息队列,用于FileMonitor监控文件更新
  577. * @return void
  578. */
  579. protected function writeFilesListToQueue()
  580. {
  581. if(!Master::getQueueId())
  582. {
  583. return;
  584. }
  585. $error_code = 0;
  586. $flip_file_list = array_flip(get_included_files());
  587. $file_list = array_diff_key($flip_file_list, $this->includeFiles);
  588. $this->includeFiles = $flip_file_list;
  589. if($file_list)
  590. {
  591. msg_send(Master::getQueueId(), self::MSG_TYPE_FILE_MONITOR, array_keys($file_list), true, false, $error_code);
  592. }
  593. }
  594. /**
  595. * 是否所有任务都已经完成
  596. * @return bool
  597. */
  598. protected function allTaskHasDone()
  599. {
  600. // 如果是长链接并且没有要处理的数据则是任务都处理完了
  601. return $this->noConnections() || ($this->isPersistentConnection && $this->allBufferIsEmpty());
  602. }
  603. /**
  604. * 检查是否所有的链接的缓冲区都是空
  605. * @return bool
  606. */
  607. protected function allBufferIsEmpty()
  608. {
  609. foreach($this->recvBuffers as $fd => $buf)
  610. {
  611. if(!empty($buf['buf']))
  612. {
  613. return false;
  614. }
  615. }
  616. return true;
  617. }
  618. /**
  619. * 该进程收到的任务是否都已经完成,重启进程时需要判断
  620. * @return bool
  621. */
  622. protected function noConnections()
  623. {
  624. return empty($this->connections);
  625. }
  626. /**
  627. * 该worker进程开始服务的时候会触发一次,可以在这里做一些全局的事情
  628. * @return bool
  629. */
  630. protected function onStart()
  631. {
  632. return false;
  633. }
  634. /**
  635. * 该worker进程停止服务的时候会触发一次,可以在这里做一些全局的事情
  636. * @return bool
  637. */
  638. protected function onStop()
  639. {
  640. return false;
  641. }
  642. }