Gateway.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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 = "SendBufferToWorker fail. The connections between Gateway and BusinessWorker are not ready";
  201. $this->log($msg);
  202. $connection->close();
  203. return false;
  204. }
  205. return true;
  206. }
  207. /**
  208. * 保存客户端连接的gateway通讯地址
  209. * @param int $global_client_id
  210. * @param string $address
  211. * @return bool
  212. */
  213. protected function storeClientAddress($global_client_id, $address)
  214. {
  215. if(!Store::instance('gateway')->set('gateway-'.$global_client_id, $address))
  216. {
  217. $msg = 'storeClientAddress fail.';
  218. if(get_class(Store::instance('gateway')) == 'Memcached')
  219. {
  220. $msg .= " reason :".Store::instance('gateway')->getResultMessage();
  221. }
  222. $this->log($msg);
  223. return false;
  224. }
  225. return true;
  226. }
  227. /**
  228. * 删除客户端gateway通讯地址
  229. * @param int $global_client_id
  230. * @return void
  231. */
  232. protected function delClientAddress($global_client_id)
  233. {
  234. Store::instance('gateway')->delete('gateway-'.$global_client_id);
  235. }
  236. /**
  237. * 当客户端关闭时
  238. * @param unknown_type $connection
  239. */
  240. public function onClientClose($connection)
  241. {
  242. // 尝试通知worker,触发Event::onClose
  243. if(method_exists('Event','onClose'))
  244. {
  245. $this->sendToWorker(GatewayProtocol::CMD_ON_CLOSE, $connection);
  246. }
  247. // 清理连接的数据
  248. $this->delClientAddress($connection->globalClientId);
  249. unset($this->_clientConnections[$connection->globalClientId]);
  250. if($this->_onClose)
  251. {
  252. call_user_func($this->_onClose, $connection);
  253. }
  254. }
  255. /**
  256. * 创建一个workerman集群全局唯一的client_id
  257. * @return int|false
  258. */
  259. protected function createGlobalClientId()
  260. {
  261. $global_socket_key = 'GLOBAL_SOCKET_ID_KEY';
  262. $store = Store::instance('gateway');
  263. $global_client_id = $store->increment($global_socket_key);
  264. if(!$global_client_id || $global_client_id > 2147483646)
  265. {
  266. $store->set($global_socket_key, 0);
  267. $global_client_id = $store->increment($global_socket_key);
  268. }
  269. if(!$global_client_id)
  270. {
  271. $msg .= "createGlobalClientId fail :";
  272. if(get_class($store) == 'Memcached')
  273. {
  274. $msg .= $store->getResultMessage();
  275. }
  276. $this->log($msg);
  277. }
  278. return $global_client_id;
  279. }
  280. /**
  281. * 当Gateway启动的时候触发的回调函数
  282. * @return void
  283. */
  284. public function onWorkerStart()
  285. {
  286. // 分配一个内部通讯端口
  287. $this->lanPort = $this->startPort - posix_getppid() + posix_getpid();
  288. if($this->lanPort<0 || $this->lanPort >=65535)
  289. {
  290. $this->lanPort = rand($this->startPort, 65535);
  291. }
  292. // 如果有设置心跳,则定时执行
  293. if($this->pingInterval > 0)
  294. {
  295. Timer::add($this->pingInterval, array($this, 'ping'));
  296. }
  297. // 初始化gateway内部的监听,用于监听worker的连接已经连接上发来的数据
  298. $this->_innerTcpWorker = new Worker("GatewayProtocol://{$this->lanIp}:{$this->lanPort}");
  299. $this->_innerTcpWorker->listen();
  300. $this->_innerUdpWorker = new Worker("GatewayProtocol://{$this->lanIp}:{$this->lanPort}");
  301. $this->_innerUdpWorker->transport = 'udp';
  302. $this->_innerUdpWorker->listen();
  303. // 重新设置自动加载根目录
  304. Autoloader::setRootPath($this->_appInitPath);
  305. // 设置内部监听的相关回调
  306. $this->_innerTcpWorker->onMessage = array($this, 'onWorkerMessage');
  307. $this->_innerUdpWorker->onMessage = array($this, 'onWorkerMessage');
  308. $this->_innerTcpWorker->onConnect = array($this, 'onWorkerConnect');
  309. $this->_innerTcpWorker->onClose = array($this, 'onWorkerClose');
  310. // 注册gateway的内部通讯地址,worker去连这个地址,以便gateway与worker之间建立起TCP长连接
  311. if(!$this->registerAddress())
  312. {
  313. $this->log('registerAddress fail and exit');
  314. Worker::stopAll();
  315. }
  316. if($this->_onWorkerStart)
  317. {
  318. call_user_func($this->_onWorkerStart, $this);
  319. }
  320. }
  321. /**
  322. * 当worker通过内部通讯端口连接到gateway时
  323. * @param TcpConnection $connection
  324. */
  325. public function onWorkerConnect($connection)
  326. {
  327. $connection->remoteAddress = $connection->getRemoteIp().':'.$connection->getRemotePort();
  328. $this->_workerConnections[$connection->remoteAddress] = $connection;
  329. }
  330. /**
  331. * 当worker发来数据时
  332. * @param TcpConnection $connection
  333. * @param mixed $data
  334. * @throws \Exception
  335. */
  336. public function onWorkerMessage($connection, $data)
  337. {
  338. $cmd = $data['cmd'];
  339. switch($cmd)
  340. {
  341. // 向某客户端发送数据,Gateway::sendToClient($client_id, $message);
  342. case GatewayProtocol::CMD_SEND_TO_ONE:
  343. if(isset($this->_clientConnections[$data['client_id']]))
  344. {
  345. $this->_clientConnections[$data['client_id']]->send($data['body']);
  346. }
  347. break;
  348. // 关闭客户端连接,Gateway::closeClient($client_id);
  349. case GatewayProtocol::CMD_KICK:
  350. if(isset($this->_clientConnections[$data['client_id']]))
  351. {
  352. $this->_clientConnections[$data['client_id']]->close();
  353. }
  354. break;
  355. // 广播, Gateway::sendToAll($message, $client_id_array)
  356. case GatewayProtocol::CMD_SEND_TO_ALL:
  357. // $client_id_array不为空时,只广播给$client_id_array指定的客户端
  358. if($data['ext_data'])
  359. {
  360. $client_id_array = unpack('N*', $data['ext_data']);
  361. foreach($client_id_array as $client_id)
  362. {
  363. if(isset($this->_clientConnections[$client_id]))
  364. {
  365. $this->_clientConnections[$client_id]->send($data['body']);
  366. }
  367. }
  368. }
  369. // $client_id_array为空时,广播给所有在线客户端
  370. else
  371. {
  372. foreach($this->_clientConnections as $client_connection)
  373. {
  374. $client_connection->send($data['body']);
  375. }
  376. }
  377. break;
  378. // 更新客户端session
  379. case GatewayProtocol::CMD_UPDATE_SESSION:
  380. if(isset($this->_clientConnections[$data['client_id']]))
  381. {
  382. $this->_clientConnections[$data['client_id']]->session = $data['ext_data'];
  383. }
  384. break;
  385. // 获得客户端在线状态 Gateway::getOnlineStatus()
  386. case GatewayProtocol::CMD_GET_ONLINE_STATUS:
  387. $online_status = json_encode(array_keys($this->_clientConnections));
  388. $connection->send($online_status);
  389. break;
  390. // 判断某个client_id是否在线 Gateway::isOnline($client_id)
  391. case GatewayProtocol::CMD_IS_ONLINE:
  392. $connection->send((int)isset($this->_clientConnections[$data['client_id']]));
  393. break;
  394. default :
  395. $err_msg = "gateway inner pack err cmd=$cmd";
  396. throw new \Exception($err_msg);
  397. }
  398. }
  399. /**
  400. * 当worker连接关闭时
  401. * @param TcpConnection $connection
  402. */
  403. public function onWorkerClose($connection)
  404. {
  405. //$this->log("{$connection->remoteAddress} CLOSE INNER_CONNECTION\n");
  406. unset($this->_workerConnections[$connection->remoteAddress]);
  407. }
  408. /**
  409. * 存储当前Gateway的内部通信地址
  410. * @param string $address
  411. * @return bool
  412. */
  413. protected function registerAddress()
  414. {
  415. $address = $this->lanIp.':'.$this->lanPort;
  416. // key
  417. $key = 'GLOBAL_GATEWAY_ADDRESS';
  418. try
  419. {
  420. $store = Store::instance('gateway');
  421. }
  422. catch(\Exception $msg)
  423. {
  424. $this->log($msg);
  425. return false;
  426. }
  427. // 为保证原子性,需要加锁
  428. Lock::get();
  429. $addresses_list = $store->get($key);
  430. if(empty($addresses_list))
  431. {
  432. $addresses_list = array();
  433. }
  434. $addresses_list[$address] = $address;
  435. if(!$store->set($key, $addresses_list))
  436. {
  437. Lock::release();
  438. if(get_class($store) == 'Memcached')
  439. {
  440. $msg = " registerAddress fail : " . $store->getResultMessage();
  441. }
  442. $this->log($msg);
  443. return false;
  444. }
  445. Lock::release();
  446. return true;
  447. }
  448. /**
  449. * 删除当前Gateway的内部通信地址
  450. * @param string $address
  451. * @return bool
  452. */
  453. protected function unregisterAddress()
  454. {
  455. $address = $this->lanIp.':'.$this->lanPort;
  456. $key = 'GLOBAL_GATEWAY_ADDRESS';
  457. try
  458. {
  459. $store = Store::instance('gateway');
  460. }
  461. catch (\Exception $msg)
  462. {
  463. $this->log($msg);
  464. return false;
  465. }
  466. // 为保证原子性,需要加锁
  467. Lock::get();
  468. $addresses_list = $store->get($key);
  469. if(empty($addresses_list))
  470. {
  471. $addresses_list = array();
  472. }
  473. unset($addresses_list[$address]);
  474. if(!$store->set($key, $addresses_list))
  475. {
  476. Lock::release();
  477. $msg = "unregisterAddress fail";
  478. if(get_class($store) == 'Memcached')
  479. {
  480. $msg .= " reason:".$store->getResultMessage();
  481. }
  482. $this->log($msg);
  483. return;
  484. }
  485. Lock::release();
  486. return true;
  487. }
  488. /**
  489. * 心跳逻辑
  490. * @return void
  491. */
  492. public function ping()
  493. {
  494. // 遍历所有客户端连接
  495. foreach($this->_clientConnections as $connection)
  496. {
  497. // 上次发送的心跳还没有回复次数大于限定值就断开
  498. if($this->pingNotResponseLimit > 0 && $connection->pingNotResponseCount >= $this->pingNotResponseLimit)
  499. {
  500. $connection->close();
  501. continue;
  502. }
  503. $connection->pingNotResponseCount++;
  504. $connection->send($this->pingData);
  505. }
  506. }
  507. /**
  508. * 当gateway关闭时触发,清理数据
  509. * @return void
  510. */
  511. public function onWorkerStop()
  512. {
  513. $this->unregisterAddress();
  514. foreach($this->_clientConnections as $connection)
  515. {
  516. $this->delClientAddress($connection->globalClientId);
  517. }
  518. // 尝试触发用户设置的回调
  519. if($this->_onWorkerStop)
  520. {
  521. call_user_func($this->_onWorkerStop, $this);
  522. }
  523. }
  524. }