Gateway.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. <?php
  2. namespace GatewayWorker;
  3. use Workerman\Connection\TcpConnection;
  4. use \Workerman\Worker;
  5. use \Workerman\Lib\Timer;
  6. use \Workerman\Protocols\GatewayProtocol;
  7. use \GatewayWorker\Lib\Lock;
  8. use \GatewayWorker\Lib\Store;
  9. use \Workerman\Autoloader;
  10. /**
  11. *
  12. * Gateway,基于Worker开发
  13. * 用于转发客户端的数据给Worker处理,以及转发Worker的数据给客户端
  14. *
  15. * @author walkor<walkor@workerman.net>
  16. *
  17. */
  18. class Gateway extends Worker
  19. {
  20. /**
  21. * 本机ip
  22. * @var 单机部署默认127.0.0.1,如果是分布式部署,需要设置成本机ip
  23. */
  24. public $lanIp = '127.0.0.1';
  25. /**
  26. * gateway内部通讯起始端口,每个gateway实例应该都不同,步长1000
  27. * @var int
  28. */
  29. public $startPort = 2000;
  30. /**
  31. * 是否可以平滑重启,gateway不能平滑重启,否则会导致连接断开
  32. * @var bool
  33. */
  34. public $reloadable = false;
  35. /**
  36. * 心跳时间间隔
  37. * @var int
  38. */
  39. public $pingInterval = 0;
  40. /**
  41. * $pingNotResponseLimit*$pingInterval时间内,客户端未发送任何数据,断开客户端连接
  42. * @var int
  43. */
  44. public $pingNotResponseLimit = 0;
  45. /**
  46. * 服务端向客户端发送的心跳数据
  47. * @var string
  48. */
  49. public $pingData = '';
  50. /**
  51. * 路由函数
  52. * @var callback
  53. */
  54. public $router = null;
  55. /**
  56. * 保存客户端的所有connection对象
  57. * @var array
  58. */
  59. protected $_clientConnections = array();
  60. /**
  61. * 保存所有worker的内部连接的connection对象
  62. * @var array
  63. */
  64. protected $_workerConnections = array();
  65. /**
  66. * gateway内部监听worker内部连接的worker
  67. * @var Worker
  68. */
  69. protected $_innerTcpWorker = null;
  70. /**
  71. * gateway内部监听udp数据的worker
  72. * @var Worker
  73. */
  74. protected $_innerUdpWorker = null;
  75. /**
  76. * 当worker启动时
  77. * @var callback
  78. */
  79. protected $_onWorkerStart = null;
  80. /**
  81. * 当有客户端连接时
  82. * @var callback
  83. */
  84. protected $_onConnect = null;
  85. /**
  86. * 当客户端发来消息时
  87. * @var callback
  88. */
  89. protected $_onMessage = null;
  90. /**
  91. * 当客户端连接关闭时
  92. * @var callback
  93. */
  94. protected $_onClose = null;
  95. /**
  96. * 当worker停止时
  97. * @var callback
  98. */
  99. protected $_onWorkerStop = null;
  100. /**
  101. * 进程启动时间
  102. * @var int
  103. */
  104. protected $_startTime = 0;
  105. /**
  106. * 构造函数
  107. * @param string $socket_name
  108. * @param array $context_option
  109. */
  110. public function __construct($socket_name, $context_option = array())
  111. {
  112. parent::__construct($socket_name, $context_option);
  113. $this->router = array("\\GatewayWorker\\Gateway", 'routerRand');
  114. $backrace = debug_backtrace();
  115. $this->_appInitPath = dirname($backrace[0]['file']);
  116. }
  117. /**
  118. * 运行
  119. * @see Workerman.Worker::run()
  120. */
  121. public function run()
  122. {
  123. // 保存用户的回调,当对应的事件发生时触发
  124. $this->_onWorkerStart = $this->onWorkerStart;
  125. $this->onWorkerStart = array($this, 'onWorkerStart');
  126. // 保存用户的回调,当对应的事件发生时触发
  127. $this->_onConnect = $this->onConnect;
  128. $this->onConnect = array($this, 'onClientConnect');
  129. // onMessage禁止用户设置回调
  130. $this->onMessage = array($this, 'onClientMessage');
  131. // 保存用户的回调,当对应的事件发生时触发
  132. $this->_onClose = $this->onClose;
  133. $this->onClose = array($this, 'onClientClose');
  134. // 保存用户的回调,当对应的事件发生时触发
  135. $this->_onWorkerStop = $this->onWorkerStop;
  136. $this->onWorkerStop = array($this, 'onWorkerStop');
  137. // 记录进程启动的时间
  138. $this->_startTime = time();
  139. // 运行父方法
  140. parent::run();
  141. }
  142. /**
  143. * 当客户端发来数据时,转发给worker处理
  144. * @param TcpConnection $connection
  145. * @param mixed $data
  146. */
  147. public function onClientMessage($connection, $data)
  148. {
  149. $connection->pingNotResponseCount = -1;
  150. $this->sendToWorker(GatewayProtocol::CMD_ON_MESSAGE, $connection, $data);
  151. }
  152. /**
  153. * 当客户端连接上来时,初始化一些客户端的数据
  154. * 包括全局唯一的client_id、初始化session等
  155. * @param unknown_type $connection
  156. */
  157. public function onClientConnect($connection)
  158. {
  159. // 分配一个全局唯一的client_id
  160. $connection->globalClientId = $this->createGlobalClientId();
  161. // 保存该连接的内部通讯的数据包报头,避免每次重新初始化
  162. $connection->gatewayHeader = array(
  163. 'local_ip' => $this->lanIp,
  164. 'local_port' => $this->lanPort,
  165. 'client_ip'=>$connection->getRemoteIp(),
  166. 'client_port'=>$connection->getRemotePort(),
  167. 'client_id'=>$connection->globalClientId,
  168. );
  169. // 连接的session
  170. $connection->session = '';
  171. // 该连接的心跳参数
  172. $connection->pingNotResponseCount = -1;
  173. // 保存客户端连接connection对象
  174. $this->_clientConnections[$connection->globalClientId] = $connection;
  175. // 保存该连接的内部gateway通讯地址
  176. $address = $this->lanIp.':'.$this->lanPort;
  177. $this->storeClientAddress($connection->globalClientId, $address);
  178. // 如果用户有自定义onConnect回调,则执行
  179. if($this->_onConnect)
  180. {
  181. call_user_func($this->_onConnect, $connection);
  182. }
  183. // 如果设置了Event::onConnect,则通知worker进程,让worker执行onConnect
  184. if(method_exists('Event','onConnect'))
  185. {
  186. $this->sendToWorker(GatewayProtocol::CMD_ON_CONNECTION, $connection);
  187. }
  188. }
  189. /**
  190. * 发送数据给worker进程
  191. * @param int $cmd
  192. * @param TcpConnection $connection
  193. * @param mixed $body
  194. */
  195. protected function sendToWorker($cmd, $connection, $body = '')
  196. {
  197. $gateway_data = $connection->gatewayHeader;
  198. $gateway_data['cmd'] = $cmd;
  199. $gateway_data['body'] = $body;
  200. $gateway_data['ext_data'] = $connection->session;
  201. if($this->_workerConnections)
  202. {
  203. // 调用路由函数,选择一个worker把请求转发给它
  204. $worker_connection = call_user_func($this->router, $this->_workerConnections, $connection, $cmd, $body);
  205. if(false === $worker_connection->send($gateway_data))
  206. {
  207. $msg = "SendBufferToWorker fail. May be the send buffer are overflow";
  208. $this->log($msg);
  209. return false;
  210. }
  211. }
  212. // 没有可用的worker
  213. else
  214. {
  215. // gateway启动后1-2秒内SendBufferToWorker fail是正常现象,因为与worker的连接还没建立起来,所以不记录日志,只是关闭连接
  216. $time_diff = 2;
  217. if(time() - $this->_startTime >= $time_diff)
  218. {
  219. $msg = "SendBufferToWorker fail. The connections between Gateway and BusinessWorker are not ready";
  220. $this->log($msg);
  221. }
  222. $connection->destroy();
  223. return false;
  224. }
  225. return true;
  226. }
  227. /**
  228. * 随机路由,返回worker connection对象
  229. * @param array $worker_connections
  230. * @param TcpConnection $client_connection
  231. * @param int $cmd
  232. * @param mixed $buffer
  233. * @return TcpConnection
  234. */
  235. public static function routerRand($worker_connections, $client_connection, $cmd, $buffer)
  236. {
  237. return $worker_connections[array_rand($worker_connections)];
  238. }
  239. /**
  240. * 保存客户端连接的gateway通讯地址
  241. * @param int $global_client_id
  242. * @param string $address
  243. * @return bool
  244. */
  245. protected function storeClientAddress($global_client_id, $address)
  246. {
  247. if(!Store::instance('gateway')->set('client_id-'.$global_client_id, $address))
  248. {
  249. $msg = 'storeClientAddress fail.';
  250. if(get_class(Store::instance('gateway')) == 'Memcached')
  251. {
  252. $msg .= " reason :".Store::instance('gateway')->getResultMessage();
  253. }
  254. $this->log($msg);
  255. return false;
  256. }
  257. return true;
  258. }
  259. /**
  260. * 删除客户端gateway通讯地址
  261. * @param int $global_client_id
  262. * @return void
  263. */
  264. protected function delClientAddress($global_client_id)
  265. {
  266. Store::instance('gateway')->delete('client_id-'.$global_client_id);
  267. }
  268. /**
  269. * 当客户端关闭时
  270. * @param unknown_type $connection
  271. */
  272. public function onClientClose($connection)
  273. {
  274. // 尝试通知worker,触发Event::onClose
  275. if(method_exists('Event','onClose'))
  276. {
  277. $this->sendToWorker(GatewayProtocol::CMD_ON_CLOSE, $connection);
  278. }
  279. // 清理连接的数据
  280. $this->delClientAddress($connection->globalClientId);
  281. unset($this->_clientConnections[$connection->globalClientId]);
  282. if($this->_onClose)
  283. {
  284. call_user_func($this->_onClose, $connection);
  285. }
  286. }
  287. /**
  288. * 创建一个workerman集群全局唯一的client_id
  289. * @return int|false
  290. */
  291. protected function createGlobalClientId()
  292. {
  293. $global_socket_key = 'GLOBAL_CLIENT_ID_KEY';
  294. $store = Store::instance('gateway');
  295. $global_client_id = $store->increment($global_socket_key);
  296. if(!$global_client_id || $global_client_id > 2147483646)
  297. {
  298. $store->set($global_socket_key, 0);
  299. $global_client_id = $store->increment($global_socket_key);
  300. }
  301. if(!$global_client_id)
  302. {
  303. $msg .= "createGlobalClientId fail :";
  304. if(get_class($store) == 'Memcached')
  305. {
  306. $msg .= $store->getResultMessage();
  307. }
  308. $this->log($msg);
  309. }
  310. return $global_client_id;
  311. }
  312. /**
  313. * 当Gateway启动的时候触发的回调函数
  314. * @return void
  315. */
  316. public function onWorkerStart()
  317. {
  318. // 分配一个内部通讯端口
  319. $this->lanPort = function_exists('posix_getppid') ? $this->startPort - posix_getppid() + posix_getpid() : $this->startPort;
  320. if($this->lanPort<0 || $this->lanPort >=65535)
  321. {
  322. $this->lanPort = rand($this->startPort, 65535);
  323. }
  324. // 如果有设置心跳,则定时执行
  325. if($this->pingInterval > 0)
  326. {
  327. Timer::add($this->pingInterval, array($this, 'ping'));
  328. }
  329. // 初始化gateway内部的监听,用于监听worker的连接已经连接上发来的数据
  330. $this->_innerTcpWorker = new Worker("GatewayProtocol://{$this->lanIp}:{$this->lanPort}");
  331. $this->_innerTcpWorker->listen();
  332. $this->_innerUdpWorker = new Worker("GatewayProtocol://{$this->lanIp}:{$this->lanPort}");
  333. $this->_innerUdpWorker->transport = 'udp';
  334. $this->_innerUdpWorker->listen();
  335. // 重新设置自动加载根目录
  336. Autoloader::setRootPath($this->_appInitPath);
  337. // 设置内部监听的相关回调
  338. $this->_innerTcpWorker->onMessage = array($this, 'onWorkerMessage');
  339. $this->_innerUdpWorker->onMessage = array($this, 'onWorkerMessage');
  340. $this->_innerTcpWorker->onConnect = array($this, 'onWorkerConnect');
  341. $this->_innerTcpWorker->onClose = array($this, 'onWorkerClose');
  342. // 注册gateway的内部通讯地址,worker去连这个地址,以便gateway与worker之间建立起TCP长连接
  343. if(!$this->registerAddress())
  344. {
  345. $this->log('registerAddress fail and exit');
  346. Worker::stopAll();
  347. }
  348. if($this->_onWorkerStart)
  349. {
  350. call_user_func($this->_onWorkerStart, $this);
  351. }
  352. }
  353. /**
  354. * 当worker通过内部通讯端口连接到gateway时
  355. * @param TcpConnection $connection
  356. */
  357. public function onWorkerConnect($connection)
  358. {
  359. $connection->remoteAddress = $connection->getRemoteIp().':'.$connection->getRemotePort();
  360. if(TcpConnection::$defaultMaxSendBufferSize == $connection->maxSendBufferSize)
  361. {
  362. $connection->maxSendBufferSize = 10*1024*1024;
  363. }
  364. $this->_workerConnections[$connection->remoteAddress] = $connection;
  365. }
  366. /**
  367. * 当worker发来数据时
  368. * @param TcpConnection $connection
  369. * @param mixed $data
  370. * @throws \Exception
  371. */
  372. public function onWorkerMessage($connection, $data)
  373. {
  374. $cmd = $data['cmd'];
  375. switch($cmd)
  376. {
  377. // 向某客户端发送数据,Gateway::sendToClient($client_id, $message);
  378. case GatewayProtocol::CMD_SEND_TO_ONE:
  379. if(isset($this->_clientConnections[$data['client_id']]))
  380. {
  381. $this->_clientConnections[$data['client_id']]->send($data['body']);
  382. }
  383. break;
  384. // 关闭客户端连接,Gateway::closeClient($client_id);
  385. case GatewayProtocol::CMD_KICK:
  386. if(isset($this->_clientConnections[$data['client_id']]))
  387. {
  388. $this->_clientConnections[$data['client_id']]->destroy();
  389. }
  390. break;
  391. // 广播, Gateway::sendToAll($message, $client_id_array)
  392. case GatewayProtocol::CMD_SEND_TO_ALL:
  393. // $client_id_array不为空时,只广播给$client_id_array指定的客户端
  394. if($data['ext_data'])
  395. {
  396. $client_id_array = unpack('N*', $data['ext_data']);
  397. foreach($client_id_array as $client_id)
  398. {
  399. if(isset($this->_clientConnections[$client_id]))
  400. {
  401. $this->_clientConnections[$client_id]->send($data['body']);
  402. }
  403. }
  404. }
  405. // $client_id_array为空时,广播给所有在线客户端
  406. else
  407. {
  408. foreach($this->_clientConnections as $client_connection)
  409. {
  410. $client_connection->send($data['body']);
  411. }
  412. }
  413. break;
  414. // 更新客户端session
  415. case GatewayProtocol::CMD_UPDATE_SESSION:
  416. if(isset($this->_clientConnections[$data['client_id']]))
  417. {
  418. $this->_clientConnections[$data['client_id']]->session = $data['ext_data'];
  419. }
  420. break;
  421. // 获得客户端在线状态 Gateway::getOnlineStatus()
  422. case GatewayProtocol::CMD_GET_ONLINE_STATUS:
  423. $online_status = json_encode(array_keys($this->_clientConnections));
  424. $connection->send($online_status);
  425. break;
  426. // 判断某个client_id是否在线 Gateway::isOnline($client_id)
  427. case GatewayProtocol::CMD_IS_ONLINE:
  428. $connection->send((int)isset($this->_clientConnections[$data['client_id']]));
  429. break;
  430. default :
  431. $err_msg = "gateway inner pack err cmd=$cmd";
  432. throw new \Exception($err_msg);
  433. }
  434. }
  435. /**
  436. * 当worker连接关闭时
  437. * @param TcpConnection $connection
  438. */
  439. public function onWorkerClose($connection)
  440. {
  441. //$this->log("{$connection->remoteAddress} CLOSE INNER_CONNECTION\n");
  442. unset($this->_workerConnections[$connection->remoteAddress]);
  443. }
  444. /**
  445. * 存储当前Gateway的内部通信地址
  446. * @param string $address
  447. * @return bool
  448. */
  449. protected function registerAddress()
  450. {
  451. $address = $this->lanIp.':'.$this->lanPort;
  452. // key
  453. $key = 'GLOBAL_GATEWAY_ADDRESS';
  454. try
  455. {
  456. $store = Store::instance('gateway');
  457. }
  458. catch(\Exception $msg)
  459. {
  460. $this->log($msg);
  461. return false;
  462. }
  463. // 为保证原子性,需要加锁
  464. Lock::get();
  465. $addresses_list = $store->get($key);
  466. if(empty($addresses_list))
  467. {
  468. $addresses_list = array();
  469. }
  470. $addresses_list[$address] = $address;
  471. if(!$store->set($key, $addresses_list))
  472. {
  473. Lock::release();
  474. if(get_class($store) == 'Memcached')
  475. {
  476. $msg = " registerAddress fail : Memcache Error " . $store->getResultMessage();
  477. }
  478. $this->log($msg);
  479. return false;
  480. }
  481. Lock::release();
  482. return true;
  483. }
  484. /**
  485. * 删除当前Gateway的内部通信地址
  486. * @param string $address
  487. * @return bool
  488. */
  489. protected function unregisterAddress()
  490. {
  491. $address = $this->lanIp.':'.$this->lanPort;
  492. $key = 'GLOBAL_GATEWAY_ADDRESS';
  493. try
  494. {
  495. $store = Store::instance('gateway');
  496. }
  497. catch (\Exception $msg)
  498. {
  499. $this->log($msg);
  500. return false;
  501. }
  502. // 为保证原子性,需要加锁
  503. Lock::get();
  504. $addresses_list = $store->get($key);
  505. if(empty($addresses_list))
  506. {
  507. $addresses_list = array();
  508. }
  509. unset($addresses_list[$address]);
  510. if(!$store->set($key, $addresses_list))
  511. {
  512. Lock::release();
  513. $msg = "unregisterAddress fail";
  514. if(get_class($store) == 'Memcached')
  515. {
  516. $msg .= " reason:".$store->getResultMessage();
  517. }
  518. $this->log($msg);
  519. return;
  520. }
  521. Lock::release();
  522. return true;
  523. }
  524. /**
  525. * 心跳逻辑
  526. * @return void
  527. */
  528. public function ping()
  529. {
  530. // 遍历所有客户端连接
  531. foreach($this->_clientConnections as $connection)
  532. {
  533. // 上次发送的心跳还没有回复次数大于限定值就断开
  534. if($this->pingNotResponseLimit > 0 && $connection->pingNotResponseCount >= $this->pingNotResponseLimit)
  535. {
  536. $connection->destroy();
  537. continue;
  538. }
  539. // $connection->pingNotResponseCount为-1说明最近客户端有发来消息,则不给客户端发送心跳
  540. if($connection->pingNotResponseCount++ >= 0)
  541. {
  542. if($this->pingData)
  543. {
  544. $connection->send($this->pingData);
  545. }
  546. }
  547. }
  548. }
  549. /**
  550. * 当gateway关闭时触发,清理数据
  551. * @return void
  552. */
  553. public function onWorkerStop()
  554. {
  555. $this->unregisterAddress();
  556. foreach($this->_clientConnections as $connection)
  557. {
  558. $this->delClientAddress($connection->globalClientId);
  559. }
  560. // 尝试触发用户设置的回调
  561. if($this->_onWorkerStop)
  562. {
  563. call_user_func($this->_onWorkerStop, $this);
  564. }
  565. }
  566. }