Worker.php 49 KB

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