Gateway.php 20 KB

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