BusinessWorker.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace GatewayWorker;
  15. use Workerman\Connection\TcpConnection;
  16. use Workerman\Worker;
  17. use Workerman\Timer;
  18. use Workerman\Connection\AsyncTcpConnection;
  19. use GatewayWorker\Protocols\GatewayProtocol;
  20. use GatewayWorker\Lib\Context;
  21. /**
  22. *
  23. * BusinessWorker 用于处理Gateway转发来的数据
  24. *
  25. * @author walkor<walkor@workerman.net>
  26. *
  27. */
  28. class BusinessWorker extends Worker
  29. {
  30. /**
  31. * 保存与 gateway 的连接 connection 对象
  32. *
  33. * @var array
  34. */
  35. public $gatewayConnections = array();
  36. /**
  37. * 注册中心地址
  38. *
  39. * @var string|array
  40. */
  41. public $registerAddress = '127.0.0.1:1236';
  42. /**
  43. * 事件处理类,默认是 Event 类
  44. *
  45. * @var string
  46. */
  47. public $eventHandler = 'Events';
  48. /**
  49. * 秘钥
  50. *
  51. * @var string
  52. */
  53. public $secretKey = '';
  54. /**
  55. * businessWorker进程将消息转发给gateway进程的发送缓冲区大小
  56. *
  57. * @var int
  58. */
  59. public $sendToGatewayBufferSize = 10240000;
  60. /**
  61. * 保存用户设置的 worker 启动回调
  62. *
  63. * @var callable|null
  64. */
  65. protected $_onWorkerStart = null;
  66. /**
  67. * 保存用户设置的 workerReload 回调
  68. *
  69. * @var callable|null
  70. */
  71. protected $_onWorkerReload = null;
  72. /**
  73. * 保存用户设置的 workerStop 回调
  74. *
  75. * @var callable|null
  76. */
  77. protected $_onWorkerStop= null;
  78. /**
  79. * 到注册中心的连接
  80. *
  81. * @var AsyncTcpConnection
  82. */
  83. protected $_registerConnection = null;
  84. /**
  85. * 处于连接状态的 gateway 通讯地址
  86. *
  87. * @var array
  88. */
  89. protected $_connectingGatewayAddresses = array();
  90. /**
  91. * 所有 geteway 内部通讯地址
  92. *
  93. * @var array
  94. */
  95. protected $_gatewayAddresses = array();
  96. /**
  97. * 等待连接个 gateway 地址
  98. *
  99. * @var array
  100. */
  101. protected $_waitingConnectGatewayAddresses = array();
  102. /**
  103. * Event::onConnect 回调
  104. *
  105. * @var callable|null
  106. */
  107. protected $_eventOnConnect = null;
  108. /**
  109. * Event::onMessage 回调
  110. *
  111. * @var callable|null
  112. */
  113. protected $_eventOnMessage = null;
  114. /**
  115. * Event::onClose 回调
  116. *
  117. * @var callable|null
  118. */
  119. protected $_eventOnClose = null;
  120. /**
  121. * websocket回调
  122. *
  123. * @var null
  124. */
  125. protected $_eventOnWebSocketConnect = null;
  126. /**
  127. * SESSION 版本缓存
  128. *
  129. * @var array
  130. */
  131. protected $_sessionVersion = array();
  132. /**
  133. * 用于保持长连接的心跳时间间隔
  134. *
  135. * @var int
  136. */
  137. const PERSISTENCE_CONNECTION_PING_INTERVAL = 25;
  138. /**
  139. * 构造函数
  140. *
  141. * @param string $socket_name
  142. * @param array $context_option
  143. */
  144. public function __construct($socket_name = '', $context_option = array())
  145. {
  146. parent::__construct($socket_name, $context_option);
  147. $backrace = debug_backtrace();
  148. $this->_autoloadRootPath = dirname($backrace[0]['file']);
  149. }
  150. /**
  151. * {@inheritdoc}
  152. */
  153. public function run()
  154. {
  155. $this->_onWorkerStart = $this->onWorkerStart;
  156. $this->_onWorkerReload = $this->onWorkerReload;
  157. $this->_onWorkerStop = $this->onWorkerStop;
  158. $this->onWorkerStop = array($this, 'onWorkerStop');
  159. $this->onWorkerStart = array($this, 'onWorkerStart');
  160. $this->onWorkerReload = array($this, 'onWorkerReload');
  161. parent::run();
  162. }
  163. /**
  164. * 当进程启动时一些初始化工作
  165. *
  166. * @return void
  167. */
  168. protected function onWorkerStart()
  169. {
  170. if (function_exists('opcache_reset')) {
  171. opcache_reset();
  172. }
  173. if (!class_exists('\Protocols\GatewayProtocol')) {
  174. class_alias('GatewayWorker\Protocols\GatewayProtocol', 'Protocols\GatewayProtocol');
  175. }
  176. if (!is_array($this->registerAddress)) {
  177. $this->registerAddress = array($this->registerAddress);
  178. }
  179. $this->connectToRegister();
  180. \GatewayWorker\Lib\Gateway::setBusinessWorker($this);
  181. \GatewayWorker\Lib\Gateway::$secretKey = $this->secretKey;
  182. if ($this->_onWorkerStart) {
  183. call_user_func($this->_onWorkerStart, $this);
  184. }
  185. if (is_callable($this->eventHandler . '::onWorkerStart')) {
  186. call_user_func($this->eventHandler . '::onWorkerStart', $this);
  187. }
  188. // 设置回调
  189. if (is_callable($this->eventHandler . '::onConnect')) {
  190. $this->_eventOnConnect = $this->eventHandler . '::onConnect';
  191. }
  192. if (is_callable($this->eventHandler . '::onMessage')) {
  193. $this->_eventOnMessage = $this->eventHandler . '::onMessage';
  194. } else {
  195. echo "Waring: {$this->eventHandler}::onMessage is not callable\n";
  196. }
  197. if (is_callable($this->eventHandler . '::onClose')) {
  198. $this->_eventOnClose = $this->eventHandler . '::onClose';
  199. }
  200. if (is_callable($this->eventHandler . '::onWebSocketConnect')) {
  201. $this->_eventOnWebSocketConnect = $this->eventHandler . '::onWebSocketConnect';
  202. }
  203. }
  204. /**
  205. * onWorkerReload 回调
  206. *
  207. * @param Worker $worker
  208. */
  209. protected function onWorkerReload($worker)
  210. {
  211. // 防止进程立刻退出
  212. $worker->reloadable = false;
  213. // 延迟 0.05 秒退出,避免 BusinessWorker 瞬间全部退出导致没有可用的 BusinessWorker 进程
  214. Timer::add(0.05, array('Workerman\Worker', 'stopAll'));
  215. // 执行用户定义的 onWorkerReload 回调
  216. if ($this->_onWorkerReload) {
  217. call_user_func($this->_onWorkerReload, $this);
  218. }
  219. }
  220. /**
  221. * 当进程关闭时一些清理工作
  222. *
  223. * @return void
  224. */
  225. protected function onWorkerStop()
  226. {
  227. if ($this->_onWorkerStop) {
  228. call_user_func($this->_onWorkerStop, $this);
  229. }
  230. if (is_callable($this->eventHandler . '::onWorkerStop')) {
  231. call_user_func($this->eventHandler . '::onWorkerStop', $this);
  232. }
  233. }
  234. /**
  235. * 连接服务注册中心
  236. *
  237. * @return void
  238. */
  239. public function connectToRegister()
  240. {
  241. foreach ($this->registerAddress as $register_address) {
  242. $register_connection = new AsyncTcpConnection("text://{$register_address}");
  243. $secret_key = $this->secretKey;
  244. $register_connection->onConnect = function () use ($register_connection, $secret_key, $register_address) {
  245. $register_connection->send('{"event":"worker_connect","secret_key":"' . $secret_key . '"}');
  246. // 如果Register服务器不在本地服务器,则需要保持心跳
  247. if (strpos($register_address, '127.0.0.1') !== 0) {
  248. $register_connection->ping_timer = Timer::add(self::PERSISTENCE_CONNECTION_PING_INTERVAL, function () use ($register_connection) {
  249. $register_connection->send('{"event":"ping"}');
  250. });
  251. }
  252. };
  253. $register_connection->onClose = function ($register_connection) {
  254. if(!empty($register_connection->ping_timer)) {
  255. Timer::del($register_connection->ping_timer);
  256. }
  257. $register_connection->reconnect(1);
  258. };
  259. $register_connection->onMessage = array($this, 'onRegisterConnectionMessage');
  260. $register_connection->connect();
  261. }
  262. }
  263. /**
  264. * 当注册中心发来消息时
  265. *
  266. * @return void
  267. */
  268. public function onRegisterConnectionMessage($register_connection, $data)
  269. {
  270. $data = json_decode($data, true);
  271. if (!isset($data['event'])) {
  272. echo "Received bad data from Register\n";
  273. return;
  274. }
  275. $event = $data['event'];
  276. switch ($event) {
  277. case 'broadcast_addresses':
  278. if (!is_array($data['addresses'])) {
  279. echo "Received bad data from Register. Addresses empty\n";
  280. return;
  281. }
  282. $addresses = $data['addresses'];
  283. $this->_gatewayAddresses = array();
  284. foreach ($addresses as $addr) {
  285. $this->_gatewayAddresses[$addr] = $addr;
  286. }
  287. $this->checkGatewayConnections($addresses);
  288. break;
  289. default:
  290. echo "Receive bad event:$event from Register.\n";
  291. }
  292. }
  293. /**
  294. * 当 gateway 转发来数据时
  295. *
  296. * @param TcpConnection $connection
  297. * @param mixed $data
  298. */
  299. public function onGatewayMessage($connection, $data)
  300. {
  301. $cmd = $data['cmd'];
  302. if ($cmd === GatewayProtocol::CMD_PING) {
  303. return;
  304. }
  305. // 上下文数据
  306. Context::$client_ip = $data['client_ip'];
  307. Context::$client_port = $data['client_port'];
  308. Context::$local_ip = $data['local_ip'];
  309. Context::$local_port = $data['local_port'];
  310. Context::$connection_id = $data['connection_id'];
  311. Context::$client_id = Context::addressToClientId($data['local_ip'], $data['local_port'],
  312. $data['connection_id']);
  313. // $_SERVER 变量
  314. $_SERVER = array(
  315. 'REMOTE_ADDR' => long2ip($data['client_ip']),
  316. 'REMOTE_PORT' => $data['client_port'],
  317. 'GATEWAY_ADDR' => long2ip($data['local_ip']),
  318. 'GATEWAY_PORT' => $data['gateway_port'],
  319. 'GATEWAY_CLIENT_ID' => Context::$client_id,
  320. );
  321. // 检查session版本,如果是过期的session数据则拉取最新的数据
  322. if ($cmd !== GatewayProtocol::CMD_ON_CLOSE && isset($this->_sessionVersion[Context::$client_id]) && $this->_sessionVersion[Context::$client_id] !== crc32($data['ext_data'])) {
  323. $_SESSION = Context::$old_session = \GatewayWorker\Lib\Gateway::getSession(Context::$client_id);
  324. $this->_sessionVersion[Context::$client_id] = crc32($data['ext_data']);
  325. } else {
  326. if (!isset($this->_sessionVersion[Context::$client_id])) {
  327. $this->_sessionVersion[Context::$client_id] = crc32($data['ext_data']);
  328. }
  329. // 尝试解析 session
  330. if ($data['ext_data'] != '') {
  331. Context::$old_session = $_SESSION = Context::sessionDecode($data['ext_data']);
  332. } else {
  333. Context::$old_session = $_SESSION = null;
  334. }
  335. }
  336. // 尝试执行 Event::onConnection、Event::onMessage、Event::onClose
  337. switch ($cmd) {
  338. case GatewayProtocol::CMD_ON_CONNECT:
  339. if ($this->_eventOnConnect) {
  340. call_user_func($this->_eventOnConnect, Context::$client_id);
  341. }
  342. break;
  343. case GatewayProtocol::CMD_ON_MESSAGE:
  344. if ($this->_eventOnMessage) {
  345. call_user_func($this->_eventOnMessage, Context::$client_id, $data['body']);
  346. }
  347. break;
  348. case GatewayProtocol::CMD_ON_CLOSE:
  349. unset($this->_sessionVersion[Context::$client_id]);
  350. if ($this->_eventOnClose) {
  351. call_user_func($this->_eventOnClose, Context::$client_id);
  352. }
  353. break;
  354. case GatewayProtocol::CMD_ON_WEBSOCKET_CONNECT:
  355. if ($this->_eventOnWebSocketConnect) {
  356. call_user_func($this->_eventOnWebSocketConnect, Context::$client_id, $data['body']);
  357. }
  358. break;
  359. }
  360. // session 必须是数组
  361. if ($_SESSION !== null && !is_array($_SESSION)) {
  362. throw new \Exception('$_SESSION must be an array. But $_SESSION=' . var_export($_SESSION, true) . ' is not array.');
  363. }
  364. // 判断 session 是否被更改
  365. if ($_SESSION !== Context::$old_session && $cmd !== GatewayProtocol::CMD_ON_CLOSE) {
  366. $session_str_now = $_SESSION !== null ? Context::sessionEncode($_SESSION) : '';
  367. \GatewayWorker\Lib\Gateway::setSocketSession(Context::$client_id, $session_str_now);
  368. $this->_sessionVersion[Context::$client_id] = crc32($session_str_now);
  369. }
  370. Context::clear();
  371. }
  372. /**
  373. * 当与 Gateway 的连接断开时触发
  374. *
  375. * @param TcpConnection $connection
  376. * @return void
  377. */
  378. public function onGatewayClose($connection)
  379. {
  380. $addr = $connection->remoteAddr;
  381. unset($this->gatewayConnections[$addr], $this->_connectingGatewayAddresses[$addr]);
  382. if (isset($this->_gatewayAddresses[$addr]) && !isset($this->_waitingConnectGatewayAddresses[$addr])) {
  383. Timer::add(1, array($this, 'tryToConnectGateway'), array($addr), false);
  384. $this->_waitingConnectGatewayAddresses[$addr] = $addr;
  385. }
  386. }
  387. /**
  388. * 尝试连接 Gateway 内部通讯地址
  389. *
  390. * @param string $addr
  391. */
  392. public function tryToConnectGateway($addr)
  393. {
  394. if (!isset($this->gatewayConnections[$addr]) && !isset($this->_connectingGatewayAddresses[$addr]) && isset($this->_gatewayAddresses[$addr])) {
  395. $gateway_connection = new AsyncTcpConnection("GatewayProtocol://$addr");
  396. $gateway_connection->remoteAddr = $addr;
  397. $gateway_connection->onConnect = array($this, 'onConnectGateway');
  398. $gateway_connection->onMessage = array($this, 'onGatewayMessage');
  399. $gateway_connection->onClose = array($this, 'onGatewayClose');
  400. $gateway_connection->onError = array($this, 'onGatewayError');
  401. $gateway_connection->maxSendBufferSize = $this->sendToGatewayBufferSize;
  402. if (TcpConnection::$defaultMaxSendBufferSize == $gateway_connection->maxSendBufferSize) {
  403. $gateway_connection->maxSendBufferSize = 50 * 1024 * 1024;
  404. }
  405. $gateway_data = GatewayProtocol::$empty;
  406. $gateway_data['cmd'] = GatewayProtocol::CMD_WORKER_CONNECT;
  407. $gateway_data['body'] = json_encode(array(
  408. 'worker_key' =>"{$this->name}:{$this->id}",
  409. 'secret_key' => $this->secretKey,
  410. ));
  411. $gateway_connection->send($gateway_data);
  412. $gateway_connection->connect();
  413. $this->_connectingGatewayAddresses[$addr] = $addr;
  414. }
  415. unset($this->_waitingConnectGatewayAddresses[$addr]);
  416. }
  417. /**
  418. * 检查 gateway 的通信端口是否都已经连
  419. * 如果有未连接的端口,则尝试连接
  420. *
  421. * @param array $addresses_list
  422. */
  423. public function checkGatewayConnections($addresses_list)
  424. {
  425. if (empty($addresses_list)) {
  426. return;
  427. }
  428. foreach ($addresses_list as $addr) {
  429. if (!isset($this->_waitingConnectGatewayAddresses[$addr])) {
  430. $this->tryToConnectGateway($addr);
  431. }
  432. }
  433. }
  434. /**
  435. * 当连接上 gateway 的通讯端口时触发
  436. * 将连接 connection 对象保存起来
  437. *
  438. * @param TcpConnection $connection
  439. * @return void
  440. */
  441. public function onConnectGateway($connection)
  442. {
  443. $this->gatewayConnections[$connection->remoteAddr] = $connection;
  444. unset($this->_connectingGatewayAddresses[$connection->remoteAddr], $this->_waitingConnectGatewayAddresses[$connection->remoteAddr]);
  445. }
  446. /**
  447. * 当与 gateway 的连接出现错误时触发
  448. *
  449. * @param TcpConnection $connection
  450. * @param int $error_no
  451. * @param string $error_msg
  452. */
  453. public function onGatewayError($connection, $error_no, $error_msg)
  454. {
  455. echo "GatewayConnection Error : $error_no ,$error_msg\n";
  456. }
  457. /**
  458. * 获取所有 Gateway 内部通讯地址
  459. *
  460. * @return array
  461. */
  462. public function getAllGatewayAddresses()
  463. {
  464. return $this->_gatewayAddresses;
  465. }
  466. }