SocketWorker.php 23 KB

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