Gateway.php 17 KB

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