Worker.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  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 Workerman;
  15. require_once __DIR__ . '/Lib/Constants.php';
  16. use Workerman\Events\EventInterface;
  17. use Workerman\Connection\ConnectionInterface;
  18. use Workerman\Connection\TcpConnection;
  19. use Workerman\Connection\UdpConnection;
  20. use Workerman\Lib\Timer;
  21. use Exception;
  22. /**
  23. * Worker class
  24. * A container for listening ports
  25. */
  26. class Worker
  27. {
  28. /**
  29. * Version.
  30. *
  31. * @var string
  32. */
  33. const VERSION = '3.4.6';
  34. /**
  35. * Status starting.
  36. *
  37. * @var int
  38. */
  39. const STATUS_STARTING = 1;
  40. /**
  41. * Status running.
  42. *
  43. * @var int
  44. */
  45. const STATUS_RUNNING = 2;
  46. /**
  47. * Status shutdown.
  48. *
  49. * @var int
  50. */
  51. const STATUS_SHUTDOWN = 4;
  52. /**
  53. * Status reloading.
  54. *
  55. * @var int
  56. */
  57. const STATUS_RELOADING = 8;
  58. /**
  59. * After sending the restart command to the child process KILL_WORKER_TIMER_TIME seconds,
  60. * if the process is still living then forced to kill.
  61. *
  62. * @var int
  63. */
  64. const KILL_WORKER_TIMER_TIME = 2;
  65. /**
  66. * Default backlog. Backlog is the maximum length of the queue of pending connections.
  67. *
  68. * @var int
  69. */
  70. const DEFAULT_BACKLOG = 102400;
  71. /**
  72. * Max udp package size.
  73. *
  74. * @var int
  75. */
  76. const MAX_UDP_PACKAGE_SIZE = 65535;
  77. /**
  78. * Worker id.
  79. *
  80. * @var int
  81. */
  82. public $id = 0;
  83. /**
  84. * Name of the worker processes.
  85. *
  86. * @var string
  87. */
  88. public $name = 'none';
  89. /**
  90. * Number of worker processes.
  91. *
  92. * @var int
  93. */
  94. public $count = 1;
  95. /**
  96. * Unix user of processes, needs appropriate privileges (usually root).
  97. *
  98. * @var string
  99. */
  100. public $user = '';
  101. /**
  102. * Unix group of processes, needs appropriate privileges (usually root).
  103. *
  104. * @var string
  105. */
  106. public $group = '';
  107. /**
  108. * reloadable.
  109. *
  110. * @var bool
  111. */
  112. public $reloadable = true;
  113. /**
  114. * reuse port.
  115. *
  116. * @var bool
  117. */
  118. public $reusePort = false;
  119. /**
  120. * Emitted when worker processes start.
  121. *
  122. * @var callback
  123. */
  124. public $onWorkerStart = null;
  125. /**
  126. * Emitted when a socket connection is successfully established.
  127. *
  128. * @var callback
  129. */
  130. public $onConnect = null;
  131. /**
  132. * Emitted when data is received.
  133. *
  134. * @var callback
  135. */
  136. public $onMessage = null;
  137. /**
  138. * Emitted when the other end of the socket sends a FIN packet.
  139. *
  140. * @var callback
  141. */
  142. public $onClose = null;
  143. /**
  144. * Emitted when an error occurs with connection.
  145. *
  146. * @var callback
  147. */
  148. public $onError = null;
  149. /**
  150. * Emitted when the send buffer becomes full.
  151. *
  152. * @var callback
  153. */
  154. public $onBufferFull = null;
  155. /**
  156. * Emitted when the send buffer becomes empty.
  157. *
  158. * @var callback
  159. */
  160. public $onBufferDrain = null;
  161. /**
  162. * Emitted when worker processes stoped.
  163. *
  164. * @var callback
  165. */
  166. public $onWorkerStop = null;
  167. /**
  168. * Emitted when worker processes get reload signal.
  169. *
  170. * @var callback
  171. */
  172. public $onWorkerReload = null;
  173. /**
  174. * Transport layer protocol.
  175. *
  176. * @var string
  177. */
  178. public $transport = 'tcp';
  179. /**
  180. * Store all connections of clients.
  181. *
  182. * @var array
  183. */
  184. public $connections = array();
  185. /**
  186. * Application layer protocol.
  187. *
  188. * @var Protocols\ProtocolInterface
  189. */
  190. public $protocol = '';
  191. /**
  192. * Root path for autoload.
  193. *
  194. * @var string
  195. */
  196. protected $_autoloadRootPath = '';
  197. /**
  198. * Daemonize.
  199. *
  200. * @var bool
  201. */
  202. public static $daemonize = false;
  203. /**
  204. * Stdout file.
  205. *
  206. * @var string
  207. */
  208. public static $stdoutFile = '/dev/null';
  209. /**
  210. * The file to store master process PID.
  211. *
  212. * @var string
  213. */
  214. public static $pidFile = '';
  215. /**
  216. * Log file.
  217. *
  218. * @var mixed
  219. */
  220. public static $logFile = '';
  221. /**
  222. * Global event loop.
  223. *
  224. * @var Events\EventInterface
  225. */
  226. public static $globalEvent = null;
  227. /**
  228. * Emitted when the master process get reload signal.
  229. *
  230. * @var callback
  231. */
  232. public static $onMasterReload = null;
  233. /**
  234. * Emitted when the master process terminated.
  235. *
  236. * @var callback
  237. */
  238. public static $onMasterStop = null;
  239. /**
  240. * EventLoopClass
  241. *
  242. * @var string
  243. */
  244. public static $eventLoopClass = '';
  245. /**
  246. * The PID of master process.
  247. *
  248. * @var int
  249. */
  250. protected static $_masterPid = 0;
  251. /**
  252. * Listening socket.
  253. *
  254. * @var resource
  255. */
  256. protected $_mainSocket = null;
  257. /**
  258. * Socket name. The format is like this http://0.0.0.0:80 .
  259. *
  260. * @var string
  261. */
  262. protected $_socketName = '';
  263. /**
  264. * Context of socket.
  265. *
  266. * @var resource
  267. */
  268. protected $_context = null;
  269. /**
  270. * All worker instances.
  271. *
  272. * @var array
  273. */
  274. protected static $_workers = array();
  275. /**
  276. * All worker porcesses pid.
  277. * The format is like this [worker_id=>[pid=>pid, pid=>pid, ..], ..]
  278. *
  279. * @var array
  280. */
  281. protected static $_pidMap = array();
  282. /**
  283. * All worker processes waiting for restart.
  284. * The format is like this [pid=>pid, pid=>pid].
  285. *
  286. * @var array
  287. */
  288. protected static $_pidsToRestart = array();
  289. /**
  290. * Mapping from PID to worker process ID.
  291. * The format is like this [worker_id=>[0=>$pid, 1=>$pid, ..], ..].
  292. *
  293. * @var array
  294. */
  295. protected static $_idMap = array();
  296. /**
  297. * Current status.
  298. *
  299. * @var int
  300. */
  301. protected static $_status = self::STATUS_STARTING;
  302. /**
  303. * Maximum length of the worker names.
  304. *
  305. * @var int
  306. */
  307. protected static $_maxWorkerNameLength = 12;
  308. /**
  309. * Maximum length of the socket names.
  310. *
  311. * @var int
  312. */
  313. protected static $_maxSocketNameLength = 12;
  314. /**
  315. * Maximum length of the process user names.
  316. *
  317. * @var int
  318. */
  319. protected static $_maxUserNameLength = 12;
  320. /**
  321. * The file to store status info of current worker process.
  322. *
  323. * @var string
  324. */
  325. protected static $_statisticsFile = '';
  326. /**
  327. * Start file.
  328. *
  329. * @var string
  330. */
  331. protected static $_startFile = '';
  332. /**
  333. * Status info of current worker process.
  334. *
  335. * @var array
  336. */
  337. protected static $_globalStatistics = array(
  338. 'start_timestamp' => 0,
  339. 'worker_exit_info' => array()
  340. );
  341. /**
  342. * Available event loops.
  343. *
  344. * @var array
  345. */
  346. protected static $_availableEventLoops = array(
  347. 'libevent' => '\Workerman\Events\Libevent',
  348. 'event' => '\Workerman\Events\Event'
  349. );
  350. /**
  351. * PHP built-in protocols.
  352. *
  353. * @var array
  354. */
  355. protected static $_builtinTransports = array(
  356. 'tcp' => 'tcp',
  357. 'udp' => 'udp',
  358. 'unix' => 'unix',
  359. 'ssl' => 'tcp'
  360. );
  361. /**
  362. * Run all worker instances.
  363. *
  364. * @return void
  365. */
  366. public static function runAll()
  367. {
  368. self::checkSapiEnv();
  369. self::init();
  370. self::parseCommand();
  371. self::daemonize();
  372. self::initWorkers();
  373. self::installSignal();
  374. self::saveMasterPid();
  375. self::forkWorkers();
  376. self::displayUI();
  377. self::resetStd();
  378. self::monitorWorkers();
  379. }
  380. /**
  381. * Check sapi.
  382. *
  383. * @return void
  384. */
  385. protected static function checkSapiEnv()
  386. {
  387. // Only for cli.
  388. if (php_sapi_name() != "cli") {
  389. exit("only run in command line mode \n");
  390. }
  391. }
  392. /**
  393. * Init.
  394. *
  395. * @return void
  396. */
  397. protected static function init()
  398. {
  399. // Start file.
  400. $backtrace = debug_backtrace();
  401. self::$_startFile = $backtrace[count($backtrace) - 1]['file'];
  402. // Pid file.
  403. if (empty(self::$pidFile)) {
  404. self::$pidFile = __DIR__ . "/../" . str_replace('/', '_', self::$_startFile) . ".pid";
  405. }
  406. // Log file.
  407. if (empty(self::$logFile)) {
  408. self::$logFile = __DIR__ . '/../workerman.log';
  409. }
  410. $log_file = (string)self::$logFile;
  411. if (!is_file($log_file)) {
  412. touch($log_file);
  413. chmod($log_file, 0622);
  414. }
  415. // State.
  416. self::$_status = self::STATUS_STARTING;
  417. // For statistics.
  418. self::$_globalStatistics['start_timestamp'] = time();
  419. self::$_statisticsFile = sys_get_temp_dir() . '/workerman.status';
  420. // Process title.
  421. self::setProcessTitle('WorkerMan: master process start_file=' . self::$_startFile);
  422. // Init data for worker id.
  423. self::initId();
  424. // Timer init.
  425. Timer::init();
  426. }
  427. /**
  428. * Init All worker instances.
  429. *
  430. * @return void
  431. */
  432. protected static function initWorkers()
  433. {
  434. foreach (self::$_workers as $worker) {
  435. // Worker name.
  436. if (empty($worker->name)) {
  437. $worker->name = 'none';
  438. }
  439. // Get maximum length of worker name.
  440. $worker_name_length = strlen($worker->name);
  441. if (self::$_maxWorkerNameLength < $worker_name_length) {
  442. self::$_maxWorkerNameLength = $worker_name_length;
  443. }
  444. // Get maximum length of socket name.
  445. $socket_name_length = strlen($worker->getSocketName());
  446. if (self::$_maxSocketNameLength < $socket_name_length) {
  447. self::$_maxSocketNameLength = $socket_name_length;
  448. }
  449. // Get unix user of the worker process.
  450. if (empty($worker->user)) {
  451. $worker->user = self::getCurrentUser();
  452. } else {
  453. if (posix_getuid() !== 0 && $worker->user != self::getCurrentUser()) {
  454. self::log('Warning: You must have the root privileges to change uid and gid.');
  455. }
  456. }
  457. // Get maximum length of unix user name.
  458. $user_name_length = strlen($worker->user);
  459. if (self::$_maxUserNameLength < $user_name_length) {
  460. self::$_maxUserNameLength = $user_name_length;
  461. }
  462. // Listen.
  463. if (!$worker->reusePort) {
  464. $worker->listen();
  465. }
  466. }
  467. }
  468. /**
  469. * Get all worker instances.
  470. *
  471. * @return array
  472. */
  473. public static function getAllWorkers()
  474. {
  475. return self::$_workers;
  476. }
  477. /**
  478. * Get global event-loop instance.
  479. *
  480. * @return EventInterface
  481. */
  482. public static function getEventLoop()
  483. {
  484. return self::$globalEvent;
  485. }
  486. /**
  487. * Init idMap.
  488. * return void
  489. */
  490. protected static function initId()
  491. {
  492. foreach (self::$_workers as $worker_id => $worker) {
  493. $new_id_map = array();
  494. for($key = 0; $key < $worker->count; $key++) {
  495. $new_id_map[$key] = isset(self::$_idMap[$worker_id][$key]) ? self::$_idMap[$worker_id][$key] : 0;
  496. }
  497. self::$_idMap[$worker_id] = $new_id_map;
  498. }
  499. }
  500. /**
  501. * Get unix user of current porcess.
  502. *
  503. * @return string
  504. */
  505. protected static function getCurrentUser()
  506. {
  507. $user_info = posix_getpwuid(posix_getuid());
  508. return $user_info['name'];
  509. }
  510. /**
  511. * Display staring UI.
  512. *
  513. * @return void
  514. */
  515. protected static function displayUI()
  516. {
  517. self::safeEcho("\033[1A\n\033[K-----------------------\033[47;30m WORKERMAN \033[0m-----------------------------\n\033[0m");
  518. self::safeEcho('Workerman version:'. Worker::VERSION. " PHP version:". PHP_VERSION. "\n");
  519. self::safeEcho("------------------------\033[47;30m WORKERS \033[0m-------------------------------\n");
  520. self::safeEcho("\033[47;30muser\033[0m". str_pad('',
  521. self::$_maxUserNameLength + 2 - strlen('user')). "\033[47;30mworker\033[0m". str_pad('',
  522. self::$_maxWorkerNameLength + 2 - strlen('worker')). "\033[47;30mlisten\033[0m". str_pad('',
  523. self::$_maxSocketNameLength + 2 - strlen('listen')). "\033[47;30mprocesses\033[0m \033[47;30m". "status\033[0m\n");
  524. foreach (self::$_workers as $worker) {
  525. self::safeEcho(str_pad($worker->user, self::$_maxUserNameLength + 2). str_pad($worker->name,
  526. self::$_maxWorkerNameLength + 2). str_pad($worker->getSocketName(),
  527. self::$_maxSocketNameLength + 2). str_pad(' ' . $worker->count, 9). " \033[32;40m [OK] \033[0m\n");
  528. }
  529. self::safeEcho("----------------------------------------------------------------\n");
  530. if (self::$daemonize) {
  531. global $argv;
  532. $start_file = $argv[0];
  533. self::safeEcho("Input \"php $start_file stop\" to quit. Start success.\n\n");
  534. } else {
  535. self::safeEcho("Press Ctrl-C to quit. Start success.\n");
  536. }
  537. }
  538. /**
  539. * Parse command.
  540. * php yourfile.php start | stop | restart | reload | status
  541. *
  542. * @return void
  543. */
  544. protected static function parseCommand()
  545. {
  546. global $argv;
  547. // Check argv;
  548. $start_file = $argv[0];
  549. $available_commands = array(
  550. 'start',
  551. 'stop',
  552. 'restart',
  553. 'reload',
  554. 'status',
  555. );
  556. if (!isset($argv[1]) || !in_array($argv[1], $available_commands)) {
  557. exit("Usage: php yourfile.php {" . implode('|', $available_commands) . "}\n");
  558. }
  559. // Get command.
  560. $command = trim($argv[1]);
  561. $command2 = isset($argv[2]) ? $argv[2] : '';
  562. // Start command.
  563. $mode = '';
  564. if ($command === 'start') {
  565. if ($command2 === '-d' || Worker::$daemonize) {
  566. $mode = 'in DAEMON mode';
  567. } else {
  568. $mode = 'in DEBUG mode';
  569. }
  570. }
  571. self::log("Workerman[$start_file] $command $mode");
  572. // Get master process PID.
  573. $master_pid = is_file(self::$pidFile) ? file_get_contents(self::$pidFile) : 0;
  574. $master_is_alive = $master_pid && @posix_kill($master_pid, 0) && posix_getpid() != $master_pid;
  575. // Master is still alive?
  576. if ($master_is_alive) {
  577. if ($command === 'start') {
  578. self::log("Workerman[$start_file] already running");
  579. exit;
  580. }
  581. } elseif ($command !== 'start' && $command !== 'restart') {
  582. self::log("Workerman[$start_file] not run");
  583. exit;
  584. }
  585. // execute command.
  586. switch ($command) {
  587. case 'start':
  588. if ($command2 === '-d') {
  589. Worker::$daemonize = true;
  590. }
  591. break;
  592. case 'status':
  593. if (is_file(self::$_statisticsFile)) {
  594. @unlink(self::$_statisticsFile);
  595. }
  596. // Master process will send status signal to all child processes.
  597. posix_kill($master_pid, SIGUSR2);
  598. // Waiting amoment.
  599. usleep(500000);
  600. // Display statisitcs data from a disk file.
  601. @readfile(self::$_statisticsFile);
  602. exit(0);
  603. case 'restart':
  604. case 'stop':
  605. self::log("Workerman[$start_file] is stoping ...");
  606. // Send stop signal to master process.
  607. $master_pid && posix_kill($master_pid, SIGINT);
  608. // Timeout.
  609. $timeout = 5;
  610. $start_time = time();
  611. // Check master process is still alive?
  612. while (1) {
  613. $master_is_alive = $master_pid && posix_kill($master_pid, 0);
  614. if ($master_is_alive) {
  615. // Timeout?
  616. if (time() - $start_time >= $timeout) {
  617. self::log("Workerman[$start_file] stop fail");
  618. exit;
  619. }
  620. // Waiting amoment.
  621. usleep(10000);
  622. continue;
  623. }
  624. // Stop success.
  625. self::log("Workerman[$start_file] stop success");
  626. if ($command === 'stop') {
  627. exit(0);
  628. }
  629. if ($command2 === '-d') {
  630. Worker::$daemonize = true;
  631. }
  632. break;
  633. }
  634. break;
  635. case 'reload':
  636. posix_kill($master_pid, SIGUSR1);
  637. self::log("Workerman[$start_file] reload");
  638. exit;
  639. default :
  640. exit("Usage: php yourfile.php {" . implode('|', $available_commands) . "}\n");
  641. }
  642. }
  643. /**
  644. * Install signal handler.
  645. *
  646. * @return void
  647. */
  648. protected static function installSignal()
  649. {
  650. // stop
  651. pcntl_signal(SIGINT, array('\Workerman\Worker', 'signalHandler'), false);
  652. // reload
  653. pcntl_signal(SIGUSR1, array('\Workerman\Worker', 'signalHandler'), false);
  654. // status
  655. pcntl_signal(SIGUSR2, array('\Workerman\Worker', 'signalHandler'), false);
  656. // ignore
  657. pcntl_signal(SIGPIPE, SIG_IGN, false);
  658. }
  659. /**
  660. * Reinstall signal handler.
  661. *
  662. * @return void
  663. */
  664. protected static function reinstallSignal()
  665. {
  666. // uninstall stop signal handler
  667. pcntl_signal(SIGINT, SIG_IGN, false);
  668. // uninstall reload signal handler
  669. pcntl_signal(SIGUSR1, SIG_IGN, false);
  670. // uninstall status signal handler
  671. pcntl_signal(SIGUSR2, SIG_IGN, false);
  672. // reinstall stop signal handler
  673. self::$globalEvent->add(SIGINT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  674. // reinstall reload signal handler
  675. self::$globalEvent->add(SIGUSR1, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  676. // reinstall status signal handler
  677. self::$globalEvent->add(SIGUSR2, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  678. }
  679. /**
  680. * Signal handler.
  681. *
  682. * @param int $signal
  683. */
  684. public static function signalHandler($signal)
  685. {
  686. switch ($signal) {
  687. // Stop.
  688. case SIGINT:
  689. self::stopAll();
  690. break;
  691. // Reload.
  692. case SIGUSR1:
  693. self::$_pidsToRestart = self::getAllWorkerPids();
  694. self::reload();
  695. break;
  696. // Show status.
  697. case SIGUSR2:
  698. self::writeStatisticsToStatusFile();
  699. break;
  700. }
  701. }
  702. /**
  703. * Run as deamon mode.
  704. *
  705. * @throws Exception
  706. */
  707. protected static function daemonize()
  708. {
  709. if (!self::$daemonize) {
  710. return;
  711. }
  712. umask(0);
  713. $pid = pcntl_fork();
  714. if (-1 === $pid) {
  715. throw new Exception('fork fail');
  716. } elseif ($pid > 0) {
  717. exit(0);
  718. }
  719. if (-1 === posix_setsid()) {
  720. throw new Exception("setsid fail");
  721. }
  722. // Fork again avoid SVR4 system regain the control of terminal.
  723. $pid = pcntl_fork();
  724. if (-1 === $pid) {
  725. throw new Exception("fork fail");
  726. } elseif (0 !== $pid) {
  727. exit(0);
  728. }
  729. }
  730. /**
  731. * Redirect standard input and output.
  732. *
  733. * @throws Exception
  734. */
  735. public static function resetStd()
  736. {
  737. if (!self::$daemonize) {
  738. return;
  739. }
  740. global $STDOUT, $STDERR;
  741. $handle = fopen(self::$stdoutFile, "a");
  742. if ($handle) {
  743. unset($handle);
  744. @fclose(STDOUT);
  745. @fclose(STDERR);
  746. $STDOUT = fopen(self::$stdoutFile, "a");
  747. $STDERR = fopen(self::$stdoutFile, "a");
  748. } else {
  749. throw new Exception('can not open stdoutFile ' . self::$stdoutFile);
  750. }
  751. }
  752. /**
  753. * Save pid.
  754. *
  755. * @throws Exception
  756. */
  757. protected static function saveMasterPid()
  758. {
  759. self::$_masterPid = posix_getpid();
  760. if (false === @file_put_contents(self::$pidFile, self::$_masterPid)) {
  761. throw new Exception('can not save pid to ' . self::$pidFile);
  762. }
  763. }
  764. /**
  765. * Get event loop name.
  766. *
  767. * @return string
  768. */
  769. protected static function getEventLoopName()
  770. {
  771. if (self::$eventLoopClass) {
  772. return self::$eventLoopClass;
  773. }
  774. $loop_name = '';
  775. foreach (self::$_availableEventLoops as $name=>$class) {
  776. if (extension_loaded($name)) {
  777. $loop_name = $name;
  778. break;
  779. }
  780. }
  781. if ($loop_name) {
  782. if (interface_exists('\React\EventLoop\LoopInterface')) {
  783. switch ($loop_name) {
  784. case 'libevent':
  785. self::$eventLoopClass = '\Workerman\Events\React\LibEventLoop';
  786. break;
  787. case 'event':
  788. self::$eventLoopClass = '\Workerman\Events\React\ExtEventLoop';
  789. break;
  790. default :
  791. self::$eventLoopClass = '\Workerman\Events\React\StreamSelectLoop';
  792. break;
  793. }
  794. } else {
  795. self::$eventLoopClass = self::$_availableEventLoops[$loop_name];
  796. }
  797. } else {
  798. self::$eventLoopClass = interface_exists('\React\EventLoop\LoopInterface')? '\Workerman\Events\React\StreamSelectLoop':'\Workerman\Events\Select';
  799. }
  800. return self::$eventLoopClass;
  801. }
  802. /**
  803. * Get all pids of worker processes.
  804. *
  805. * @return array
  806. */
  807. protected static function getAllWorkerPids()
  808. {
  809. $pid_array = array();
  810. foreach (self::$_pidMap as $worker_pid_array) {
  811. foreach ($worker_pid_array as $worker_pid) {
  812. $pid_array[$worker_pid] = $worker_pid;
  813. }
  814. }
  815. return $pid_array;
  816. }
  817. /**
  818. * Fork some worker processes.
  819. *
  820. * @return void
  821. */
  822. protected static function forkWorkers()
  823. {
  824. foreach (self::$_workers as $worker) {
  825. if (self::$_status === self::STATUS_STARTING) {
  826. if (empty($worker->name)) {
  827. $worker->name = $worker->getSocketName();
  828. }
  829. $worker_name_length = strlen($worker->name);
  830. if (self::$_maxWorkerNameLength < $worker_name_length) {
  831. self::$_maxWorkerNameLength = $worker_name_length;
  832. }
  833. }
  834. $worker->count = $worker->count <= 0 ? 1 : $worker->count;
  835. while (count(self::$_pidMap[$worker->workerId]) < $worker->count) {
  836. static::forkOneWorker($worker);
  837. }
  838. }
  839. }
  840. /**
  841. * Fork one worker process.
  842. *
  843. * @param Worker $worker
  844. * @throws Exception
  845. */
  846. protected static function forkOneWorker($worker)
  847. {
  848. // Get available worker id.
  849. $id = self::getId($worker->workerId, 0);
  850. if ($id === false) {
  851. return;
  852. }
  853. $pid = pcntl_fork();
  854. // For master process.
  855. if ($pid > 0) {
  856. self::$_pidMap[$worker->workerId][$pid] = $pid;
  857. self::$_idMap[$worker->workerId][$id] = $pid;
  858. } // For child processes.
  859. elseif (0 === $pid) {
  860. if ($worker->reusePort) {
  861. $worker->listen();
  862. }
  863. if (self::$_status === self::STATUS_STARTING) {
  864. self::resetStd();
  865. }
  866. self::$_pidMap = array();
  867. self::$_workers = array($worker->workerId => $worker);
  868. Timer::delAll();
  869. self::setProcessTitle('WorkerMan: worker process ' . $worker->name . ' ' . $worker->getSocketName());
  870. $worker->setUserAndGroup();
  871. $worker->id = $id;
  872. $worker->run();
  873. $err = new Exception('event-loop exited');
  874. self::log($err);
  875. exit(250);
  876. } else {
  877. throw new Exception("forkOneWorker fail");
  878. }
  879. }
  880. /**
  881. * Get worker id.
  882. *
  883. * @param int $worker_id
  884. * @param int $pid
  885. */
  886. protected static function getId($worker_id, $pid)
  887. {
  888. return array_search($pid, self::$_idMap[$worker_id]);
  889. }
  890. /**
  891. * Set unix user and group for current process.
  892. *
  893. * @return void
  894. */
  895. public function setUserAndGroup()
  896. {
  897. // Get uid.
  898. $user_info = posix_getpwnam($this->user);
  899. if (!$user_info) {
  900. self::log("Warning: User {$this->user} not exsits");
  901. return;
  902. }
  903. $uid = $user_info['uid'];
  904. // Get gid.
  905. if ($this->group) {
  906. $group_info = posix_getgrnam($this->group);
  907. if (!$group_info) {
  908. self::log("Warning: Group {$this->group} not exsits");
  909. return;
  910. }
  911. $gid = $group_info['gid'];
  912. } else {
  913. $gid = $user_info['gid'];
  914. }
  915. // Set uid and gid.
  916. if ($uid != posix_getuid() || $gid != posix_getgid()) {
  917. if (!posix_setgid($gid) || !posix_initgroups($user_info['name'], $gid) || !posix_setuid($uid)) {
  918. self::log("Warning: change gid or uid fail.");
  919. }
  920. }
  921. }
  922. /**
  923. * Set process name.
  924. *
  925. * @param string $title
  926. * @return void
  927. */
  928. protected static function setProcessTitle($title)
  929. {
  930. // >=php 5.5
  931. if (function_exists('cli_set_process_title')) {
  932. @cli_set_process_title($title);
  933. } // Need proctitle when php<=5.5 .
  934. elseif (extension_loaded('proctitle') && function_exists('setproctitle')) {
  935. @setproctitle($title);
  936. }
  937. }
  938. /**
  939. * Monitor all child processes.
  940. *
  941. * @return void
  942. */
  943. protected static function monitorWorkers()
  944. {
  945. self::$_status = self::STATUS_RUNNING;
  946. while (1) {
  947. // Calls signal handlers for pending signals.
  948. pcntl_signal_dispatch();
  949. // Suspends execution of the current process until a child has exited, or until a signal is delivered
  950. $status = 0;
  951. $pid = pcntl_wait($status, WUNTRACED);
  952. // Calls signal handlers for pending signals again.
  953. pcntl_signal_dispatch();
  954. // If a child has already exited.
  955. if ($pid > 0) {
  956. // Find out witch worker process exited.
  957. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  958. if (isset($worker_pid_array[$pid])) {
  959. $worker = self::$_workers[$worker_id];
  960. // Exit status.
  961. if ($status !== 0) {
  962. self::log("worker[" . $worker->name . ":$pid] exit with status $status");
  963. }
  964. // For Statistics.
  965. if (!isset(self::$_globalStatistics['worker_exit_info'][$worker_id][$status])) {
  966. self::$_globalStatistics['worker_exit_info'][$worker_id][$status] = 0;
  967. }
  968. self::$_globalStatistics['worker_exit_info'][$worker_id][$status]++;
  969. // Clear process data.
  970. unset(self::$_pidMap[$worker_id][$pid]);
  971. // Mark id is available.
  972. $id = self::getId($worker_id, $pid);
  973. self::$_idMap[$worker_id][$id] = 0;
  974. break;
  975. }
  976. }
  977. // Is still running state then fork a new worker process.
  978. if (self::$_status !== self::STATUS_SHUTDOWN) {
  979. self::forkWorkers();
  980. // If reloading continue.
  981. if (isset(self::$_pidsToRestart[$pid])) {
  982. unset(self::$_pidsToRestart[$pid]);
  983. self::reload();
  984. }
  985. } else {
  986. // If shutdown state and all child processes exited then master process exit.
  987. if (!self::getAllWorkerPids()) {
  988. self::exitAndClearAll();
  989. }
  990. }
  991. } else {
  992. // If shutdown state and all child processes exited then master process exit.
  993. if (self::$_status === self::STATUS_SHUTDOWN && !self::getAllWorkerPids()) {
  994. self::exitAndClearAll();
  995. }
  996. }
  997. }
  998. }
  999. /**
  1000. * Exit current process.
  1001. *
  1002. * @return void
  1003. */
  1004. protected static function exitAndClearAll()
  1005. {
  1006. foreach (self::$_workers as $worker) {
  1007. $socket_name = $worker->getSocketName();
  1008. if ($worker->transport === 'unix' && $socket_name) {
  1009. list(, $address) = explode(':', $socket_name, 2);
  1010. @unlink($address);
  1011. }
  1012. }
  1013. @unlink(self::$pidFile);
  1014. self::log("Workerman[" . basename(self::$_startFile) . "] has been stopped");
  1015. if (self::$onMasterStop) {
  1016. call_user_func(self::$onMasterStop);
  1017. }
  1018. exit(0);
  1019. }
  1020. /**
  1021. * Execute reload.
  1022. *
  1023. * @return void
  1024. */
  1025. protected static function reload()
  1026. {
  1027. // For master process.
  1028. if (self::$_masterPid === posix_getpid()) {
  1029. // Set reloading state.
  1030. if (self::$_status !== self::STATUS_RELOADING && self::$_status !== self::STATUS_SHUTDOWN) {
  1031. self::log("Workerman[" . basename(self::$_startFile) . "] reloading");
  1032. self::$_status = self::STATUS_RELOADING;
  1033. // Try to emit onMasterReload callback.
  1034. if (self::$onMasterReload) {
  1035. try {
  1036. call_user_func(self::$onMasterReload);
  1037. } catch (\Exception $e) {
  1038. self::log($e);
  1039. exit(250);
  1040. } catch (\Error $e) {
  1041. self::log($e);
  1042. exit(250);
  1043. }
  1044. self::initId();
  1045. }
  1046. }
  1047. // Send reload signal to all child processes.
  1048. $reloadable_pid_array = array();
  1049. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  1050. $worker = self::$_workers[$worker_id];
  1051. if ($worker->reloadable) {
  1052. foreach ($worker_pid_array as $pid) {
  1053. $reloadable_pid_array[$pid] = $pid;
  1054. }
  1055. } else {
  1056. foreach ($worker_pid_array as $pid) {
  1057. // Send reload signal to a worker process which reloadable is false.
  1058. posix_kill($pid, SIGUSR1);
  1059. }
  1060. }
  1061. }
  1062. // Get all pids that are waiting reload.
  1063. self::$_pidsToRestart = array_intersect(self::$_pidsToRestart, $reloadable_pid_array);
  1064. // Reload complete.
  1065. if (empty(self::$_pidsToRestart)) {
  1066. if (self::$_status !== self::STATUS_SHUTDOWN) {
  1067. self::$_status = self::STATUS_RUNNING;
  1068. }
  1069. return;
  1070. }
  1071. // Continue reload.
  1072. $one_worker_pid = current(self::$_pidsToRestart);
  1073. // Send reload signal to a worker process.
  1074. posix_kill($one_worker_pid, SIGUSR1);
  1075. // If the process does not exit after self::KILL_WORKER_TIMER_TIME seconds try to kill it.
  1076. Timer::add(self::KILL_WORKER_TIMER_TIME, 'posix_kill', array($one_worker_pid, SIGKILL), false);
  1077. } // For child processes.
  1078. else {
  1079. $worker = current(self::$_workers);
  1080. // Try to emit onWorkerReload callback.
  1081. if ($worker->onWorkerReload) {
  1082. try {
  1083. call_user_func($worker->onWorkerReload, $worker);
  1084. } catch (\Exception $e) {
  1085. self::log($e);
  1086. exit(250);
  1087. } catch (\Error $e) {
  1088. self::log($e);
  1089. exit(250);
  1090. }
  1091. }
  1092. if ($worker->reloadable) {
  1093. self::stopAll();
  1094. }
  1095. }
  1096. }
  1097. /**
  1098. * Stop.
  1099. *
  1100. * @return void
  1101. */
  1102. public static function stopAll()
  1103. {
  1104. self::$_status = self::STATUS_SHUTDOWN;
  1105. // For master process.
  1106. if (self::$_masterPid === posix_getpid()) {
  1107. self::log("Workerman[" . basename(self::$_startFile) . "] Stopping ...");
  1108. $worker_pid_array = self::getAllWorkerPids();
  1109. // Send stop signal to all child processes.
  1110. foreach ($worker_pid_array as $worker_pid) {
  1111. posix_kill($worker_pid, SIGINT);
  1112. Timer::add(self::KILL_WORKER_TIMER_TIME, 'posix_kill', array($worker_pid, SIGKILL), false);
  1113. }
  1114. // Remove statistics file.
  1115. if (is_file(self::$_statisticsFile)) {
  1116. @unlink(self::$_statisticsFile);
  1117. }
  1118. } // For child processes.
  1119. else {
  1120. // Execute exit.
  1121. foreach (self::$_workers as $worker) {
  1122. $worker->stop();
  1123. }
  1124. self::$globalEvent->destroy();
  1125. exit(0);
  1126. }
  1127. }
  1128. /**
  1129. * Write statistics data to disk.
  1130. *
  1131. * @return void
  1132. */
  1133. protected static function writeStatisticsToStatusFile()
  1134. {
  1135. // For master process.
  1136. if (self::$_masterPid === posix_getpid()) {
  1137. $loadavg = function_exists('sys_getloadavg') ? array_map('round', sys_getloadavg(), array(2)) : array('-', '-', '-');
  1138. file_put_contents(self::$_statisticsFile,
  1139. "---------------------------------------GLOBAL STATUS--------------------------------------------\n");
  1140. file_put_contents(self::$_statisticsFile,
  1141. 'Workerman version:' . Worker::VERSION . " PHP version:" . PHP_VERSION . "\n", FILE_APPEND);
  1142. file_put_contents(self::$_statisticsFile, 'start time:' . date('Y-m-d H:i:s',
  1143. self::$_globalStatistics['start_timestamp']) . ' run ' . floor((time() - self::$_globalStatistics['start_timestamp']) / (24 * 60 * 60)) . ' days ' . floor(((time() - self::$_globalStatistics['start_timestamp']) % (24 * 60 * 60)) / (60 * 60)) . " hours \n",
  1144. FILE_APPEND);
  1145. $load_str = 'load average: ' . implode(", ", $loadavg);
  1146. file_put_contents(self::$_statisticsFile,
  1147. str_pad($load_str, 33) . 'event-loop:' . self::getEventLoopName() . "\n", FILE_APPEND);
  1148. file_put_contents(self::$_statisticsFile,
  1149. count(self::$_pidMap) . ' workers ' . count(self::getAllWorkerPids()) . " processes\n",
  1150. FILE_APPEND);
  1151. file_put_contents(self::$_statisticsFile,
  1152. str_pad('worker_name', self::$_maxWorkerNameLength) . " exit_status exit_count\n", FILE_APPEND);
  1153. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  1154. $worker = self::$_workers[$worker_id];
  1155. if (isset(self::$_globalStatistics['worker_exit_info'][$worker_id])) {
  1156. foreach (self::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
  1157. file_put_contents(self::$_statisticsFile,
  1158. str_pad($worker->name, self::$_maxWorkerNameLength) . " " . str_pad($worker_exit_status,
  1159. 16) . " $worker_exit_count\n", FILE_APPEND);
  1160. }
  1161. } else {
  1162. file_put_contents(self::$_statisticsFile,
  1163. str_pad($worker->name, self::$_maxWorkerNameLength) . " " . str_pad(0, 16) . " 0\n",
  1164. FILE_APPEND);
  1165. }
  1166. }
  1167. file_put_contents(self::$_statisticsFile,
  1168. "---------------------------------------PROCESS STATUS-------------------------------------------\n",
  1169. FILE_APPEND);
  1170. file_put_contents(self::$_statisticsFile,
  1171. "pid\tmemory " . str_pad('listening', self::$_maxSocketNameLength) . " " . str_pad('worker_name',
  1172. self::$_maxWorkerNameLength) . " connections " . str_pad('total_request',
  1173. 13) . " " . str_pad('send_fail', 9) . " " . str_pad('throw_exception', 15) . "\n", FILE_APPEND);
  1174. chmod(self::$_statisticsFile, 0722);
  1175. foreach (self::getAllWorkerPids() as $worker_pid) {
  1176. posix_kill($worker_pid, SIGUSR2);
  1177. }
  1178. return;
  1179. }
  1180. // For child processes.
  1181. /** @var Worker $worker */
  1182. $worker = current(self::$_workers);
  1183. $worker_status_str = posix_getpid() . "\t" . str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M",
  1184. 7) . " " . str_pad($worker->getSocketName(),
  1185. self::$_maxSocketNameLength) . " " . str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name),
  1186. self::$_maxWorkerNameLength) . " ";
  1187. $worker_status_str .= str_pad(ConnectionInterface::$statistics['connection_count'],
  1188. 11) . " " . str_pad(ConnectionInterface::$statistics['total_request'],
  1189. 14) . " " . str_pad(ConnectionInterface::$statistics['send_fail'],
  1190. 9) . " " . str_pad(ConnectionInterface::$statistics['throw_exception'], 15) . "\n";
  1191. file_put_contents(self::$_statisticsFile, $worker_status_str, FILE_APPEND);
  1192. }
  1193. /**
  1194. * Check errors when current process exited.
  1195. *
  1196. * @return void
  1197. */
  1198. public static function checkErrors()
  1199. {
  1200. if (self::STATUS_SHUTDOWN != self::$_status) {
  1201. $error_msg = 'Worker['. posix_getpid() .'] process terminated with ';
  1202. $errors = error_get_last();
  1203. if ($errors && ($errors['type'] === E_ERROR ||
  1204. $errors['type'] === E_PARSE ||
  1205. $errors['type'] === E_CORE_ERROR ||
  1206. $errors['type'] === E_COMPILE_ERROR ||
  1207. $errors['type'] === E_RECOVERABLE_ERROR)
  1208. ) {
  1209. $error_msg .= self::getErrorType($errors['type']) . " \"{$errors['message']} in {$errors['file']} on line {$errors['line']}\"";
  1210. } else {
  1211. $error_msg .= 'exit()/die(). Please do not call exit()/die() in workerman.';
  1212. }
  1213. self::log($error_msg);
  1214. }
  1215. }
  1216. /**
  1217. * Get error message by error code.
  1218. *
  1219. * @param integer $type
  1220. * @return string
  1221. */
  1222. protected static function getErrorType($type)
  1223. {
  1224. switch ($type) {
  1225. case E_ERROR: // 1 //
  1226. return 'E_ERROR';
  1227. case E_WARNING: // 2 //
  1228. return 'E_WARNING';
  1229. case E_PARSE: // 4 //
  1230. return 'E_PARSE';
  1231. case E_NOTICE: // 8 //
  1232. return 'E_NOTICE';
  1233. case E_CORE_ERROR: // 16 //
  1234. return 'E_CORE_ERROR';
  1235. case E_CORE_WARNING: // 32 //
  1236. return 'E_CORE_WARNING';
  1237. case E_COMPILE_ERROR: // 64 //
  1238. return 'E_COMPILE_ERROR';
  1239. case E_COMPILE_WARNING: // 128 //
  1240. return 'E_COMPILE_WARNING';
  1241. case E_USER_ERROR: // 256 //
  1242. return 'E_USER_ERROR';
  1243. case E_USER_WARNING: // 512 //
  1244. return 'E_USER_WARNING';
  1245. case E_USER_NOTICE: // 1024 //
  1246. return 'E_USER_NOTICE';
  1247. case E_STRICT: // 2048 //
  1248. return 'E_STRICT';
  1249. case E_RECOVERABLE_ERROR: // 4096 //
  1250. return 'E_RECOVERABLE_ERROR';
  1251. case E_DEPRECATED: // 8192 //
  1252. return 'E_DEPRECATED';
  1253. case E_USER_DEPRECATED: // 16384 //
  1254. return 'E_USER_DEPRECATED';
  1255. }
  1256. return "";
  1257. }
  1258. /**
  1259. * Log.
  1260. *
  1261. * @param string $msg
  1262. * @return void
  1263. */
  1264. public static function log($msg)
  1265. {
  1266. $msg = $msg . "\n";
  1267. if (!self::$daemonize) {
  1268. self::safeEcho($msg);
  1269. }
  1270. file_put_contents((string)self::$logFile, date('Y-m-d H:i:s') . ' ' . 'pid:'. posix_getpid() . ' ' . $msg, FILE_APPEND | LOCK_EX);
  1271. }
  1272. /**
  1273. * Safe Echo.
  1274. *
  1275. * @param $msg
  1276. */
  1277. public static function safeEcho($msg)
  1278. {
  1279. if (!function_exists('posix_isatty') || posix_isatty(STDOUT)) {
  1280. echo $msg;
  1281. }
  1282. }
  1283. /**
  1284. * Construct.
  1285. *
  1286. * @param string $socket_name
  1287. * @param array $context_option
  1288. */
  1289. public function __construct($socket_name = '', $context_option = array())
  1290. {
  1291. // Save all worker instances.
  1292. $this->workerId = spl_object_hash($this);
  1293. self::$_workers[$this->workerId] = $this;
  1294. self::$_pidMap[$this->workerId] = array();
  1295. // Get autoload root path.
  1296. $backtrace = debug_backtrace();
  1297. $this->_autoloadRootPath = dirname($backtrace[0]['file']);
  1298. // Context for socket.
  1299. if ($socket_name) {
  1300. $this->_socketName = $socket_name;
  1301. if (!isset($context_option['socket']['backlog'])) {
  1302. $context_option['socket']['backlog'] = self::DEFAULT_BACKLOG;
  1303. }
  1304. $this->_context = stream_context_create($context_option);
  1305. }
  1306. // Set an empty onMessage callback.
  1307. $this->onMessage = function () {
  1308. };
  1309. }
  1310. /**
  1311. * Listen port.
  1312. *
  1313. * @throws Exception
  1314. */
  1315. public function listen()
  1316. {
  1317. if (!$this->_socketName || $this->_mainSocket) {
  1318. return;
  1319. }
  1320. // Autoload.
  1321. Autoloader::setRootPath($this->_autoloadRootPath);
  1322. // Get the application layer communication protocol and listening address.
  1323. list($scheme, $address) = explode(':', $this->_socketName, 2);
  1324. // Check application layer protocol class.
  1325. if (!isset(self::$_builtinTransports[$scheme])) {
  1326. if(class_exists($scheme)){
  1327. $this->protocol = $scheme;
  1328. } else {
  1329. $scheme = ucfirst($scheme);
  1330. $this->protocol = '\\Protocols\\' . $scheme;
  1331. if (!class_exists($this->protocol)) {
  1332. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  1333. if (!class_exists($this->protocol)) {
  1334. throw new Exception("class \\Protocols\\$scheme not exist");
  1335. }
  1336. }
  1337. }
  1338. if (!isset(self::$_builtinTransports[$this->transport])) {
  1339. throw new \Exception('Bad worker->transport ' . var_export($this->transport, true));
  1340. }
  1341. } else {
  1342. $this->transport = $scheme;
  1343. }
  1344. $local_socket = self::$_builtinTransports[$this->transport] . ":" . $address;
  1345. // Flag.
  1346. $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
  1347. $errno = 0;
  1348. $errmsg = '';
  1349. // SO_REUSEPORT.
  1350. if ($this->reusePort) {
  1351. stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
  1352. }
  1353. // Create an Internet or Unix domain server socket.
  1354. $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context);
  1355. if (!$this->_mainSocket) {
  1356. throw new Exception($errmsg);
  1357. }
  1358. if ($this->transport === 'ssl') {
  1359. stream_socket_enable_crypto($this->_mainSocket, false);
  1360. }
  1361. // Try to open keepalive for tcp and disable Nagle algorithm.
  1362. if (function_exists('socket_import_stream') && self::$_builtinTransports[$this->transport] === 'tcp') {
  1363. $socket = socket_import_stream($this->_mainSocket);
  1364. @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
  1365. @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
  1366. }
  1367. // Non blocking.
  1368. stream_set_blocking($this->_mainSocket, 0);
  1369. // Register a listener to be notified when server socket is ready to read.
  1370. if (self::$globalEvent) {
  1371. if ($this->transport !== 'udp') {
  1372. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptConnection'));
  1373. } else {
  1374. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1375. array($this, 'acceptUdpConnection'));
  1376. }
  1377. }
  1378. }
  1379. /**
  1380. * Get socket name.
  1381. *
  1382. * @return string
  1383. */
  1384. public function getSocketName()
  1385. {
  1386. return $this->_socketName ? lcfirst($this->_socketName) : 'none';
  1387. }
  1388. /**
  1389. * Run worker instance.
  1390. *
  1391. * @return void
  1392. */
  1393. public function run()
  1394. {
  1395. //Update process state.
  1396. self::$_status = self::STATUS_RUNNING;
  1397. // Register shutdown function for checking errors.
  1398. register_shutdown_function(array("\\Workerman\\Worker", 'checkErrors'));
  1399. // Set autoload root path.
  1400. Autoloader::setRootPath($this->_autoloadRootPath);
  1401. // Create a global event loop.
  1402. if (!self::$globalEvent) {
  1403. $event_loop_class = self::getEventLoopName();
  1404. self::$globalEvent = new $event_loop_class;
  1405. // Register a listener to be notified when server socket is ready to read.
  1406. if ($this->_socketName) {
  1407. if ($this->transport !== 'udp') {
  1408. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1409. array($this, 'acceptConnection'));
  1410. } else {
  1411. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1412. array($this, 'acceptUdpConnection'));
  1413. }
  1414. }
  1415. }
  1416. // Reinstall signal.
  1417. self::reinstallSignal();
  1418. // Init Timer.
  1419. Timer::init(self::$globalEvent);
  1420. // Try to emit onWorkerStart callback.
  1421. if ($this->onWorkerStart) {
  1422. try {
  1423. call_user_func($this->onWorkerStart, $this);
  1424. } catch (\Exception $e) {
  1425. self::log($e);
  1426. // Avoid rapid infinite loop exit.
  1427. sleep(1);
  1428. exit(250);
  1429. } catch (\Error $e) {
  1430. self::log($e);
  1431. // Avoid rapid infinite loop exit.
  1432. sleep(1);
  1433. exit(250);
  1434. }
  1435. }
  1436. // Main loop.
  1437. self::$globalEvent->loop();
  1438. }
  1439. /**
  1440. * Stop current worker instance.
  1441. *
  1442. * @return void
  1443. */
  1444. public function stop()
  1445. {
  1446. // Try to emit onWorkerStop callback.
  1447. if ($this->onWorkerStop) {
  1448. try {
  1449. call_user_func($this->onWorkerStop, $this);
  1450. } catch (\Exception $e) {
  1451. self::log($e);
  1452. exit(250);
  1453. } catch (\Error $e) {
  1454. self::log($e);
  1455. exit(250);
  1456. }
  1457. }
  1458. // Remove listener for server socket.
  1459. self::$globalEvent->del($this->_mainSocket, EventInterface::EV_READ);
  1460. @fclose($this->_mainSocket);
  1461. }
  1462. /**
  1463. * Accept a connection.
  1464. *
  1465. * @param resource $socket
  1466. * @return void
  1467. */
  1468. public function acceptConnection($socket)
  1469. {
  1470. // Accept a connection on server socket.
  1471. $new_socket = @stream_socket_accept($socket, 0, $remote_address);
  1472. // Thundering herd.
  1473. if (!$new_socket) {
  1474. return;
  1475. }
  1476. // TcpConnection.
  1477. $connection = new TcpConnection($new_socket, $remote_address);
  1478. $this->connections[$connection->id] = $connection;
  1479. $connection->worker = $this;
  1480. $connection->protocol = $this->protocol;
  1481. $connection->transport = $this->transport;
  1482. $connection->onMessage = $this->onMessage;
  1483. $connection->onClose = $this->onClose;
  1484. $connection->onError = $this->onError;
  1485. $connection->onBufferDrain = $this->onBufferDrain;
  1486. $connection->onBufferFull = $this->onBufferFull;
  1487. // Try to emit onConnect callback.
  1488. if ($this->onConnect) {
  1489. try {
  1490. call_user_func($this->onConnect, $connection);
  1491. } catch (\Exception $e) {
  1492. self::log($e);
  1493. exit(250);
  1494. } catch (\Error $e) {
  1495. self::log($e);
  1496. exit(250);
  1497. }
  1498. }
  1499. }
  1500. /**
  1501. * For udp package.
  1502. *
  1503. * @param resource $socket
  1504. * @return bool
  1505. */
  1506. public function acceptUdpConnection($socket)
  1507. {
  1508. $recv_buffer = stream_socket_recvfrom($socket, self::MAX_UDP_PACKAGE_SIZE, 0, $remote_address);
  1509. if (false === $recv_buffer || empty($remote_address)) {
  1510. return false;
  1511. }
  1512. // UdpConnection.
  1513. $connection = new UdpConnection($socket, $remote_address);
  1514. $connection->protocol = $this->protocol;
  1515. if ($this->onMessage) {
  1516. if ($this->protocol) {
  1517. $parser = $this->protocol;
  1518. $recv_buffer = $parser::decode($recv_buffer, $connection);
  1519. // Discard bad packets.
  1520. if ($recv_buffer === false)
  1521. return true;
  1522. }
  1523. ConnectionInterface::$statistics['total_request']++;
  1524. try {
  1525. call_user_func($this->onMessage, $connection, $recv_buffer);
  1526. } catch (\Exception $e) {
  1527. self::log($e);
  1528. exit(250);
  1529. } catch (\Error $e) {
  1530. self::log($e);
  1531. exit(250);
  1532. }
  1533. }
  1534. return true;
  1535. }
  1536. }