Gateway.php 17 KB

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