Gateway.php 18 KB

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