Gateway.php 19 KB

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