Gateway.php 16 KB

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