BusinessWorker.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. <?php
  2. /**
  3. *
  4. * 处理具体逻辑
  5. *
  6. * @author walkor <walkor@workerman.net>
  7. *
  8. */
  9. require_once __DIR__ . '/../Lib/Autoloader.php';
  10. use \Protocols\GatewayProtocol;
  11. use \Lib\Store;
  12. use \Lib\Gateway;
  13. use \Lib\StatisticClient;
  14. use \Lib\Context;
  15. class BusinessWorker extends Man\Core\SocketWorker
  16. {
  17. /**
  18. * 与gateway的连接
  19. * ['ip:port' => conn, 'ip:port' => conn, ...]
  20. * @var array
  21. */
  22. protected $gatewayConnections = array();
  23. /**
  24. * 连不上的gateway地址
  25. * ['ip:port' => retry_count, 'ip:port' => retry_count, ...]
  26. * @var array
  27. */
  28. protected $badGatewayAddress = array();
  29. /**
  30. * 连接gateway失败重试次数
  31. * @var int
  32. */
  33. const MAX_RETRY_COUNT = 5;
  34. /**
  35. * 命令字映射 统计用到
  36. * @var array
  37. */
  38. protected static $interfaceMap = array(
  39. GatewayProtocol::CMD_ON_GATEWAY_CONNECTION => 'CMD_ON_GATEWAY_CONNECTION',
  40. GatewayProtocol::CMD_ON_MESSAGE => 'CMD_ON_MESSAGE',
  41. GatewayProtocol::CMD_ON_CLOSE => 'CMD_ON_CLOSE',
  42. );
  43. /**
  44. * 进程启动时初始化
  45. * @see Man\Core.SocketWorker::onStart()
  46. */
  47. protected function onStart()
  48. {
  49. // 强制设置成长链接
  50. $this->isPersistentConnection = true;
  51. // 定时检查与gateway进程的连接
  52. \Man\Core\Lib\Task::init($this->event);
  53. \Man\Core\Lib\Task::add(1, array($this, 'checkGatewayConnections'));
  54. $this->checkGatewayConnections();
  55. Gateway::setBusinessWorker($this);
  56. }
  57. /**
  58. * 获取与gateway的连接
  59. */
  60. public function getGatewayConnections()
  61. {
  62. return $this->gatewayConnections;
  63. }
  64. /**
  65. * 检查gateway转发来的用户请求是否完整
  66. * @see Man\Core.SocketWorker::dealInput()
  67. */
  68. public function dealInput($recv_buffer)
  69. {
  70. return GatewayProtocol::input($recv_buffer);
  71. }
  72. /**
  73. * 处理请求
  74. * @see Man\Core.SocketWorker::dealProcess()
  75. */
  76. public function dealProcess($recv_buffer)
  77. {
  78. $pack = new GatewayProtocol($recv_buffer);
  79. Context::$client_ip = $pack->header['client_ip'];
  80. Context::$client_port = $pack->header['client_port'];
  81. Context::$local_ip = $pack->header['local_ip'];
  82. Context::$local_port = $pack->header['local_port'];
  83. Context::$socket_id = $pack->header['socket_id'];
  84. Context::$client_id = $pack->header['client_id'];
  85. $_SERVER = array(
  86. 'REMOTE_ADDR' => Context::$client_ip,
  87. 'REMOTE_PORT' => Context::$client_port,
  88. 'GATEWAY_ADDR' => Context::$local_ip,
  89. 'GATEWAY_PORT' => Context::$local_port,
  90. 'GATEWAY_CLIENT_ID' => Context::$client_id,
  91. );
  92. if($pack->ext_data != '')
  93. {
  94. $_SESSION = Context::sessionDecode($pack->ext_data);
  95. }
  96. else
  97. {
  98. $_SESSION = null;
  99. }
  100. // 备份一次$pack->ext_data,请求处理完毕后判断session是否和备份相等,不相等就更新session
  101. $session_str_copy = $pack->ext_data;
  102. $cmd = $pack->header['cmd'];
  103. $interface = isset(self::$interfaceMap[$cmd]) ? self::$interfaceMap[$cmd] : $cmd;
  104. StatisticClient::tick(__CLASS__, $interface);
  105. try{
  106. switch($cmd)
  107. {
  108. case GatewayProtocol::CMD_ON_GATEWAY_CONNECTION:
  109. Event::onGatewayConnect(Context::$client_id);
  110. break;
  111. case GatewayProtocol::CMD_ON_MESSAGE:
  112. Event::onMessage(Context::$client_id, $pack->body);
  113. break;
  114. case GatewayProtocol::CMD_ON_CLOSE:
  115. Event::onClose(Context::$client_id);
  116. break;
  117. }
  118. StatisticClient::report(__CLASS__, $interface, 1, 0, '');
  119. }
  120. catch(\Exception $e)
  121. {
  122. $msg = 'client_id:'.Context::$client_id."\tclient_ip:".Context::$client_ip."\n".$e->__toString();
  123. StatisticClient::report(__CLASS__, $interface, 0, $e->getCode() > 0 ? $e->getCode() : 201, $msg);
  124. }
  125. $session_str_now = $_SESSION !== null ? Context::sessionEncode($_SESSION) : '';
  126. if($session_str_copy != $session_str_now)
  127. {
  128. Gateway::updateSocketSession(Context::$socket_id, $session_str_now);
  129. }
  130. Context::clear();
  131. }
  132. /**
  133. * 定时检查gateway通信端口,如果有新的gateway则去建立长连接
  134. */
  135. public function checkGatewayConnections()
  136. {
  137. $key = 'GLOBAL_GATEWAY_ADDRESS';
  138. $addresses_list = Store::instance('gateway')->get($key);
  139. if(empty($addresses_list))
  140. {
  141. return;
  142. }
  143. $addresses_list = array_reverse($addresses_list, true);
  144. // 循环遍历,查找未连接的gateway ip 端口
  145. foreach($addresses_list as $addr)
  146. {
  147. if(!isset($this->gatewayConnections[$addr]))
  148. {
  149. // 执行连接
  150. $conn = @stream_socket_client("tcp://$addr", $errno, $errstr, 1);
  151. if(!$conn)
  152. {
  153. if(!isset($this->badGatewayAddress[$addr]))
  154. {
  155. $this->badGatewayAddress[$addr] = 0;
  156. }
  157. // 删除连不上的端口
  158. if($this->badGatewayAddress[$addr]++ > self::MAX_RETRY_COUNT)
  159. {
  160. \Man\Core\Lib\Mutex::get();
  161. $addresses_list = Store::instance('gateway')->get($key);
  162. unset($addresses_list[$addr]);
  163. Store::instance('gateway')->set($key, $addresses_list);
  164. $this->notice("tcp://$addr ".$errstr." del $addr from store", false);
  165. \Man\Core\Lib\Mutex::release();
  166. }
  167. continue;
  168. }
  169. unset($this->badGatewayAddress[$addr]);
  170. $this->gatewayConnections[$addr] = $conn;
  171. stream_set_blocking($this->gatewayConnections[$addr], 0);
  172. // 初始化一些值
  173. $fd = (int) $this->gatewayConnections[$addr];
  174. $this->connections[$fd] = $this->gatewayConnections[$addr];
  175. $this->recvBuffers[$fd] = array('buf'=>'', 'remain_len'=>$this->prereadLength);
  176. // 添加数据可读事件
  177. $this->event->add($this->connections[$fd], \Man\Core\Events\BaseEvent::EV_READ , array($this, 'dealInputBase'), $fd);
  178. }
  179. }
  180. }
  181. /**
  182. * 发送数据给客户端
  183. * @see Man\Core.SocketWorker::sendToClient()
  184. */
  185. public function sendToClient($buffer, $con = null)
  186. {
  187. if($con)
  188. {
  189. $this->currentDealFd = (int) $con;
  190. }
  191. return parent::sendToClient($buffer);
  192. }
  193. /**
  194. * 关闭连接
  195. * @see Man\Core.SocketWorker::closeClient()
  196. */
  197. protected function closeClient($fd = null)
  198. {
  199. // 清理$this->gatewayConnections对应项
  200. foreach($this->gatewayConnections as $addr => $con)
  201. {
  202. $the_fd = (int) $con;
  203. if($the_fd == $fd)
  204. {
  205. unset($this->gatewayConnections[$addr], $this->badGatewayAddress[$addr]);
  206. }
  207. }
  208. parent::closeClient($fd);
  209. }
  210. }