BusinessWorker.php 18 KB

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